├── .gitignore ├── BitManipulation ├── SingleNumber.cpp ├── BitCounter.cpp ├── ReverseBits.cpp ├── CountingBits.cpp └── SubsetXORSum.cpp ├── Sorting ├── ValidAnagram.cpp ├── BubbleSort.cpp ├── InsertSort.cpp ├── ColorSorter.cpp ├── TwoSumLessThanK.cpp ├── MinDiff.cpp ├── QuickSort.cpp ├── HeapSort.cpp └── HighFive.cpp ├── Array ├── CreateTargetArray │ ├── go │ │ ├── CreateTargetArray.go │ │ └── CreateTargetArray_test.go │ └── cpp │ │ └── CreateTargetArray.cpp ├── DecompressRLE │ ├── go │ │ ├── DecompressRLE.go │ │ └── DecompressRLE_test.go │ ├── cpp │ │ └── DecompressRLE.cpp │ └── Problem.md ├── MissingNumber.cpp ├── MakeTwoArraysEqual │ ├── go │ │ ├── MakeTwoArraysEqual.go │ │ └── MakeTwoArraysEqual_test.go │ ├── cpp │ │ └── MakeTwoArraysEqual.cpp │ └── Problem.md ├── NumberOfCandies.cpp ├── RunningSum.cpp ├── ConsecutiveOnes │ ├── cpp │ │ └── ConsecutiveOnes.cpp │ ├── Problem.md │ └── go │ │ ├── ConsecutiveOnes.go │ │ └── ConsecutiveOnes_test.go ├── LCISFinder │ ├── cpp │ │ └── LCISFinder.cpp │ ├── go │ │ ├── LCISFinder_test.go │ │ └── LCISFinder.go │ └── Problem.md ├── LineChecker │ ├── go │ │ ├── LineChecker.go │ │ └── LineChecker_test.go │ ├── Problem.md │ └── cpp │ │ └── LineChecker.cpp ├── ArraysIntersection │ ├── Problem.md │ └── cpp │ │ └── ArraysIntersection.cpp ├── ArrayIntersection │ ├── Problem.md │ ├── cpp │ │ └── ArrayIntersection.cpp │ └── go │ │ ├── ArrayIntersection_test.go │ │ └── ArrayIntersection.go ├── HIndexCalculator │ ├── cpp │ │ └── HIndexCalculator.cpp │ ├── go │ │ ├── HIndexCalculator.go │ │ └── HIndexCalculator_test.go │ └── Problem.md ├── MidIndexFinder.cpp ├── IsMonotone │ ├── cpp │ │ └── IsMonotone.cpp │ ├── Problem.md │ └── go │ │ ├── IsMonotone.go │ │ └── IsMonotone_test.go ├── GoodPairs │ ├── Problem.md │ ├── cpp │ │ └── GoodPairs.cpp │ └── go │ │ └── GoodPairs.go ├── PlusOne.cpp ├── MergeSortedArray │ ├── go │ │ └── MergeSortedArray.go │ └── cpp │ │ └── MergeSortedArray.cpp ├── AddToArrayForm │ ├── Problem.md │ ├── go │ │ └── AddToArrayForm.go │ └── cpp │ │ └── AddToArrayForm.cpp ├── ShiftingLetters.cpp ├── FixedPoint │ ├── go │ │ ├── FixedPoint.go │ │ └── FixedPoint_test.go │ ├── Problem.md │ └── cpp │ │ └── FixedPoint.cpp ├── RangeSumQuery.cpp ├── MoveZeroes.cpp ├── ThirdMaxFinder.cpp ├── SortArrayByParity.cpp ├── KthPositiveElement │ ├── Problem.md │ ├── cpp │ │ └── KthPositiveElement.cpp │ └── go │ │ ├── KthPositiveElement_test.go │ │ └── KthPositiveElement.go ├── RotateArray.cpp ├── IntervalListIntersections │ ├── go │ │ └── IntervalListIntersections.go │ ├── Problem.md │ └── cpp │ │ └── IntervalListIntersections.cpp ├── SortByIncreasingFrequency.cpp ├── MissingRangeFinder.cpp └── ProductExceptSelf.cpp ├── String ├── ShuffleString.cpp ├── LastWordLength.cpp ├── IPAddrDefanger.cpp ├── ReverseString.cpp ├── LongestUncommonSubsequence.cpp ├── RansomNote.cpp ├── PalindromePermutation.cpp ├── VowelRemover.cpp ├── ExcelSheetColumnTitle.cpp ├── BackspaceCompare.cpp ├── IsSubsequence.cpp ├── OrderlyQueue.cpp ├── WordComparator.cpp ├── AddBinary.cpp ├── LongestCommonPrefixFinder.cpp ├── StringDifference.cpp ├── ReverseVowels.cpp ├── ValidPalindrome.cpp ├── AddString.cpp ├── IsomorphicString.cpp ├── GoatLatin.cpp ├── BuddyStringFinder.cpp └── StringFinder.cpp ├── DynamicProgramming ├── NTribonacci.cpp ├── FibonacciNumber.cpp ├── ClimbingStairs.cpp ├── DivisorGame.cpp ├── MinMostClimbingStairs.cpp ├── IsSubsequence.cpp ├── GetMaxGeneratedArray.cpp ├── PascalTriangle.cpp ├── MaxSubArray.cpp ├── PalindromeValidator.cpp ├── FirstBadVersion.cpp ├── UniquePaths.cpp ├── EggDrop.cpp ├── CountSortedVowelStrings.cpp ├── CountDifferSubstrings.cpp ├── DecodeWays.cpp ├── MinCostTickets.cpp ├── PartitionEqualSubsetSum.cpp ├── PalindromicSubstrings.cpp ├── TargetSum.cpp └── WordBreak.cpp ├── HashTable ├── MissingNumber.cpp ├── DuplicateFinder.cpp ├── ContinuousSubarraySum.cpp ├── JewelStoneCounter.cpp ├── MajorityElement.cpp ├── SubarraySum.cpp ├── NumberMatchingSubsequences.cpp ├── DuplicateRemover.cpp ├── FindUniqueCharacter.cpp ├── HitCounter.cpp ├── GroupAnagrams.cpp ├── TimeMap.cpp ├── UncommonWords.cpp ├── AlienDictionaryValidator.cpp ├── OrderedStream.cpp ├── Logger.cpp ├── TwoSumStream.cpp └── TwoSum.cpp ├── Heap ├── KLargestElement.cpp ├── KSmallestElementMatrix.cpp ├── LastStoneWeight.cpp ├── KthLargestFromStream.cpp ├── KClosestPointsToOrigin.cpp ├── MedianFinder.cpp ├── SortCharactersByFrequency.cpp └── KFrequentElement.cpp ├── Miscellaneous ├── ValidParantheses.cpp ├── ValidPerfectSquare.cpp ├── FizzBuzz.cpp ├── ReverseInteger.cpp ├── StrobogrammaticNumber.cpp ├── NumTeams.cpp ├── RomanToInteger.cpp ├── LongestConsecutiveSequence.cpp └── MovingAverage.cpp ├── Search ├── SearchInsertPosition.cpp ├── FindMinRotatedSortedArray.cpp └── BinarySearch.cpp ├── Matrix ├── ToeplitzMatrix.cpp ├── RichestCustomerWealth.cpp ├── MinimumPathSum.cpp ├── IslandPerimeter.cpp └── BestMeetingSpot.cpp ├── LinkedList ├── ListReverse.cpp ├── SwapNodesInPairs.cpp ├── CycleDetector.cpp ├── FindMid.cpp ├── ListMerger.cpp ├── DeleteNode.cpp ├── BinaryTreeToDoublyLinkedList.cpp ├── LinkedListIntersection.cpp ├── PalindromeLinkedList.cpp └── TwoNumbersList.cpp ├── Greedy ├── MaxWaterContainer.cpp ├── MaximumScore.cpp ├── StockStrategy.cpp ├── CanPlaceFlowers.cpp └── MaximumUnitsTruck.cpp ├── Stack ├── RemoveDuplicates.cpp ├── MaxNestingDepth.cpp ├── CrawlerLogFolder.cpp ├── ValidParantheses.cpp ├── MakeStringGreat.cpp ├── MinStack.cpp ├── AsteroidCollision.cpp └── MakeStringValid.cpp ├── Tree ├── MaxDepth.cpp ├── TreeComparator.cpp ├── InvertBinaryTree.cpp ├── MergeBinaryTrees.cpp ├── BinaryTreeTilt.cpp ├── RangeSumBST.cpp ├── BalancedTreeValidator.cpp ├── PathSum.cpp ├── PreOrderTraversal.cpp ├── IncreasingOrderSearchTree.cpp ├── ConvertToBST.cpp ├── RemoveNthNodeFromEndOfList.cpp ├── ElementsInBinaryTrees.cpp ├── MinDepth.cpp ├── BinaryTreeDiameter.cpp ├── SubtreeCheck.cpp ├── ClosestBinarySearchTreeValue.cpp └── BinaryTreeMaximumPathSum.cpp ├── Graph ├── MinimumVerticesToNodes.cpp ├── FindTownJudge.cpp ├── KeysAndRooms.cpp ├── FindCenterOfGraph.cpp ├── EmployeeImportance.cpp ├── NumberProvinces.cpp ├── FindIfPathExists.cpp ├── ParallelCourses.cpp ├── PathsFromSourceToTarget.cpp ├── TilePossibilities.cpp └── GraphValidTree.cpp ├── Concurrency ├── SyncExecutor.cpp └── ReaderWriterLock.cpp ├── Backtracking ├── ParanthesesGenerator.cpp ├── Combinations.cpp └── GenerateSubsets.cpp └── Intervals └── MeetingRooms.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | -------------------------------------------------------------------------------- /BitManipulation/SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/single-number/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class SingleNumber { 8 | public: 9 | int singleNumber(vector& nums) { 10 | int result = 0; 11 | for (int& i : nums) result = result ^ i; 12 | return result; 13 | } 14 | }; -------------------------------------------------------------------------------- /Sorting/ValidAnagram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class ValidAnagram { 7 | public: 8 | bool isAnagram(string s, string t) { 9 | if (s.size() != t.size()) return false; 10 | sort(s.begin(), s.end()); 11 | sort(t.begin(), t.end()); 12 | return s == t; 13 | } 14 | }; -------------------------------------------------------------------------------- /Array/CreateTargetArray/go/CreateTargetArray.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // Time: O(n^2) as copy is O(n) 4 | // Space: O(1) 5 | func createTargetArray(nums []int, index []int) []int { 6 | res := make([]int, len(nums)) 7 | for i := 0; i < len(nums); i++ { 8 | if index[i] <= i { 9 | copy(res[index[i]+1:], res[index[i]:]) 10 | } 11 | res[index[i]] = nums[i] 12 | } 13 | return res 14 | } 15 | -------------------------------------------------------------------------------- /String/ShuffleString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class ShuffleString { 7 | public: 8 | string restoreString(string s, vector& indices) { 9 | string output = s; 10 | for (int index = 0; index < indices.size(); ++index){ 11 | output[indices[index]] = s[index]; 12 | } 13 | return output; 14 | } 15 | }; -------------------------------------------------------------------------------- /Array/DecompressRLE/go/DecompressRLE.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // deCompressRLE : iterate through the freq and append to array 4 | // Time: O(n) 5 | // Space: O(n) 6 | func decompressRLElist(nums []int) []int { 7 | res := make([]int, 0) 8 | for i := 0; i < len(nums); i += 2 { 9 | key, value := nums[i], nums[i+1] 10 | for j := 0; j < key; j++ { 11 | res = append(res, value) 12 | } 13 | } 14 | return res 15 | } 16 | -------------------------------------------------------------------------------- /DynamicProgramming/NTribonacci.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/n-th-tribonacci-number/ 2 | 3 | class NTribonacci { 4 | public: 5 | int tribonacci(int n) { 6 | int s[max(4, n + 1)]; 7 | s[0] = 0; 8 | s[1] = 1; 9 | s[2] = 1; 10 | for (int i = 3; i <=n; ++i) { 11 | s[i] = s[i-1] + s[i-2] + s[i-3]; 12 | } 13 | return s[n]; 14 | } 15 | }; -------------------------------------------------------------------------------- /Array/MissingNumber.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/missing-number/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MissingNumber { 8 | public: 9 | int missingNumber(vector& nums) { 10 | int s = nums.size(); 11 | int sum = (s * (s + 1))/2; 12 | for (const int num : nums) { 13 | sum -= num; 14 | } 15 | return sum; 16 | } 17 | }; -------------------------------------------------------------------------------- /HashTable/MissingNumber.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link: https://leetcode.com/problems/missing-number/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int missingNumber(vector& nums) { 10 | int s = nums.size(); 11 | int sum = (s * (s + 1))/2; 12 | for (const int num : nums) { 13 | sum -= num; 14 | } 15 | return sum; 16 | } 17 | }; -------------------------------------------------------------------------------- /BitManipulation/BitCounter.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link: https://leetcode.com/problems/number-of-1-bits/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class BitCounter { 8 | public: 9 | int hammingWeight(uint32_t n) { 10 | int steps = 0; 11 | int count = 0; 12 | while (steps < 32) { 13 | if (n & (1 << steps)) ++count; 14 | ++steps; 15 | } 16 | return count; 17 | } 18 | }; -------------------------------------------------------------------------------- /BitManipulation/ReverseBits.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/reverse-bits/ 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | uint32_t reverseBits(uint32_t n) { 9 | int steps = 0; 10 | int result = 0; 11 | int bitmask = 1; 12 | while (steps < 32) { 13 | if (n & (bitmask << steps)) result = result | (bitmask << (32 - steps - 1)); 14 | ++steps; 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /DynamicProgramming/FibonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/fibonacci-number/ 2 | 3 | class FibonacciNumber { 4 | public: 5 | int fib(int N) { 6 | if (N == 0) return 0; 7 | if (N == 1) return 1; 8 | int f_n[N+1]; 9 | f_n[0] = 0; 10 | f_n[1] = 1; 11 | for (int i = 2; i <= N; ++i){ 12 | f_n[i] = f_n[i-1] + f_n[i-2]; 13 | } 14 | return f_n[N]; 15 | } 16 | }; -------------------------------------------------------------------------------- /Array/MakeTwoArraysEqual/go/MakeTwoArraysEqual.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // canBeEqual store frequency of each element in map and check if two arrays are equal 4 | // Time Complexity: O(n) 5 | // Space Complexity: O(n) 6 | func canBeEqual(target []int, arr []int) bool { 7 | m := make(map[int]int) 8 | for _, v := range target { 9 | m[v]++ 10 | } 11 | for _, v := range arr { 12 | m[v]-- 13 | if m[v] < 0 { 14 | return false 15 | } 16 | } 17 | return true 18 | } 19 | -------------------------------------------------------------------------------- /Heap/KLargestElement.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/kth-largest-element-in-an-array/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class KLargestElement { 9 | public: 10 | int findKthLargest(vector& nums, int k) { 11 | priority_queue pq; 12 | for (int i = 0; i < nums.size(); ++i) pq.push(nums[i]); 13 | for (int i = 1; i < k; ++i) pq.pop(); 14 | return pq.top(); 15 | } 16 | }; -------------------------------------------------------------------------------- /Sorting/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class HeapSort { 6 | public: 7 | void sort(vector& nums) { 8 | for (int i = 0; i < nums.size(); ++i) { 9 | for (int j = 0; j < nums.size() - i - 1; ++j) { 10 | if (nums[j] > nums[j + 1]) swap(nums, j, j + 1); 11 | } 12 | } 13 | } 14 | 15 | private: 16 | void swap(vector& nums, int i, int j) { 17 | int tmp = nums.at(i); 18 | nums[i] = nums[j]; 19 | nums[j] = tmp; 20 | } 21 | 22 | }; -------------------------------------------------------------------------------- /String/LastWordLength.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/length-of-last-word/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class LastWordLength { 8 | public: 9 | int lengthOfLastWord(string s) { 10 | int len = 0; 11 | for (int i = s.size() - 1; i >= 0; --i) { 12 | char ch = s[i]; 13 | if (ch == ' ' && len == 0) continue; 14 | if (ch == ' ' && len > 0) return len; 15 | if (ch != ' ') ++len; 16 | } 17 | return len; 18 | } 19 | }; -------------------------------------------------------------------------------- /DynamicProgramming/ClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class ClimbingStairs { 6 | private: 7 | unordered_map memory; 8 | 9 | public: 10 | int climbStairs(int n) { 11 | if (n == 0) return 0; 12 | if (n == 1) return 1; 13 | if (n == 2) return 2; 14 | if (memory.find(n) != memory.end()) return memory[n]; 15 | memory[n] = climbStairs (n - 1) + climbStairs(n - 2); 16 | return memory[n]; 17 | } 18 | }; -------------------------------------------------------------------------------- /Miscellaneous/ValidParantheses.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ValidParantheses { 8 | public: 9 | int minAddToMakeValid(string s) { 10 | int bal = 0; 11 | int ans = 0; 12 | for (char ch : s) { 13 | if (ch == '(') ++bal; 14 | else --bal; 15 | if (bal == -1) { ++ans; ++bal; } 16 | } 17 | return ans + bal; 18 | } 19 | }; -------------------------------------------------------------------------------- /String/IPAddrDefanger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class IPAddrDefanger { 5 | public: 6 | string defangIPaddr(string address) { 7 | string defanged_string = ""; 8 | for (int index = 0; index < address.size(); ++index) { 9 | if (address[index] == '.') { 10 | defanged_string += "[.]"; 11 | } else { 12 | defanged_string += address[index]; 13 | } 14 | } 15 | return defanged_string; 16 | } 17 | }; -------------------------------------------------------------------------------- /String/ReverseString.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/reverse-string/ 2 | 3 | class ReverseString { 4 | public void reverseString(char[] s) { 5 | int start = 0; 6 | int end = s.length - 1; 7 | while (start < end) { 8 | swap(s, start, end); 9 | ++start; 10 | --end; 11 | } 12 | } 13 | 14 | private void swap(char[] s, int x, int y) { 15 | char temp = s[x]; 16 | s[x] = s[y]; 17 | s[y] = temp; 18 | } 19 | } -------------------------------------------------------------------------------- /HashTable/DuplicateFinder.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/contains-duplicate/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class DuplicateFinder { 8 | public: 9 | bool containsDuplicate(vector& nums) { 10 | unordered_set nums_set; 11 | for (int i = 0; i < nums.size(); ++i) { 12 | if (nums_set.find(nums.at(i)) != nums_set.end()) return true; 13 | nums_set.insert(nums.at(i)); 14 | } 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /Array/NumberOfCandies.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class NumberOfCandies { 6 | public: 7 | vector kidsWithCandies(vector& candies, int extraCandies) { 8 | int max = 0; 9 | vector out_vec; 10 | for (int index = 0; index < candies.size(); ++index) { 11 | if (max < candies[index]) max = candies[index]; 12 | } 13 | for (int index = 0; index < candies.size(); ++index) { 14 | out_vec.push_back((candies[index] + extraCandies >= max)); 15 | } 16 | return out_vec; 17 | } 18 | }; -------------------------------------------------------------------------------- /Array/RunningSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/running-sum-of-1d-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class RunningSum { 8 | public: 9 | vector runningSum(vector& nums) { 10 | vector running_sums; 11 | int curr_sum = 0; 12 | for (int index = 0; index < nums.size(); ++index) { 13 | running_sums.push_back(curr_sum + nums[index]); 14 | curr_sum += nums[index]; 15 | } 16 | return running_sums; 17 | } 18 | }; -------------------------------------------------------------------------------- /DynamicProgramming/DivisorGame.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/divisor-game/ 2 | 3 | class DivisorGame { 4 | public: 5 | bool divisorGame(int n) { 6 | if (n == 1) return false; 7 | if (n == 2) return true; 8 | bool dp[n + 1]; 9 | for (int i = 0; i <= n; ++i) dp[i] = false; 10 | dp[2] = true; 11 | for (int i = 3; i <= n; ++i) { 12 | for (int j = i - 1; j > 0; --j) { 13 | int x = i - j; 14 | if ((i % x) != 0) continue; 15 | if (!dp[j]) { dp[i] = true; break; } 16 | } 17 | } 18 | return dp[n]; 19 | } 20 | }; -------------------------------------------------------------------------------- /String/LongestUncommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/longest-uncommon-subsequence-i/submissions/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class LongestUncommonSubsequence { 8 | public: 9 | int findLUSlength(string a, string b) { 10 | if (a.size() != b.size()) return getMax(a.size(), b.size()); 11 | if (a == b) return -1; 12 | return a.size(); 13 | } 14 | private: 15 | int getMax(int a, int b) { 16 | if (a > b) return a; 17 | return b; 18 | } 19 | }; -------------------------------------------------------------------------------- /Array/ConsecutiveOnes/cpp/ConsecutiveOnes.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/max-consecutive-ones/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ConsecutiveOnes { 8 | public: 9 | int findMaxConsecutiveOnes(vector& nums) { 10 | int max_len = 0, curr_len = 0; 11 | for (int i = 0; i < nums.size(); ++i) { 12 | if (nums[i] == 0) curr_len = 0; 13 | else { 14 | curr_len++; 15 | max_len = max(curr_len, max_len); 16 | } 17 | } 18 | max_len = max(curr_len, max_len); 19 | return max_len; 20 | } 21 | }; -------------------------------------------------------------------------------- /Array/LCISFinder/cpp/LCISFinder.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/longest-continuous-increasing-subsequence/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class LCISFinder { 8 | public: 9 | int findLengthOfLCIS(vector& nums) { 10 | int len = 1; 11 | int max_len = 1; 12 | for (int idx = 0; idx < (int)(nums.size() - 1); ++idx) { 13 | if (nums[idx] < nums[idx + 1]) { ++len; max_len = max(max_len, len); } 14 | else len = 1; 15 | } 16 | return max_len; 17 | } 18 | }; -------------------------------------------------------------------------------- /BitManipulation/CountingBits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class CountingBits { 6 | public: 7 | vector countBits(int n) { 8 | vector bitsCount; 9 | for (int index = 0; index <= n; ++index) { 10 | int num = index; 11 | int numOnes = 0; 12 | while (num > 0){ 13 | if ((num & 1) > 0) ++numOnes; 14 | num /= 2; 15 | } 16 | bitsCount.push_back(numOnes); 17 | } 18 | return bitsCount; 19 | } 20 | }; -------------------------------------------------------------------------------- /String/RansomNote.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/ransom-note/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class RansomNote { 8 | public: 9 | bool canConstruct(string ransomNote, string magazine) { 10 | int letters[26]; 11 | memset(letters, 0, sizeof(letters)); 12 | for (char ch : magazine) letters[ch - 'a']++; 13 | for (char ch : ransomNote) { 14 | letters[ch - 'a']--; 15 | if (letters[ch - 'a'] < 0) return false; 16 | } 17 | return true; 18 | } 19 | }; -------------------------------------------------------------------------------- /Array/ConsecutiveOnes/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/max-consecutive-ones/ 2 | 3 | ```text 4 | Given a binary array nums, return the maximum number of consecutive 1's in the array. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,1,0,1,1,1] 11 | Output: 3 12 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. 13 | Example 2: 14 | 15 | Input: nums = [1,0,1,1,0,1] 16 | Output: 2 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= nums.length <= 105 22 | nums[i] is either 0 or 1. 23 | ``` -------------------------------------------------------------------------------- /Miscellaneous/ValidPerfectSquare.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/valid-perfect-square/ 2 | 3 | class ValidPerfectSquare { 4 | public: 5 | bool isPerfectSquare(int num) { 6 | int st = 0, end = num, mid; 7 | while (st <= end) { 8 | mid = st + (end - st)/2; 9 | if (mid == 0) { mid = mid + 1; } 10 | double result = ((double)num)/mid; 11 | if (result == mid) return true; 12 | if (result < mid) { end = mid - 1; } 13 | else st = mid + 1; 14 | } 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /String/PalindromePermutation.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/palindrome-permutation/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class PalindromePermutation { 8 | public: 9 | bool canPermutePalindrome(string s) { 10 | bool sign[26]; 11 | int odd = 0; 12 | memset(sign, false, sizeof(sign)); 13 | for (char ch : s) { 14 | sign[ch - 'a'] = not sign[ch - 'a']; 15 | } 16 | for (int i = 0; i < 26; ++i) { 17 | if (sign[i]) ++odd; 18 | } 19 | if (odd > 1) return false; 20 | if (odd == 1) return (s.size() % 2 == 1); 21 | return true; 22 | } 23 | }; -------------------------------------------------------------------------------- /DynamicProgramming/MinMostClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/min-cost-climbing-stairs/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MinMostClimbingStairs { 8 | public: 9 | int minCostClimbingStairs(vector& cost) { 10 | int n_stairs = cost.size() + 1; 11 | int dp[n_stairs + 1]; 12 | for (int i = 0; i <= n_stairs; ++i) dp[i] = 0; 13 | for (int i = 3; i <= n_stairs; ++i) { 14 | dp[i] = min(dp[i - 1] + cost[i - 2], dp[i - 2] + cost[i - 3]); 15 | } 16 | return dp[n_stairs]; 17 | } 18 | }; -------------------------------------------------------------------------------- /Sorting/InsertSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class InsertSort { 6 | public: 7 | void sort(vector& nums) { 8 | for (int i = 1; i < nums.size(); ++i) { 9 | int j = i; 10 | while (j > 0 && isDescending(nums, j - 1, j)) { 11 | swap(nums, j - 1 , j); 12 | --j; 13 | } 14 | } 15 | } 16 | 17 | private: 18 | bool isDescending(const vector& nums, int i, int j) { 19 | return nums.at(i) > nums.at(j); 20 | } 21 | 22 | void swap(vector& nums, int i, int j) { 23 | int tmp = nums.at(i); 24 | nums[i] = nums[j]; 25 | nums[j] = tmp; 26 | } 27 | }; -------------------------------------------------------------------------------- /Array/LineChecker/go/LineChecker.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // checkStraightLine compare slopes of each point from the first point to the rest of the points. 4 | // Time complexity: O(n) 5 | // Space complexity: O(1) 6 | func checkStraightLine(coordinates [][]int) bool { 7 | x1, y1 := coordinates[0][0], coordinates[0][1] 8 | x2, y2 := coordinates[1][0], coordinates[1][1] 9 | 10 | dy := y2 - y1 11 | dx := x2 - x1 12 | 13 | for i := 2; i < len(coordinates); i++ { 14 | x, y := coordinates[i][0], coordinates[i][1] 15 | if dy*(x-x1) != dx*(y-y1) { 16 | return false 17 | } 18 | } 19 | return true 20 | } 21 | -------------------------------------------------------------------------------- /Array/ArraysIntersection/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/intersection-of-three-sorted-arrays/ 2 | 3 | ```text 4 | Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays. 5 | 6 | Example 1: 7 | 8 | Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] 9 | 10 | Output: [1,5] 11 | 12 | Explanation: Only 1 and 5 appeared in the three arrays. 13 | 14 | Constraints: 15 | 16 | 1 <= arr1.length, arr2.length, arr3.length <= 1000 17 | 1 <= arr1[i], arr2[i], arr3[i] <= 2000 18 | 19 | ``` -------------------------------------------------------------------------------- /Array/MakeTwoArraysEqual/cpp/MakeTwoArraysEqual.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MakeTwoArraysEqual { 8 | public: 9 | bool canBeEqual(vector& target, vector& arr) { 10 | int count[1001]; 11 | memset(count, 0, sizeof(count)); 12 | for (int elem : target) count[elem]++; 13 | for (int elem : arr) { 14 | count[elem]--; 15 | if (count[elem] < 0) return false; 16 | } 17 | return true; 18 | } 19 | }; -------------------------------------------------------------------------------- /DynamicProgramming/IsSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class IsSubsequence { 6 | public: 7 | bool isSubsequence(string s, string t) { 8 | return isSubsequenceInternal(s, t, 0, 0); 9 | } 10 | 11 | bool isSubsequenceInternal(string s, string t, int s_start, int t_start) { 12 | if (s_start >= s.size()) return true; 13 | if (t_start >= t.size()) return false; 14 | if (s[s_start] == t[t_start]) return isSubsequenceInternal(s, t, s_start + 1, t_start + 1); 15 | return isSubsequenceInternal(s, t, s_start, t_start + 1); 16 | } 17 | }; -------------------------------------------------------------------------------- /Search/SearchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/search-insert-position/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class SearchInsertPosition { 8 | public: 9 | int searchInsert(vector& nums, int target) { 10 | int pivot, left = 0, right = nums.size() - 1; 11 | while (left <= right) { 12 | pivot = left + (right - left) / 2; 13 | if (target == nums[pivot]) return pivot; 14 | if (target < nums[pivot]) right = pivot - 1; 15 | else left = pivot + 1; 16 | } 17 | return left; 18 | } 19 | }; -------------------------------------------------------------------------------- /String/VowelRemover.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/remove-vowels-from-a-string/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class VowelRemover { 7 | public: 8 | string removeVowels(string s) { 9 | string target_string = ""; 10 | for (int index = 0; index < s.size(); ++index) { 11 | if (isVowel(s[index])) continue; 12 | target_string += s[index]; 13 | } 14 | return target_string; 15 | } 16 | private: 17 | bool isVowel(char ch) { 18 | return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'); 19 | } 20 | }; -------------------------------------------------------------------------------- /Array/ArrayIntersection/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/intersection-of-two-arrays/ 2 | 3 | ```text 4 | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. 5 | 6 | Example 1: 7 | 8 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 9 | Output: [2] 10 | Example 2: 11 | 12 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 13 | Output: [9,4] 14 | Explanation: [4,9] is also accepted. 15 | 16 | 17 | Constraints: 18 | 19 | 1 <= nums1.length, nums2.length <= 1000 20 | 0 <= nums1[i], nums2[i] <= 1000 21 | ``` 22 | -------------------------------------------------------------------------------- /Array/DecompressRLE/cpp/DecompressRLE.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/decompress-run-length-encoded-list/ 2 | #include 3 | 4 | using namespace std; 5 | 6 | class DecompressRLE { 7 | public: 8 | vector decompressRLElist(vector& nums) { 9 | vector output; 10 | for (int index = 0; index < nums.size(); ++index){ 11 | int freq = nums[index]; 12 | int val = nums[index + 1]; 13 | while(freq > 0) { 14 | output.push_back(val); 15 | --freq; 16 | } 17 | ++index; 18 | } 19 | return output; 20 | } 21 | }; -------------------------------------------------------------------------------- /HashTable/ContinuousSubarraySum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/continuous-subarray-sum/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class ContinuousSubarraySum { 9 | public: 10 | bool checkSubarraySum(vector& nums, int k) { 11 | int sum = 0; 12 | unordered_map s_map; 13 | s_map[0] = 0; 14 | for (int i = 0; i < nums.size(); ++i) { 15 | sum += nums[i]; 16 | sum %= k; 17 | if (s_map.find(sum) != s_map.end()) { 18 | if (((i + 1) - s_map[sum]) > 1) return true; 19 | } else s_map[sum] = i + 1; 20 | } 21 | return false; 22 | } 23 | }; -------------------------------------------------------------------------------- /Miscellaneous/FizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/fizz-buzz/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class FizzBuzz { 9 | public: 10 | vector fizzBuzz(int n) { 11 | vector result; 12 | for (int i = 1; i <= n; ++i) { 13 | if ((i % 3 == 0) && (i % 5 == 0)) result.push_back("FizzBuzz"); 14 | else if (i % 3 == 0) result.push_back("Fizz"); 15 | else if (i % 5 == 0) result.push_back("Buzz"); 16 | else result.push_back(to_string(i)); 17 | } 18 | return result; 19 | } 20 | }; -------------------------------------------------------------------------------- /Array/HIndexCalculator/cpp/HIndexCalculator.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/h-index/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class HIndexCalculator { 8 | public: 9 | int hIndex(vector& citations) { 10 | int h_index = 0; 11 | int c_count[1001]; 12 | for (int i = 0; i < 1001; ++i) { 13 | c_count[i] = 0; 14 | } 15 | for (int i = 0; i < citations.size(); ++i) { 16 | c_count[citations[i]]++; 17 | } 18 | int c_sum = 0; 19 | for (int i = 1000; i > 0; --i) { 20 | c_sum += c_count[i]; 21 | if (i <= c_sum) { h_index = i; break; } 22 | } 23 | return h_index; 24 | } 25 | }; -------------------------------------------------------------------------------- /DynamicProgramming/GetMaxGeneratedArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/get-maximum-in-generated-array/ 2 | 3 | class GetMaxGeneratedArray { 4 | public: 5 | int getMaximumGenerated(int n) { 6 | if (n <= 1) return n; 7 | int nums[101]; 8 | nums[0]= 0; 9 | nums[1]= 1; 10 | int max_num = 1; 11 | for (int i = 2; i <= n; ++i) { 12 | if ((i % 2) == 0) nums[i] = nums[i/2]; 13 | else nums[i] = nums[i/2] + nums[i/2 + 1]; 14 | max_num = max(max_num, nums[i]); 15 | } 16 | return max_num; 17 | } 18 | }; -------------------------------------------------------------------------------- /HashTable/JewelStoneCounter.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/jewels-and-stones/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class JewelStoneCounter { 7 | public: 8 | int numJewelsInStones(string J, string S) { 9 | std::unordered_set jewels; 10 | for (int i = 0; i < J.size(); ++i){ 11 | jewels.insert(J.at(i)); 12 | } 13 | int count = 0; 14 | for (int i = 0; i < S.size(); ++i){ 15 | if (jewels.find(S.at(i)) != jewels.end()) { 16 | ++count; 17 | } 18 | } 19 | return count; 20 | } 21 | }; -------------------------------------------------------------------------------- /String/ExcelSheetColumnTitle.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/excel-sheet-column-title/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ExcelSheetColumnTitle { 8 | public: 9 | string convertToTitle(int columnNumber) { 10 | string outStr = ""; 11 | int num = columnNumber; 12 | while (num > 0) { 13 | int rem = num % 26; 14 | if (rem == 0) rem = 26; 15 | char ch = 'A' + (rem -1); 16 | outStr = ch + outStr; 17 | --num; 18 | num /= 26; 19 | } 20 | return outStr; 21 | } 22 | }; -------------------------------------------------------------------------------- /Search/FindMinRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class FindMinRotatedSortedArray { 8 | public: 9 | int findMin(vector& nums) { 10 | return findMinInt(nums, 0, nums.size() - 1); 11 | } 12 | 13 | private: 14 | int findMinInt(const vector& nums, int s, int e) { 15 | if (s == e) return nums.at(s); 16 | if ((s + 1) == e) return std::min(nums.at(s), nums.at(e)); 17 | int mid = (s + e) / 2; 18 | if (nums.at(mid) < nums.at(e)) return findMinInt(nums, s, mid); 19 | return findMinInt(nums, mid, e); 20 | } 21 | }; -------------------------------------------------------------------------------- /Array/MidIndexFinder.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/find-the-middle-index-in-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MidIndexFinder { 8 | public: 9 | int findMiddleIndex(vector& nums) { 10 | if (nums.size() == 1) return 0; 11 | int sum = 0; 12 | int sum_l = 0, sum_r = 0; 13 | for (int i = 0; i < nums.size(); ++i) sum += nums[i]; 14 | for (int i = 0; i < nums.size(); ++i) { 15 | sum_r = sum - sum_l - nums[i]; 16 | if (sum_r == sum_l) return i; 17 | sum_l += nums[i]; 18 | } 19 | return -1; 20 | } 21 | }; -------------------------------------------------------------------------------- /Miscellaneous/ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | class ReverseInteger { 2 | public: 3 | int reverse(int x) { 4 | int abs_x = abs(x); 5 | int max_num = std::pow(2, 31) - 1; 6 | int min_num = std::pow(2, 31) * (-1); 7 | int curr_num = abs_x; 8 | double reverse_x = 0; 9 | while (curr_num > 0) { 10 | int digit = curr_num - ((curr_num/10) * 10); 11 | reverse_x = reverse_x*10 + digit; 12 | curr_num /= 10; 13 | 14 | } 15 | if (x < 0) reverse_x *= -1; 16 | if (reverse_x > max_num || reverse_x < min_num) return 0; 17 | return (int)reverse_x; 18 | } 19 | }; -------------------------------------------------------------------------------- /Array/ArrayIntersection/cpp/ArrayIntersection.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/intersection-of-two-arrays/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ArrayIntersection { 8 | public: 9 | vector intersect(vector& nums1, vector& nums2) { 10 | int ar1[1001]; 11 | for (int i = 0; i < 1001; ++i) ar1[i] = 0; 12 | vector result; 13 | for (int i : nums1) ar1[i]++; 14 | for (int i : nums2) { 15 | if (ar1[i] > 0) { 16 | result.push_back(i); 17 | ar1[i]--; 18 | } 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /Array/IsMonotone/cpp/IsMonotone.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/monotonic-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class IsMonotone { 8 | public: 9 | bool isMonotonic(vector& nums) { 10 | if (nums.size() <= 2) return true; 11 | bool sign[2]; 12 | memset(sign, false, sizeof(sign)); 13 | for (int i = 1; i < nums.size(); ++i) { 14 | int diff = nums[i] - nums[i - 1]; 15 | if (diff < 0) sign[0] = true; 16 | else if (diff > 0) sign[1] = true; 17 | if (sign[0] && sign[1]) return false; 18 | } 19 | return true; 20 | } 21 | }; -------------------------------------------------------------------------------- /Matrix/ToeplitzMatrix.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/toeplitz-matrix/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ToeplitzMatrix { 8 | public: 9 | bool isToeplitzMatrix(vector>& matrix) { 10 | int max_rows = matrix.size(); 11 | int max_cols = matrix[0].size(); 12 | for (int i = 0; i < max_rows; ++i) { 13 | for (int j = 0; j < max_cols; ++j) { 14 | if (((i + 1) >= max_rows) || ((j + 1) >= max_cols)) continue; 15 | if (matrix[i][j] != matrix[i + 1][j + 1]) return false; 16 | } 17 | } 18 | return true; 19 | } 20 | }; -------------------------------------------------------------------------------- /LinkedList/ListReverse.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/reverse-linked-list/ 2 | 3 | // Definition for singly-linked list. 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode() : val(0), next(nullptr) {} 8 | ListNode(int x) : val(x), next(nullptr) {} 9 | ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | }; 11 | 12 | class ListReverse { 13 | public: 14 | ListNode* reverseList(ListNode* head) { 15 | ListNode* curr = head; 16 | ListNode* prev = nullptr; 17 | while (curr) { 18 | ListNode* tmp = curr->next; 19 | curr->next = prev; 20 | prev = curr; 21 | curr = tmp; 22 | } 23 | return prev; 24 | } 25 | }; -------------------------------------------------------------------------------- /String/BackspaceCompare.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/backspace-string-compare/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class BackspaceCompare { 9 | public: 10 | bool backspaceCompare(const string& s, const string& t) { 11 | stack st_s, st_t; 12 | for (char ch : s) { 13 | if (ch == '#') { if (st_s.size() > 0) st_s.pop(); } 14 | else st_s.push(ch); 15 | } 16 | for (char ch : t) { 17 | if (ch == '#') { if (st_t.size() > 0) st_t.pop(); } 18 | else st_t.push(ch); 19 | } 20 | return st_s == st_t; 21 | } 22 | }; -------------------------------------------------------------------------------- /String/IsSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/is-subsequence/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class IsSubsequence { 8 | public: 9 | bool isSubsequence(const string& s, const string& t) { 10 | return isSubsequenceInternal(s, t, 0, 0); 11 | } 12 | 13 | private: 14 | bool isSubsequenceInternal(const string& s, const string& t, int s_start, int t_start) { 15 | if (s_start >= s.size()) return true; 16 | if (t_start >= t.size()) return false; 17 | if (s[s_start] == t[t_start]) return isSubsequenceInternal(s, t, s_start + 1, t_start + 1); 18 | return isSubsequenceInternal(s, t, s_start, t_start + 1); 19 | } 20 | }; -------------------------------------------------------------------------------- /Greedy/MaxWaterContainer.cpp: -------------------------------------------------------------------------------- 1 | // Problem-link: https://leetcode.com/problems/container-with-most-water/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MaxWaterContainer { 8 | public: 9 | int maxArea(vector& height) { 10 | int s = 0, e = height.size() - 1; 11 | int max_area = (e - s) * std::min(height.at(s), height.at(e)); 12 | while (s < e) { 13 | if (height.at(s) < height.at(e)) ++s; 14 | else --e; 15 | int curr_area = (e - s) * std::min(height.at(s), height.at(e)); 16 | max_area = std::max(max_area, curr_area); 17 | } 18 | return max_area; 19 | } 20 | }; -------------------------------------------------------------------------------- /Sorting/ColorSorter.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/sort-colors/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class ColorSorter { 7 | public: 8 | void sortColors(vector& nums) { 9 | int num[3]; 10 | for (int i = 0; i < 3; ++i) { 11 | num[i] = 0; 12 | } 13 | for (int i = 0; i< nums.size(); ++i) { 14 | num[nums[i]]++; 15 | } 16 | int curr_idx = 0; 17 | for (int i = 0; i < 3; ++i){ 18 | for (int j = 0; j < num[i]; ++j) { 19 | nums[curr_idx] = i; 20 | curr_idx++; 21 | } 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /Array/GoodPairs/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/number-of-good-pairs/ 2 | 3 | ```text 4 | Given an array of integers nums, return the number of good pairs. 5 | 6 | A pair (i, j) is called good if nums[i] == nums[j] and i < j. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,2,3,1,1,3] 13 | Output: 4 14 | Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 15 | Example 2: 16 | 17 | Input: nums = [1,1,1,1] 18 | Output: 6 19 | Explanation: Each pair in the array are good. 20 | Example 3: 21 | 22 | Input: nums = [1,2,3] 23 | Output: 0 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 100 29 | 1 <= nums[i] <= 100 30 | ``` -------------------------------------------------------------------------------- /String/OrderlyQueue.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/orderly-queue/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class OrderlyQueue { 8 | public: 9 | string orderlyQueue(string s, int k) { 10 | string curr = s, result = s; 11 | if (k>1) { 12 | sort(result.begin(), result.end()); 13 | return result; 14 | } 15 | while (true) { 16 | curr.append(1, curr[0]); 17 | curr.erase(curr.begin()); 18 | if (curr == s) break; 19 | if (curr < result) { result = curr; } 20 | } 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /HashTable/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/majority-element/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class MajorityElement { 9 | public: 10 | int majorityElement(vector& nums) { 11 | unordered_map num_count; 12 | int max_count = 0; 13 | int max_num = 0; 14 | for (int i = 0; i < nums.size(); ++i) { 15 | num_count[nums[i]]++; 16 | if (max_count < num_count[nums[i]]) { 17 | max_count = num_count[nums[i]]; 18 | max_num = nums[i]; 19 | } 20 | } 21 | return max_num; 22 | } 23 | }; -------------------------------------------------------------------------------- /HashTable/SubarraySum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/subarray-sum-equals-k/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class SubarraySum { 9 | public: 10 | int subarraySum(vector& nums, int k) { 11 | unordered_map s_map; 12 | int count = 0; 13 | int c_sum = 0; 14 | s_map[0] = 1; 15 | for (int i = 0; i < nums.size(); ++i) { 16 | c_sum += nums[i]; 17 | int diff = c_sum - k; 18 | if (s_map.find(diff) != s_map.end()) { count += s_map[diff]; } 19 | s_map[c_sum]++; 20 | } 21 | return count; 22 | } 23 | }; -------------------------------------------------------------------------------- /Array/PlusOne.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/plus-one/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class PlusOne { 8 | public: 9 | vector plusOne(vector& digits) { 10 | vector result; 11 | int carry = 1; 12 | for (int i = digits.size() - 1; i >= 0; --i) { 13 | int num = digits[i] + carry; 14 | if (num == 10) { 15 | num = 0; 16 | carry = 1; 17 | } else carry = 0; 18 | result.insert(result.begin(), num); 19 | } 20 | if (carry == 1) result.insert(result.begin(), 1); 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /Array/MergeSortedArray/go/MergeSortedArray.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // merge iterate both array and merge them, if nums1 is greater, append after nums2 and vice versa 4 | // Time Complexity: O(n) 5 | // Space Complexity: O(1) 6 | func merge(nums1 []int, m int, nums2 []int, n int) { 7 | ans := make([]int, m+n) 8 | i, j, k := 0, 0, 0 9 | for i < m && j < n { 10 | if nums1[i] < nums2[j] { 11 | ans[k] = nums1[i] 12 | i++ 13 | } else { 14 | ans[k] = nums2[j] 15 | j++ 16 | } 17 | k++ 18 | } 19 | for i < m { 20 | ans[k] = nums1[i] 21 | i++ 22 | k++ 23 | } 24 | for j < n { 25 | ans[k] = nums2[j] 26 | j++ 27 | k++ 28 | } 29 | copy(nums1, ans) 30 | ans = nil 31 | } 32 | -------------------------------------------------------------------------------- /Stack/RemoveDuplicates.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class RemoveDuplicates { 9 | public: 10 | string removeDuplicates(const string& s) { 11 | stack s_stack; 12 | string result; 13 | for (int i = 0; i < s.size(); ++i) { 14 | if (s_stack.empty()) s_stack.push(s[i]); 15 | else { 16 | if (s[i] == s_stack.top()) s_stack.pop(); 17 | else s_stack.push(s[i]); 18 | 19 | } 20 | } 21 | while (!s_stack.empty()) { 22 | result.insert(result.begin(), s_stack.top()); 23 | s_stack.pop(); 24 | } 25 | return result; 26 | } 27 | }; -------------------------------------------------------------------------------- /Greedy/MaximumScore.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/maximum-score-from-removing-stones/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class MaximumScore { 9 | public: 10 | int maximumScore(int a, int b, int c) { 11 | priority_queue> pq; 12 | pq.push(a); pq.push(b); pq.push(c); 13 | int output = 0; 14 | while (pq.size() > 1) { 15 | int v1 = pq.top(); pq.pop(); 16 | int v2 = pq.top(); pq.pop(); 17 | ++output; --v1; --v2; 18 | if (v1 > 0) pq.push(v1); 19 | if (v2 > 0) pq.push(v2); 20 | } 21 | return output; 22 | } 23 | }; -------------------------------------------------------------------------------- /LinkedList/SwapNodesInPairs.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/swap-nodes-in-pairs/ 2 | // Definition for singly-linked list. 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class SwapNodesInPairs { 12 | public: 13 | ListNode* swapPairs(ListNode* head) { 14 | if (head == nullptr || head->next == nullptr) return head; 15 | ListNode* curr = head; 16 | ListNode* next = curr->next; 17 | curr->next = swapPairs(next->next); 18 | next->next = curr; 19 | return next; 20 | } 21 | }; -------------------------------------------------------------------------------- /String/WordComparator.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class WordComparator { 8 | public: 9 | bool isSumEqual(string firstWord, string secondWord, string targetWord) { 10 | return toNum(firstWord) + toNum(secondWord) == toNum(targetWord); 11 | } 12 | private: 13 | int toNum(string word) { 14 | int num = 0; 15 | for (int index = 0; index < word.size(); ++index) { 16 | char ch = word.at(index); 17 | int val = (int)(ch) - (int)('a'); 18 | num = num * 10 + val; 19 | } 20 | return num; 21 | } 22 | }; -------------------------------------------------------------------------------- /Tree/MaxDepth.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | 3 | #include 4 | 5 | // Definition for a binary tree node. 6 | struct TreeNode { 7 | int val; 8 | TreeNode *left; 9 | TreeNode *right; 10 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | }; 14 | 15 | class MaxDepth { 16 | public: 17 | int maxDepth(TreeNode* root) { 18 | if (root == nullptr) return 0; 19 | return std::max(maxDepth(root->left), maxDepth(root->right)) + 1; 20 | } 21 | }; -------------------------------------------------------------------------------- /Array/MergeSortedArray/cpp/MergeSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/merge-sorted-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MergeSortedArray { 8 | public: 9 | void merge(vector& nums1, int m, vector& nums2, int n) { 10 | vector numsCopy; 11 | int i1 = 0; 12 | int i2 = 0; 13 | while (i1 < m && i2 < n) { 14 | if (nums1[i1] <= nums2[i2]) { numsCopy.push_back(nums1[i1]); ++i1; } 15 | else { numsCopy.push_back(nums2[i2]); ++i2; } 16 | } 17 | while (i1 < m) { 18 | numsCopy.push_back(nums1[i1]); ++i1; 19 | } 20 | while (i2 < n) { 21 | numsCopy.push_back(nums2[i2]); ++i2; 22 | } 23 | nums1 = numsCopy; 24 | } 25 | }; -------------------------------------------------------------------------------- /Stack/MaxNestingDepth.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/ 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MaxNestingDepth { 8 | public: 9 | int maxDepth(string s) { 10 | stack s_stack; 11 | int max_depth = 0; 12 | for (int i = 0; i < s.size(); ++i) { 13 | char ch = s[i]; 14 | if (ch == '(') { 15 | s_stack.push(ch); 16 | max_depth = max(max_depth, (int)s_stack.size()); 17 | } 18 | if (ch == ')') { 19 | s_stack.pop(); 20 | } 21 | } 22 | return max_depth; 23 | } 24 | }; -------------------------------------------------------------------------------- /Graph/MinimumVerticesToNodes.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MinimumVerticesToNodes { 8 | public: 9 | vector findSmallestSetOfVertices(int n, vector>& edges) { 10 | vector incoming; 11 | vector result; 12 | incoming.resize(n, 0); 13 | int count = 0; 14 | for (int i = 0; i < edges.size(); ++i) incoming[edges[i][1]]++; 15 | for (int i = 0; i < n; ++i) { 16 | if (incoming[i] == 0) { 17 | result.push_back(i); 18 | } 19 | } 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /HashTable/NumberMatchingSubsequences.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/number-of-matching-subsequences/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class NumberMatchingSubsequences { 9 | public: 10 | int numMatchingSubseq(string S, vector& words) { 11 | vector waiting[128]; 12 | for (auto &w : words) 13 | waiting[w[0]].push_back(w.c_str()); 14 | for (char c : S) { 15 | auto advance = waiting[c]; 16 | waiting[c].clear(); 17 | for (auto it : advance) 18 | waiting[*++it].push_back(it); 19 | } 20 | return waiting[0].size(); 21 | } 22 | }; -------------------------------------------------------------------------------- /LinkedList/CycleDetector.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/linked-list-cycle/ 2 | // Definition for singly-linked list. 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode(int x) : val(x), next(NULL) {} 7 | }; 8 | 9 | class CycleDetector { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | if (head == nullptr || head->next == nullptr) return false; 13 | ListNode* c1 = head; 14 | ListNode* c2 = head->next; 15 | while (c1 != c2) { 16 | if ((c1 == nullptr) || (c2 == nullptr) || (c2->next == nullptr)) break; 17 | c1 = c1->next; 18 | c2 = c2->next->next; 19 | } 20 | return c1 == c2; 21 | } 22 | }; -------------------------------------------------------------------------------- /Tree/TreeComparator.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/same-tree/ 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 TreeComparator { 13 | public: 14 | bool isSameTree(TreeNode* p, TreeNode* q) { 15 | if (p == nullptr || q == nullptr) { 16 | return p == q; 17 | } 18 | if (p->val != q->val) return false; 19 | return 20 | isSameTree(p->left, q->left) && 21 | isSameTree(p->right, q->right); 22 | } 23 | }; -------------------------------------------------------------------------------- /Array/AddToArrayForm/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/add-to-array-form-of-integer/ 2 | 3 | ```text 4 | The array-form of an integer num is an array representing its digits in left to right order. 5 | 6 | For example, for num = 1321, the array form is [1,3,2,1]. 7 | Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. 8 | 9 | Example 1: 10 | 11 | Input: num = [1,2,0,0], k = 34 12 | Output: [1,2,3,4] 13 | Explanation: 1200 + 34 = 1234 14 | Example 2: 15 | 16 | Input: num = [2,7,4], k = 181 17 | Output: [4,5,5] 18 | Explanation: 274 + 181 = 455 19 | Example 3: 20 | 21 | Input: num = [2,1,5], k = 806 22 | Output: [1,0,2,1] 23 | Explanation: 215 + 806 = 1021 24 | ``` -------------------------------------------------------------------------------- /Array/ShiftingLetters.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/shifting-letters/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class ShiftingLetters { 9 | public: 10 | string shiftingLetters(string s, vector& shifts) { 11 | int sum = 0; 12 | vector actual_shifts; 13 | actual_shifts.resize(shifts.size(), 0); 14 | for (int i = shifts.size() - 1; i >= 0; --i) { 15 | actual_shifts[i] = shifts[i] + sum % 26; 16 | sum += shifts[i] % 26; 17 | } 18 | for (int i = 0; i < actual_shifts.size(); ++i) { 19 | s[i] = ((s[i] + actual_shifts[i] - 'a') % 26) + 'a'; 20 | } 21 | return s; 22 | } 23 | }; -------------------------------------------------------------------------------- /DynamicProgramming/PascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/pascals-triangle-ii/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class PascalTriangle { 8 | public: 9 | vector getRow(int rowIndex) { 10 | vector curr, prev; 11 | int ci = 0; 12 | curr.push_back(1); 13 | while (ci < (rowIndex)) { 14 | prev = curr; 15 | curr.clear(); 16 | curr.push_back(1); 17 | for (int i = 1; i < prev.size(); ++i) { 18 | curr.push_back(prev[i -1] + prev[i]); 19 | } 20 | curr.push_back(1); 21 | ++ci; 22 | } 23 | return curr; 24 | } 25 | }; -------------------------------------------------------------------------------- /DynamicProgramming/MaxSubArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/maximum-subarray/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class MaxSubArray { 9 | public: 10 | int maxSubArray(vector& nums) { 11 | if (nums.size() == 0) return 0; 12 | // At least one element is present. 13 | int currSum = nums[0]; 14 | int maxSum = currSum; 15 | for (int index = 1; index < nums.size(); ++index) { 16 | int currNum = nums[index]; 17 | int newSum = currSum + currNum; 18 | currSum = std::max(newSum, currNum); 19 | maxSum = std::max(maxSum, currSum); 20 | } 21 | return maxSum; 22 | } 23 | }; -------------------------------------------------------------------------------- /DynamicProgramming/PalindromeValidator.cpp: -------------------------------------------------------------------------------- 1 | //Problem: https://leetcode.com/problems/valid-palindrome-ii/ 2 | #include 3 | 4 | using namespace std; 5 | 6 | class PalindromeValidator { 7 | public: 8 | bool validPalindrome(string s) { 9 | return validPalindromeInt(s, 0, s.size() - 1, 1); 10 | } 11 | 12 | private: 13 | bool validPalindromeInt(string s, int start, int end, int count) { 14 | while (start < end && s[start] == s[end]) { 15 | ++start; 16 | --end; 17 | } 18 | if (start >= end) return true; 19 | if (count <= 0) return false; 20 | return validPalindromeInt(s, start + 1, end, count - 1) || validPalindromeInt(s, start, end - 1, count - 1); 21 | } 22 | }; -------------------------------------------------------------------------------- /HashTable/DuplicateRemover.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class DuplicateRemover { 8 | public: 9 | int removeDuplicates(vector& nums) { 10 | if (nums.size() < 2) return nums.size(); 11 | int index = 0; 12 | int j = 0; 13 | for (int j = 0; j < nums.size() - 1; ++j) { 14 | if (nums[j] != nums[j + 1]) { 15 | nums[index] = nums[j]; 16 | ++index; 17 | } 18 | } 19 | if (index < nums.size()) { 20 | nums[index] = nums[nums.size() - 1]; 21 | ++index; 22 | } 23 | return index; 24 | } 25 | }; -------------------------------------------------------------------------------- /Sorting/TwoSumLessThanK.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/two-sum-less-than-k/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class TwoSumLessThanK { 9 | public: 10 | int twoSumLessThanK(vector& nums, int k) { 11 | int max_sum = -1; 12 | int i = 0; 13 | int j = nums.size() - 1; 14 | sort(nums.begin(), nums.end()); 15 | while(i= k) --j; 18 | if (curr_sum < k) { 19 | if (curr_sum > max_sum) max_sum = curr_sum; 20 | ++i; 21 | } 22 | } 23 | return max_sum; 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/FixedPoint/go/FixedPoint.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // fixedPoint iterate through the array and check index = value 4 | // Time: O(n) 5 | // space: O(1) 6 | func fixedPoint(nums []int) int { 7 | for i, v := range nums { 8 | if i == v { 9 | return v 10 | } 11 | } 12 | return -1 13 | } 14 | 15 | // fixedPoint2 continue searching if you found the num 16 | // Time: O(log n) 17 | // space: O(1) 18 | func fixedPoint2(nums []int) int { 19 | low, high, mid, ans := 0, len(nums)-1, 0, -1 20 | for low <= high { 21 | mid = low + (high-low)/2 22 | if nums[mid] == mid { 23 | ans = mid 24 | high = mid - 1 25 | } else if nums[mid] > mid { 26 | high = mid - 1 27 | } else { 28 | low = mid + 1 29 | } 30 | } 31 | return ans 32 | } 33 | -------------------------------------------------------------------------------- /Heap/KSmallestElementMatrix.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class KSmallestElementMatrix { 9 | public: 10 | int kthSmallest(vector>& matrix, int k) { 11 | priority_queue, std::greater> pq; 12 | for (int i = 0; i < min(k+1, (int)matrix.size()); ++i) { 13 | vector row = matrix[i]; 14 | for (int j = 0; j < min(k +1, (int)row.size()); ++j) { 15 | pq.push(row[j]); 16 | } 17 | } 18 | for (int i = 1; i < k; ++i) pq.pop(); 19 | return pq.top(); 20 | } 21 | }; -------------------------------------------------------------------------------- /Miscellaneous/StrobogrammaticNumber.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/strobogrammatic-number/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class StrobogrammaticNumber { 8 | public: 9 | bool isStrobogrammatic(const string& num) { 10 | string rotated; 11 | for (char ch : num) { 12 | rotated.insert(rotated.begin(), rotate(ch)); 13 | } 14 | return rotated == num; 15 | } 16 | 17 | private: 18 | char rotate(char ch) { 19 | switch (ch) { 20 | case '0': return '0'; 21 | case '1': return '1'; 22 | case '6': return '9'; 23 | case '8': return '8'; 24 | case '9': return '6'; 25 | } 26 | return '-'; 27 | } 28 | }; -------------------------------------------------------------------------------- /Array/IsMonotone/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/monotonic-array/ 2 | 3 | ```text 4 | An array is monotonic if it is either monotone increasing or monotone decreasing. 5 | 6 | An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. 7 | 8 | Given an integer array nums, return true if the given array is monotonic, or false otherwise. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: nums = [1,2,2,3] 15 | Output: true 16 | Example 2: 17 | 18 | Input: nums = [6,5,4,4] 19 | Output: true 20 | Example 3: 21 | 22 | Input: nums = [1,3,2] 23 | Output: false 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 105 29 | -105 <= nums[i] <= 105 30 | ``` -------------------------------------------------------------------------------- /String/AddBinary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class AddBinary { 6 | public: 7 | string addBinary(const string& a, const string& b) { 8 | string result = ""; 9 | int i = a.size() - 1; 10 | int j = b.size() - 1; 11 | int carry_over = 0; 12 | while (i >= 0 || j >=0) { 13 | int sum = carry_over; 14 | if (i >= 0) sum += (a[i]-'0'); 15 | if (j >= 0) sum += (b[j]-'0'); 16 | carry_over = sum / 2; 17 | sum = sum % 2; 18 | result = to_string(sum) + result; 19 | --i; 20 | --j; 21 | } 22 | if (carry_over > 0) result = std::string("1") + result; 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/FixedPoint/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/fixed-point/ 2 | ```text 3 | Given an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: [-10,-5,0,3,7] 10 | Output: 3 11 | Explanation: 12 | For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3. 13 | Example 2: 14 | 15 | Input: [0,2,5,8,17] 16 | Output: 0 17 | Explanation: 18 | A[0] = 0, thus the output is 0. 19 | Example 3: 20 | 21 | Input: [-10,-5,3,4,7,9] 22 | Output: -1 23 | Explanation: 24 | There is no such i that A[i] = i, thus the output is -1. 25 | 26 | 27 | Note: 28 | 29 | 1 <= A.length < 10^4 30 | -10^9 <= A[i] <= 10^9 31 | ``` -------------------------------------------------------------------------------- /DynamicProgramming/FirstBadVersion.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/first-bad-version/ 2 | // The API isBadVersion is defined for you. 3 | // bool isBadVersion(int version); 4 | 5 | class FirstBadVersion { 6 | public: 7 | int firstBadVersion(int n) { 8 | if (isBadVersion(1)) return 1; 9 | return firstBadVersionInt(1, n, n); 10 | } 11 | 12 | private: 13 | int firstBadVersionInt(int s, int e, int n) { 14 | int mid = max(s, s / 2 + e / 2); 15 | bool isBad1 = isBadVersion(mid); 16 | bool isBad2 = isBadVersion(min(n, mid + 1)); 17 | if (not isBad1 && isBad2) return min(n, mid + 1); 18 | if (isBad1) return firstBadVersionInt(s, mid - 1, n); 19 | return firstBadVersionInt(mid + 1, e, n); 20 | } 21 | }; -------------------------------------------------------------------------------- /Miscellaneous/NumTeams.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/count-number-of-teams/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class NumTeams { 8 | public: 9 | int numTeams(vector& rating) { 10 | int sum = 0; 11 | for (int i = 0; i < rating.size(); ++i) { 12 | int less[2] = {}, greater[2] = {}; 13 | for (int j = 0; j < rating.size(); ++j) { 14 | if (rating[i] < rating[j]) { 15 | greater[i < j]++; 16 | } 17 | else if (rating[i] > rating[j]) { 18 | less[i < j]++; 19 | } 20 | } 21 | sum += less[0] * greater[1] + less[1] * greater[0]; 22 | } 23 | return sum; 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/LineChecker/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem https://leetcode.com/problems/check-if-it-is-a-straight-line/ 2 | 3 | Open above link for full description and images 4 | ```text 5 | 6 | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. 7 | 8 | Example 1: 9 | 10 | 11 | 12 | Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 13 | Output: true 14 | Example 2: 15 | 16 | 17 | 18 | Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 19 | Output: false 20 | 21 | 22 | Constraints: 23 | 24 | 2 <= coordinates.length <= 1000 25 | coordinates[i].length == 2 26 | -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 27 | coordinates contains no duplicate point. 28 | ``` -------------------------------------------------------------------------------- /LinkedList/FindMid.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/middle-of-the-linked-list/ 2 | // Definition for singly-linked list. 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class FindMid { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | if (head == nullptr) return head; 15 | ListNode* curr = head; 16 | ListNode* twoStep = head->next; 17 | while (twoStep && twoStep->next) { 18 | curr = curr->next; 19 | twoStep = twoStep->next->next; 20 | } 21 | if (twoStep == nullptr) return curr; 22 | return curr->next; 23 | } 24 | }; -------------------------------------------------------------------------------- /String/LongestCommonPrefixFinder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class LongestCommonPrefixFinder { 7 | public: 8 | string longestCommonPrefix(vector& strs) { 9 | if (strs.size() == 0) return ""; 10 | int index = 0; 11 | string longest_prefix = ""; 12 | while (true) { 13 | if (strs[0].size() <= index) break; 14 | char ch = strs[0][index]; 15 | for (int i = 1; i < strs.size(); ++i) { 16 | if ((strs[i].size() <= index) || (ch != strs[i][index])) { 17 | return longest_prefix; 18 | } 19 | } 20 | longest_prefix += ch; 21 | ++index; 22 | } 23 | return longest_prefix; 24 | } 25 | }; -------------------------------------------------------------------------------- /LinkedList/ListMerger.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/merge-two-sorted-lists/ 2 | // Definition for singly-linked list. 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class ListMerger { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 14 | if (l1 == nullptr) return l2; 15 | if (l2 == nullptr) return l1; 16 | // None of these are null. 17 | if (l1->val <= l2->val) { 18 | l1->next = mergeTwoLists(l1->next, l2); 19 | return l1; 20 | } 21 | l2->next = mergeTwoLists(l1, l2->next); 22 | return l2; 23 | } 24 | }; -------------------------------------------------------------------------------- /String/StringDifference.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/find-the-difference/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class StringDifference { 9 | public: 10 | char findTheDifference(string s, string t) { 11 | if (t.size() == 1) return t.at(0); 12 | unordered_map m1; 13 | unordered_map m2; 14 | getCount(s, m1); 15 | getCount(t, m2); 16 | for (int i = 0; i < t.size(); ++i) { 17 | char ch = t.at(i); 18 | int c1 = m1[ch]; 19 | int c2 = m2[ch]; 20 | if (c2 > c1) return ch; 21 | } 22 | return ' '; 23 | } 24 | private: 25 | void getCount(const string& s, unordered_map& char_count) { 26 | for (int i = 0; i < s.size(); ++i) { 27 | char ch = s.at(i); 28 | char_count[ch]++; 29 | } 30 | } 31 | }; -------------------------------------------------------------------------------- /Search/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class BinarySearch { 6 | public: 7 | int search(vector& nums, int target) { 8 | return searchInt(nums, 0, nums.size() - 1, target); 9 | } 10 | 11 | private: 12 | int searchInt(const vector& nums, int s, int e, int target) { 13 | if (s > e) return -1; 14 | if (s < 0 || e >= nums.size()) return -1; 15 | if (s == e) { 16 | if (nums.at(s) == target) return s; 17 | return -1; 18 | } 19 | int mid_index = (s + e) / 2; 20 | int mid = nums.at(mid_index); 21 | if (target == mid) return mid_index; 22 | if (mid > target) return searchInt(nums, s, mid_index - 1, target); 23 | return searchInt(nums, mid_index + 1, e, target); 24 | } 25 | }; -------------------------------------------------------------------------------- /Tree/InvertBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/invert-binary-tree/ 2 | 3 | // Definition for a binary tree node. 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 11 | }; 12 | 13 | class InvertBinaryTree { 14 | public: 15 | TreeNode* invertTree(TreeNode* root) { 16 | if (root == nullptr) return nullptr; 17 | if (root->left == nullptr && root->right == nullptr) return root; 18 | TreeNode* tmp = root->left; 19 | root->left = root->right; 20 | root->right = tmp; 21 | invertTree(root->left); 22 | invertTree(root->right); 23 | return root; 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/RangeSumQuery.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /** 7 | * Your RangeSumQuery object will be instantiated and called as such: 8 | * RangeSumQuery* obj = new RangeSumQuery(nums); 9 | * int param_1 = obj->sumRange(left,right); 10 | */ 11 | 12 | class RangeSumQuery { 13 | public: 14 | RangeSumQuery(vector& nums) : _nums(nums) { 15 | int sum = 0; 16 | for (int index = 0; index < nums.size(); ++index) { 17 | _sums[index] = sum + nums[index]; 18 | sum = _sums[index]; 19 | } 20 | } 21 | int sumRange(int left, int right) { 22 | return _sums[right] - _sums[left] + _nums[left]; 23 | } 24 | 25 | private: 26 | vector _nums; 27 | unordered_map _sums; 28 | }; 29 | -------------------------------------------------------------------------------- /Array/GoodPairs/cpp/GoodPairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef int count; 7 | 8 | class GoodPairs { 9 | public: 10 | int numIdenticalPairs(vector& nums) { 11 | unordered_map numCount; 12 | unordered_map::iterator it; 13 | int numPairs = 0; 14 | for (int index = 0; index < nums.size(); ++index) { 15 | numCount[nums[index]]++; 16 | } 17 | for (it = numCount.begin(); it != numCount.end(); ++it) { 18 | if (it->second > 1) { 19 | numPairs += numCombinations(it->second); 20 | } 21 | } 22 | return numPairs; 23 | } 24 | 25 | private: 26 | int numCombinations(int num) { 27 | return (num * (num - 1))/2; 28 | } 29 | }; -------------------------------------------------------------------------------- /LinkedList/DeleteNode.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/delete-node-in-a-linked-list/ 2 | 3 | // Definition for singly-linked list. 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode(int x) : val(x), next(NULL) {} 8 | }; 9 | 10 | class DeleteNode { 11 | public: 12 | void deleteNode(ListNode* node) { 13 | if (node == nullptr || node->next == nullptr) return; 14 | while (true) { 15 | swap(node, node->next); 16 | if (node->next->next == nullptr) { 17 | node->next = nullptr; 18 | break; 19 | } 20 | else node = node->next; 21 | } 22 | } 23 | 24 | void swap(ListNode* n1, ListNode* n2) { 25 | int tmp = n1->val; 26 | n1->val = n2->val; 27 | n2->val = tmp; 28 | } 29 | }; -------------------------------------------------------------------------------- /Sorting/MinDiff.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MinDiff { 8 | public: 9 | int minDifference(vector& nums) { 10 | int n = nums.size(); 11 | if (n < 5) return 0; 12 | sort(nums.begin(), nums.end()); 13 | int ans = INT_MAX; 14 | // Case-I: Kill 3 largest. 15 | ans = min(ans, nums[n - 4] - nums[0]); 16 | // Case-II: Kill 3 smallest. 17 | ans = min(ans, nums[n - 1] - nums[3]); 18 | // Case-III: Kill 2 largest, 1 smallest. 19 | ans = min(ans, nums[n - 3] - nums[1]); 20 | // Case-IV: Kill 2 smallest, 1 largest. 21 | ans = min(ans, nums[n - 2] - nums[2]); 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /Matrix/RichestCustomerWealth.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/richest-customer-wealth/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class RichestCustomerWealth { 8 | public: 9 | int maximumWealth(vector>& accounts) { 10 | int max_wealth = 0; 11 | for (int customer_index = 0; customer_index < accounts.size(); customer_index++) { 12 | int wealth = calculateWealth(accounts.at(customer_index)); 13 | if (wealth > max_wealth) { 14 | max_wealth = wealth; 15 | } 16 | } 17 | return max_wealth; 18 | } 19 | 20 | private: 21 | int calculateWealth(const vector& account) { 22 | int wealth = 0; 23 | for (int i = 0; i < account.size(); ++i) wealth += account[i]; 24 | return wealth; 25 | } 26 | }; -------------------------------------------------------------------------------- /Concurrency/SyncExecutor.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://www.educative.io/blog/top-five-concurrency-interview-questions-for-software-engineers 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class AsyncExecutor { 12 | public: 13 | void execute(function callback) { 14 | sleep(10); 15 | callback(); 16 | } 17 | }; 18 | 19 | class SyncExecutor: public AsyncExecutor { 20 | public: 21 | void execute(functioncallback) { 22 | function f = [this, callback] { 23 | callback(); 24 | cond.notify_all(); 25 | }; 26 | AsyncExecutor::execute(f); 27 | unique_lock lock(mtx_); 28 | cond.wait(lock); 29 | } 30 | 31 | private: 32 | mutex mtx_; 33 | condition_variable cond; 34 | }; -------------------------------------------------------------------------------- /Tree/MergeBinaryTrees.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/merge-two-binary-trees/ 2 | // Definition for a binary tree node. 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 11 | }; 12 | 13 | class MergeBinaryTrees { 14 | public: 15 | TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { 16 | if (root1 == nullptr) return root2; 17 | if (root2 == nullptr) return root1; 18 | TreeNode* newNode = new TreeNode(root1->val + root2->val); 19 | newNode->left = mergeTrees(root1->left, root2->left); 20 | newNode->right = mergeTrees(root1->right, root2->right); 21 | return newNode; 22 | } 23 | }; -------------------------------------------------------------------------------- /Array/ConsecutiveOnes/go/ConsecutiveOnes.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // FindMaxConsecutiveOnes 4 | // Time complexity: O(n) 5 | // Space complexity: O(1) 6 | func findMaxConsecutiveOnes(nums []int) int { 7 | n := len(nums) 8 | count, ans := 0, 0 9 | for i := 0; i < n; i++ { 10 | if nums[i] == 1 { 11 | count++ 12 | } else { 13 | count = 0 14 | } 15 | ans = max(ans, count) 16 | } 17 | return ans 18 | } 19 | 20 | // FindMaxConsecutiveOnes2 Simple create a number by adding 1 and update when it is 0 21 | // Time complexity: O(n) 22 | // Space complexity: O(1) 23 | func findMaxConsecutiveOnes2(nums []int) int { 24 | sum, ans := 0, 0 25 | for _, num := range nums { 26 | sum = sum*num + num 27 | ans = max(ans, sum) 28 | } 29 | return ans 30 | } 31 | 32 | func max(a, b int) int { 33 | if a > b { 34 | return a 35 | } 36 | return b 37 | } 38 | -------------------------------------------------------------------------------- /Array/FixedPoint/cpp/FixedPoint.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/fixed-point/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class FixedPoint { 8 | public: 9 | int fixedPoint(vector& arr) { 10 | return fixedPointInt(arr, 0, arr.size() - 1); 11 | } 12 | 13 | private: 14 | int fixedPointInt(vector& arr, int start, int end) { 15 | if (start > end) return -1; 16 | int mid = (end + start) / 2; 17 | if (arr[mid] == mid) { 18 | int index = mid; 19 | while (index >= 0 && arr[index] == index) { 20 | mid = index; 21 | index--; 22 | } 23 | return mid; 24 | } 25 | if (arr[mid] > mid) return fixedPointInt(arr, start, mid - 1); 26 | return fixedPointInt(arr, mid + 1, end); 27 | } 28 | }; -------------------------------------------------------------------------------- /HashTable/FindUniqueCharacter.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class FindUniqueCharacter { 8 | public: 9 | int firstUniqChar(const string& s) { 10 | int c_map[26]; 11 | for (int i = 0; i < 26; ++i) { 12 | c_map[i] = -1; 13 | } 14 | int c_index = -1; 15 | for (char ch : s) { 16 | ++c_index; 17 | int index = ch - 'a'; 18 | if (c_map[index] == -1) c_map[index] = c_index; 19 | else if (c_map[index] > -1) c_map[index] = -2; 20 | } 21 | int ans = s.size(); 22 | for (int i = 0; i < 26; ++i) { 23 | if (c_map[i] > -1) ans = min(ans, c_map[i]); 24 | } 25 | return ans == s.size() ? -1 : ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Heap/LastStoneWeight.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class LastStoneWeight { 7 | public: 8 | int lastStoneWeight(vector& stones) { 9 | make_heap(stones.begin(), stones.end()); 10 | while(stones.size() > 1) { 11 | int s1 = stones.front(); 12 | std::pop_heap(stones.begin(), stones.end()); 13 | stones.pop_back(); 14 | int s2 = stones.front(); 15 | std::pop_heap(stones.begin(), stones.end()); 16 | stones.pop_back(); 17 | if (s1 != s2) { 18 | stones.push_back(std::abs(s1 - s2)); 19 | std::push_heap(stones.begin(), stones.end()); 20 | } 21 | } 22 | if (stones.empty()) return 0; 23 | return stones[0]; 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/MoveZeroes.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/move-zeroes/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MoveZeroes { 8 | public: 9 | void moveZeroes(vector& nums) { 10 | if (nums.size() < 2) return; 11 | int zi = -1; 12 | int nzi = -1; 13 | for (int i = 0; i < nums.size(); ++i) { 14 | if (zi == -1 && nums[i] == 0) zi = i; 15 | if (zi == -1) continue; 16 | if (nzi == -1 && nums[i] != 0) nzi = i; 17 | // Nothing to swap so continue. 18 | if (zi == -1 || nzi == -1) continue; 19 | // Swap the numbers. 20 | nums[zi] = nums[nzi]; 21 | nums[nzi] = 0; 22 | // Need to find the next non-zero number's index. 23 | nzi = -1; 24 | zi++; 25 | } 26 | } 27 | }; -------------------------------------------------------------------------------- /DynamicProgramming/UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/unique-paths/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class UniquePaths { 9 | public: 10 | int uniquePaths(int m, int n) { 11 | unordered_map memo; 12 | return uniquePathsInt(m - 1, n - 1, memo); 13 | } 14 | 15 | private: 16 | int uniquePathsInt(int m, int n, unordered_map& memo) { 17 | if (m == 0 && n == 0) return 1; 18 | if (m < 0 || n < 0) return 0; 19 | const string key = std::to_string(m) + ":" + std::to_string(n); 20 | if (memo.find(key) != memo.end()) return memo[key]; 21 | int num_paths = uniquePathsInt(m - 1, n, memo) + uniquePathsInt(m , n -1, memo); 22 | memo[key] = num_paths; 23 | return num_paths; 24 | } 25 | }; -------------------------------------------------------------------------------- /Sorting/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class QuickSort { 6 | public: 7 | void sort(vector& nums) { 8 | qSort(nums, 0, nums.size() - 1); 9 | } 10 | 11 | private: 12 | void qSort(vector& nums, int low, int high) { 13 | if (low >= high) return; 14 | int p = partition(nums, low, high); 15 | qSort(nums, low, p - 1); 16 | qSort(nums, p + 1, high); 17 | } 18 | 19 | int partition(vector& nums, int low, int high) { 20 | int pivot = nums[high]; 21 | int i = low - 1; 22 | for (int j = low; j < high; ++j) { 23 | if (nums[j] < pivot) { 24 | ++i; 25 | swap(nums, j, i); 26 | } 27 | } 28 | swap(nums, i + 1, high); 29 | return (i + 1); 30 | } 31 | 32 | void swap(vector& nums, int i, int j) { 33 | int tmp = nums.at(i); 34 | nums[i] = nums[j]; 35 | nums[j] = tmp; 36 | } 37 | }; -------------------------------------------------------------------------------- /Array/ThirdMaxFinder.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/third-maximum-number/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class ThirdMaxFinder { 10 | public: 11 | int thirdMax(vector& nums) { 12 | if (nums.size() == 0) return 0; 13 | unordered_set nums_set; 14 | for (int index = 0; index < nums.size(); ++index) { 15 | nums_set.insert(nums[index]); 16 | } 17 | vector new_nums; 18 | unordered_set::iterator it; 19 | for (it = nums_set.begin(); it != nums_set.end(); ++it) { 20 | new_nums.push_back(*it); 21 | } 22 | std::sort(new_nums.begin(), new_nums.end(), greater()); 23 | if (new_nums.size() < 3) return new_nums[0]; 24 | return new_nums[2]; 25 | } 26 | }; -------------------------------------------------------------------------------- /Graph/FindTownJudge.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/find-the-town-judge/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class FindTownJudge { 8 | public: 9 | int findJudge(int n, vector>& trust) { 10 | vector incoming; 11 | vector outgoing; 12 | vector judges; 13 | incoming.resize(n + 1, 0); 14 | outgoing.resize(n + 1, 0); 15 | for (int i = 0; i < trust.size(); ++i) { 16 | outgoing[trust[i][0]]++; 17 | incoming[trust[i][1]]++; 18 | 19 | } 20 | for (int i = 1; i <= n; ++i) { 21 | if (incoming[i] == (n-1) && outgoing[i] == 0) { 22 | judges.push_back(i); 23 | } 24 | } 25 | if (judges.size() != 1) { return -1; } 26 | return judges.at(0); 27 | } 28 | }; -------------------------------------------------------------------------------- /Stack/CrawlerLogFolder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class CrawlerLogFolder { 7 | public: 8 | int minOperations(vector& logs) { 9 | stack folder_stack; 10 | int num_operations = 0; 11 | for (int index = 0; index < logs.size(); ++index) { 12 | string op = getOperation(logs[index]); 13 | if (op == ".") continue; 14 | if (op == "..") { 15 | if (not folder_stack.empty()) folder_stack.pop(); 16 | continue; 17 | } 18 | folder_stack.push(op); 19 | } 20 | return folder_stack.size(); 21 | } 22 | 23 | private: 24 | string getOperation(string str) { 25 | size_t pos = str.find('/'); 26 | // Note: pos is len here. 27 | return str.substr(0, pos); 28 | } 29 | }; -------------------------------------------------------------------------------- /Array/SortArrayByParity.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/sort-array-by-parity/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class SortArrayByParity { 8 | public: 9 | vector sortArrayByParity(vector& nums) { 10 | int odd = nums.size() - 1; 11 | int even = 0; 12 | while (even < odd) { 13 | if ((nums[even] % 2) == 0) { ++even; continue; } 14 | if ((nums[odd] % 2) == 1) { --odd; continue; } 15 | // Even has an odd digit. 16 | // Odd has an even digit. 17 | // Even is less than odd. 18 | swap(nums, odd, even); 19 | } 20 | return nums; 21 | } 22 | 23 | private: 24 | void swap(vector& nums, int i1, int i2) { 25 | int tmp = nums[i1]; 26 | nums[i1] = nums[i2]; 27 | nums[i2] = tmp; 28 | } 29 | }; -------------------------------------------------------------------------------- /Array/ArraysIntersection/cpp/ArraysIntersection.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/intersection-of-three-sorted-arrays/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class ArraysIntersection { 9 | public: 10 | vector arraysIntersection(vector& arr1, 11 | vector& arr2, 12 | vector& arr3) { 13 | vector result; 14 | unordered_set s1; 15 | unordered_set s2; 16 | for (int elem : arr1) s1.insert(elem); 17 | for (int elem : arr2) s2.insert(elem); 18 | for (int elem : arr3) { 19 | if (s1.find(elem) != s1.end() && s2.find(elem) != s2.end()) { 20 | result.push_back(elem); 21 | } 22 | } 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/LineChecker/go/LineChecker_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_checkStraightLine(t *testing.T) { 8 | type args struct { 9 | coordinates [][]int 10 | } 11 | tests := []struct { 12 | name string 13 | args args 14 | want bool 15 | }{ 16 | { 17 | name: "Test1", 18 | args: args{ 19 | coordinates: [][]int{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}}, 20 | }, 21 | want: true, 22 | }, 23 | { 24 | name: "Test2", 25 | args: args{ 26 | coordinates: [][]int{{1, 1}, {2, 2}, {3, 4}, {4, 5}, {5, 6}, {7, 7}}, 27 | }, 28 | want: false, 29 | }, 30 | } 31 | for _, tt := range tests { 32 | t.Run(tt.name, func(t *testing.T) { 33 | if got := checkStraightLine(tt.args.coordinates); got != tt.want { 34 | t.Errorf("checkStraightLine() = %v, want %v", got, tt.want) 35 | } 36 | }) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Graph/KeysAndRooms.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/keys-and-rooms/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | class KeysAndRooms { 8 | public: 9 | bool canVisitAllRooms(vector>& rooms) { 10 | unordered_set seen; 11 | queue rooms_q; 12 | rooms_q.push(0); 13 | while (rooms_q.size() > 0) { 14 | int curr_room = rooms_q.front(); rooms_q.pop(); 15 | seen.insert(curr_room); 16 | vector& dest_rooms = rooms[curr_room]; 17 | for (int i = 0; i < dest_rooms.size(); ++i) { 18 | int dest = dest_rooms[i]; 19 | if (seen.find(dest) != seen.end()) continue; 20 | rooms_q.push(dest); 21 | } 22 | } 23 | return seen.size() == rooms.size(); 24 | } 25 | }; -------------------------------------------------------------------------------- /String/ReverseVowels.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/reverse-vowels-of-a-string/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ReverseVowels { 8 | public: 9 | string reverseVowels(string s) { 10 | int lo = 0, hi = s.size() - 1; 11 | while (lo < hi) { 12 | while (hi > lo && not IsVowel(tolower(s[hi]))) --hi; 13 | while (lo < hi && not IsVowel(tolower(s[lo]))) ++lo; 14 | if (lo >= hi) break; 15 | swap(s, lo, hi); 16 | --hi; ++lo; 17 | } 18 | return s; 19 | } 20 | 21 | private: 22 | bool IsVowel(char ch) { 23 | return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'); 24 | } 25 | 26 | void swap(string& s, int l, int r) { 27 | char tmp = s[l]; 28 | s[l] = s[r]; 29 | s[r] = tmp; 30 | } 31 | }; -------------------------------------------------------------------------------- /Array/MakeTwoArraysEqual/go/MakeTwoArraysEqual_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_canBeEqual(t *testing.T) { 8 | type args struct { 9 | target []int 10 | arr []int 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want bool 16 | }{ 17 | { 18 | name: "Test 1", 19 | args: args{ 20 | target: []int{1, 2, 3, 4}, 21 | arr: []int{2, 4, 1, 3}, 22 | }, 23 | want: true, 24 | }, 25 | { 26 | name: "Test 2", 27 | args: args{ 28 | target: []int{1, 2, 3, 4}, 29 | arr: []int{2, 1, 1, 3}, 30 | }, 31 | want: false, 32 | }, 33 | } 34 | for _, tt := range tests { 35 | t.Run(tt.name, func(t *testing.T) { 36 | if got := canBeEqual(tt.args.target, tt.args.arr); got != tt.want { 37 | t.Errorf("canBeEqual() = %v, want %v", got, tt.want) 38 | } 39 | }) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /HashTable/HitCounter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class HitCounter { 6 | public: 7 | HitCounter() { 8 | times.resize(300, 0); 9 | hits.resize(300, 0); 10 | } 11 | 12 | void hit(int timestamp) { 13 | int t_mod = timestamp % 300; 14 | if (times[t_mod] != timestamp) { 15 | times[t_mod] = timestamp; 16 | hits[t_mod] = 1; 17 | } else { 18 | hits[t_mod]++; 19 | } 20 | 21 | } 22 | 23 | int getHits(int timestamp) { 24 | int sum = 0; 25 | for (int i = 0; i < 300; ++i) { 26 | int t_delta = timestamp - times[i]; 27 | if (t_delta < 300) { 28 | sum += hits[i]; 29 | } 30 | } 31 | return sum; 32 | } 33 | 34 | private: 35 | vector times; 36 | vector hits; 37 | }; 38 | -------------------------------------------------------------------------------- /Tree/BinaryTreeTilt.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/binary-tree-tilt/ 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 BinaryTreeTilt { 13 | public: 14 | int findTilt(TreeNode* root) { 15 | if (root == nullptr) return 0; 16 | int tilt = abs(findSum(root->left) - findSum(root->right)); 17 | return tilt + findTilt(root->left) + findTilt(root->right); 18 | } 19 | 20 | private: 21 | int findSum(TreeNode* root) { 22 | if (root == nullptr) return 0; 23 | return root->val + findSum(root->left) + findSum(root->right); 24 | } 25 | }; -------------------------------------------------------------------------------- /String/ValidPalindrome.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/valid-palindrome/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ValidPalindrome { 8 | private: 9 | string normalize(string s) { 10 | string out; 11 | for (int i = 0; i < s.size(); ++i) { 12 | char ch = s.at(i); 13 | if (std::isalnum(ch)) { 14 | out.append(1, std::tolower(ch)); 15 | } 16 | } 17 | return out; 18 | } 19 | 20 | public: 21 | bool isPalindrome(string s) { 22 | if (s.size() == 0) return true; 23 | string s_norm = normalize(s); 24 | 25 | int start = 0, end = s_norm.size() -1; 26 | while (start < end) { 27 | if (s_norm[start] != s_norm[end]) return false; 28 | ++start; 29 | --end; 30 | } 31 | return true; 32 | } 33 | }; -------------------------------------------------------------------------------- /Array/KthPositiveElement/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/kth-missing-positive-number/ 2 | ```text 3 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 4 | 5 | Return the kth positive integer that is missing from this array. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: arr = [2,3,4,7,11], k = 5 12 | Output: 9 13 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 14 | Example 2: 15 | 16 | Input: arr = [1,2,3,4], k = 2 17 | Output: 6 18 | Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= arr.length <= 1000 24 | 1 <= arr[i] <= 1000 25 | 1 <= k <= 1000 26 | arr[i] < arr[j] for 1 <= i < j <= arr.length 27 | 28 | 29 | Follow up: 30 | 31 | Could you solve this problem in less than O(n) complexity? 32 | ``` -------------------------------------------------------------------------------- /String/AddString.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/add-strings/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class AddString { 8 | public: 9 | string addStrings(const string& num1, const string& num2) { 10 | string num = ""; 11 | int carry_over = 0; 12 | int i = num1.size() - 1; 13 | int j = num2.size() - 1; 14 | while (i >= 0 || j >= 0) { 15 | int sum = carry_over; 16 | if (i >= 0) sum += (num1[i] - '0'); 17 | if (j >= 0) sum += (num2[j] - '0'); 18 | carry_over = sum/10; 19 | sum = sum % 10; 20 | num = to_string(sum) + num; 21 | --i; 22 | --j; 23 | } 24 | if (carry_over > 0) num = std::string("1") + num; 25 | return num; 26 | } 27 | }; -------------------------------------------------------------------------------- /HashTable/GroupAnagrams.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/group-anagrams/ 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class GroupAnagrams { 11 | public: 12 | vector> groupAnagrams(vector& strs) { 13 | vector> out; 14 | unordered_map> strs_map; 15 | for (int i = 0; i < strs.size(); ++i) { 16 | string st = strs[i]; 17 | std::sort(st.begin(), st.end()); 18 | strs_map[st].push_back(i); 19 | 20 | } 21 | unordered_map>::iterator it; 22 | for (it = strs_map.begin(); it != strs_map.end(); ++it) { 23 | vector indices = it->second; 24 | vector tmp; 25 | for (int i = 0; i < indices.size(); ++i) { 26 | tmp.push_back(strs[indices[i]]); 27 | } 28 | out.push_back(tmp); 29 | } 30 | return out; 31 | } 32 | }; -------------------------------------------------------------------------------- /Stack/ValidParantheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class ValidParantheses { 7 | public: 8 | bool isValid(string s) { 9 | stack s_stack; 10 | for (int index = 0; index < s.size(); ++index) { 11 | char ch = s[index]; 12 | if (ch == '(' || ch == '{' || ch == '[') { 13 | s_stack.push(ch); 14 | } else if (ch == ')' || ch == '}' || ch == ']') { 15 | if (s_stack.empty()) return false; 16 | char c2 = s_stack.top(); s_stack.pop(); 17 | if (not match(c2, ch)) return false; 18 | } 19 | } 20 | return s_stack.empty(); 21 | } 22 | 23 | bool match(char c1, char c2) { 24 | if (c1 == '(') return c2 == ')'; 25 | if (c1 == '{') return c2 == '}'; 26 | if (c1 == '[') return c2 == ']'; 27 | return true; 28 | } 29 | }; -------------------------------------------------------------------------------- /Array/KthPositiveElement/cpp/KthPositiveElement.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/kth-missing-positive-number/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class KthPositiveElement { 8 | public: 9 | int findKthPositive(vector& arr, int k) { 10 | vector missing_elems; 11 | int curr_num = 1; 12 | for (int i = 0; i < arr.size(); ++i) { 13 | if (arr[i] > curr_num) { 14 | 15 | for (int j = curr_num; j < arr[i]; ++j) { 16 | missing_elems.push_back(j); 17 | } 18 | } 19 | curr_num = arr[i] + 1; 20 | if (missing_elems.size() >= k) return missing_elems[k - 1]; 21 | } 22 | while (missing_elems.size() < k) { 23 | missing_elems.push_back(curr_num); 24 | curr_num++; 25 | } 26 | 27 | return missing_elems[k - 1]; 28 | } 29 | }; -------------------------------------------------------------------------------- /HashTable/TimeMap.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/time-based-key-value-store/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | /** 9 | * Your TimeMap object will be instantiated and called as such: 10 | * TimeMap* obj = new TimeMap(); 11 | * obj->set(key,value,timestamp); 12 | * string param_2 = obj->get(key,timestamp); 13 | */ 14 | class TimeMap { 15 | public: 16 | /** Initialize your data structure here. */ 17 | TimeMap() {} 18 | 19 | void set(string key, string value, int timestamp) { 20 | this->_h_map[key][timestamp] = value; 21 | } 22 | 23 | string get(string key, int timestamp) { 24 | auto it = this->_h_map[key].upper_bound(timestamp); 25 | return it == this->_h_map[key].begin() ? "" : prev(it)->second; 26 | } 27 | 28 | private: 29 | unordered_map> _h_map; 30 | }; -------------------------------------------------------------------------------- /HashTable/UncommonWords.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/uncommon-words-from-two-sentences/ 2 | 3 | using namespace std; 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class UncommonWords { 12 | public: 13 | vector uncommonFromSentences(string s1, string s2) { 14 | vector result; 15 | unordered_map words; 16 | string word; 17 | stringstream ss1(s1); 18 | stringstream ss2(s2); 19 | while(getline(ss1, word, ' ')) words[word]++; 20 | while(getline(ss2, word, ' ')) words[word]++; 21 | unordered_map::iterator it; 22 | for (it = words.begin(); it != words.end(); ++it) { 23 | if (it->second == 1) { 24 | result.push_back(it->first); 25 | } 26 | } 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /String/IsomorphicString.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/isomorphic-strings/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class IsomorphicString { 8 | public: 9 | bool isIsomorphic(const string& s, const string& t) { 10 | char lm[256]; 11 | bool seen_s[256]; 12 | bool seen_t[256]; 13 | memset(seen_s, false, sizeof(seen_s)); 14 | memset(seen_t, false, sizeof(seen_t)); 15 | for (int idx = 0; idx < s.size(); ++idx) { 16 | char ch_s = s[idx]; 17 | char ch_t = t[idx]; 18 | if (seen_s[ch_s]) { 19 | if (lm[ch_s] != ch_t) return false; 20 | } else { 21 | if (seen_t[ch_t]) return false; 22 | lm[ch_s] = ch_t; 23 | seen_s[ch_s] = true; 24 | seen_t[ch_t] = true; 25 | } 26 | } 27 | return true; 28 | } 29 | }; -------------------------------------------------------------------------------- /Tree/RangeSumBST.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/range-sum-of-bst/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Definition for a binary tree node. 8 | struct TreeNode { 9 | int val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 13 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 14 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 15 | }; 16 | 17 | class RangeSumBST { 18 | public: 19 | int rangeSumBST(TreeNode* root, int low, int high) { 20 | if (root == nullptr) return 0; 21 | int sum = 0; 22 | if (root->val >= low && root->val <= high) sum += root->val; 23 | if (root->val > low) sum += rangeSumBST(root->left, low, high); 24 | if (root->val < high) sum += rangeSumBST(root->right, low, high); 25 | return sum; 26 | } 27 | }; -------------------------------------------------------------------------------- /Heap/KthLargestFromStream.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/kth-largest-element-in-a-stream/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /** 10 | * Your KthLargest object will be instantiated and called as such: 11 | * KthLargest* obj = new KthLargest(k, nums); 12 | * int param_1 = obj->add(val); 13 | */ 14 | class KthLargestFromStream { 15 | public: 16 | KthLargest(int k, vector& nums) { 17 | max_size_ = k; 18 | for (int i = 0; i < nums.size(); ++i) { 19 | pq_.push(nums[i]); 20 | if (pq_.size() > k) pq_.pop(); 21 | } 22 | } 23 | 24 | int add(int val) { 25 | pq_.push(val); 26 | if (pq_.size() > max_size_) pq_.pop(); 27 | return pq_.top(); 28 | } 29 | 30 | private: 31 | priority_queue, std::greater> pq_; 32 | int max_size_; 33 | }; 34 | -------------------------------------------------------------------------------- /Tree/BalancedTreeValidator.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/balanced-binary-tree/ 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 BalancedTreeValidator { 13 | public: 14 | bool isBalanced(TreeNode* root) { 15 | if (root == nullptr) return true; 16 | if ((abs(getHeight(root->left) - getHeight(root->right))) > 1) return false; 17 | return isBalanced(root->left) && isBalanced(root->right); 18 | } 19 | 20 | private: 21 | int getHeight(TreeNode* root) { 22 | if (root == nullptr) return 0; 23 | return 1 + max(getHeight(root->left), getHeight(root->right)); 24 | } 25 | }; -------------------------------------------------------------------------------- /Array/RotateArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/rotate-array/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class RotateArray { 8 | public: 9 | void rotate(vector& nums, int k) { 10 | if (k == 0) return; 11 | int buffer[k]; 12 | int max_size = nums.size(); 13 | for (int i = 0; i < k; ++i) buffer[i] = 0; 14 | int num_changes = 0; 15 | int curr_index = 0; 16 | swapK(buffer, nums, curr_index, k); 17 | curr_index += k; 18 | while (num_changes < max_size) { 19 | swapK(buffer, nums, curr_index, min(k, max_size - num_changes)); 20 | num_changes += k; 21 | curr_index += k; 22 | } 23 | } 24 | 25 | private: 26 | void swap(int* a, int * b) { 27 | int temp = *b; 28 | *b = *a; 29 | *a = temp; 30 | } 31 | 32 | void swapK(int* a, vector& b, int s, int k) { 33 | int max_size = b.size(); 34 | for (int i = 0; i < k; ++i) { 35 | swap(a + i, &(b[(i + s) % max_size])); 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /Tree/PathSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/path-sum/ 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 PathSum { 13 | public: 14 | bool hasPathSum(TreeNode* root, int targetSum) { 15 | if (root == nullptr) return false; 16 | if (targetSum == root->val && isLeaf(root)) return true; 17 | return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val); 18 | } 19 | 20 | private: 21 | bool isLeaf(TreeNode* node) { 22 | if (node == nullptr) return false; 23 | return node->left == node-> right && node->left == nullptr; 24 | } 25 | }; -------------------------------------------------------------------------------- /Greedy/StockStrategy.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class StockStrategy { 9 | public: 10 | int maxProfit(vector& prices) { 11 | if (prices.size() < 2) return 0; 12 | int max_profit = 0; 13 | int buy_at = prices.at(0); 14 | int sell_at = prices.at(1); 15 | max_profit = std::max(sell_at - buy_at, max_profit); 16 | for (int i = 0; i < prices.size(); ++i) { 17 | int curr_price = prices.at(i); 18 | if (buy_at > curr_price) { 19 | buy_at = curr_price; 20 | sell_at = 0; 21 | } 22 | if (sell_at < curr_price) { 23 | sell_at = curr_price; 24 | } 25 | max_profit = std::max(sell_at - buy_at, max_profit); 26 | } 27 | return max_profit; 28 | } 29 | }; -------------------------------------------------------------------------------- /Stack/MakeStringGreat.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class MakeStringGreat { 7 | public: 8 | string makeGood(string s) { 9 | string out = ""; 10 | stack s_stack; 11 | for (int index = 0; index < s.size(); ++index) { 12 | if (s_stack.empty()) { 13 | s_stack.push(s[index]); 14 | continue; 15 | } 16 | char c1 = s_stack.top(); 17 | if (isBad(c1, s[index])) { 18 | s_stack.pop(); 19 | } else { 20 | s_stack.push(s[index]); 21 | } 22 | } 23 | while (not s_stack.empty()) { 24 | out = string(1, s_stack.top()) + out; 25 | s_stack.pop(); 26 | } 27 | return out; 28 | } 29 | 30 | private: 31 | bool isBad(char c1, char c2) { 32 | return ((c1 != c2) && (tolower(c1) == tolower(c2))); 33 | } 34 | }; -------------------------------------------------------------------------------- /Array/CreateTargetArray/cpp/CreateTargetArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/create-target-array-in-the-given-order/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class CreateTargetArray { 8 | public: 9 | vector createTargetArray(vector& nums, vector& index) { 10 | int max_size = nums.size(); 11 | vector target; 12 | if (max_size == 0) return target; 13 | for (int i = 0; i < max_size; ++i) { 14 | target.push_back(0); 15 | } 16 | for (int j = 0; j < max_size; ++j) { 17 | int target_index = index[j]; 18 | // Push back all the rest of the elements. 19 | int pos = max_size - 1; 20 | while (pos > target_index) { 21 | target[pos] = target[pos - 1]; 22 | --pos; 23 | } 24 | target[target_index] = nums[j]; 25 | } 26 | return target; 27 | } 28 | }; -------------------------------------------------------------------------------- /Array/CreateTargetArray/go/CreateTargetArray_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_createTargetArray(t *testing.T) { 9 | type args struct { 10 | nums []int 11 | index []int 12 | } 13 | tests := []struct { 14 | name string 15 | args args 16 | want []int 17 | }{ 18 | { 19 | name: "Test 1", 20 | args: args{ 21 | nums: []int{0, 1, 2, 3, 4}, 22 | index: []int{0, 1, 2, 2, 1}, 23 | }, 24 | want: []int{0, 4, 1, 3, 2}, 25 | }, 26 | { 27 | name: "Test 2", 28 | args: args{ 29 | nums: []int{1, 2, 3, 4, 0}, 30 | index: []int{0, 1, 2, 3, 0}, 31 | }, 32 | want: []int{0, 1, 2, 3, 4}, 33 | }, 34 | } 35 | for _, tt := range tests { 36 | t.Run(tt.name, func(t *testing.T) { 37 | if got := createTargetArray(tt.args.nums, tt.args.index); !reflect.DeepEqual(got, tt.want) { 38 | t.Errorf("createTargetArray() = %v, want %v", got, tt.want) 39 | } 40 | }) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Tree/PreOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/binary-tree-preorder-traversal/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // Definition for a binary tree node. 10 | struct TreeNode { 11 | int val; 12 | TreeNode *left; 13 | TreeNode *right; 14 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | }; 18 | 19 | class PreOrderTraversal { 20 | public: 21 | vector preorderTraversal(TreeNode* root) { 22 | stack st; 23 | vector result; 24 | if (root) st.push(root); 25 | while (st.size() > 0) { 26 | TreeNode* tmp = st.top(); st.pop(); 27 | result.push_back(tmp->val); 28 | if (tmp->right) st.push(tmp->right); 29 | if (tmp->left) st.push(tmp->left); 30 | } 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /Array/KthPositiveElement/go/KthPositiveElement_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_findKthPositive(t *testing.T) { 8 | type args struct { 9 | arr []int 10 | k int 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want int 16 | }{ 17 | { 18 | name: "test1", 19 | args: args{ 20 | arr: []int{2, 3, 4, 7, 11}, 21 | k: 5, 22 | }, 23 | want: 9, 24 | }, 25 | { 26 | name: "test2", 27 | args: args{ 28 | arr: []int{1, 2, 3, 4}, 29 | k: 2, 30 | }, 31 | want: 6, 32 | }, 33 | } 34 | for _, tt := range tests { 35 | t.Run(tt.name, func(t *testing.T) { 36 | if got := findKthPositive(tt.args.arr, tt.args.k); got != tt.want { 37 | t.Errorf("findKthPositive() = %v, want %v", got, tt.want) 38 | } 39 | if got := findKthPositive2(tt.args.arr, tt.args.k); got != tt.want { 40 | t.Errorf("findKthPositive()2 = %v, want %v", got, tt.want) 41 | } 42 | }) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Array/IsMonotone/go/IsMonotone.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // isMonotonic brute force solution 4 | // Time complexity: O(n) 5 | // Space complexity: O(1) 6 | func isMonotonic(nums []int) bool { 7 | if isMonotoneIncreasing(nums) || isMonotoneDecreasing(nums) { 8 | return true 9 | } 10 | return false 11 | } 12 | 13 | // isMonotonic2 clean code 14 | // Time complexity: O(n) 15 | // Space complexity: O(1) 16 | func isMonotonic2(nums []int) bool { 17 | inc, dec := true, true 18 | for i := 1; i < len(nums); i++ { 19 | inc = inc && nums[i] >= nums[i-1] 20 | dec = dec && nums[i] <= nums[i-1] 21 | } 22 | return inc || dec 23 | } 24 | 25 | func isMonotoneIncreasing(nums []int) bool { 26 | for i := 1; i < len(nums); i++ { 27 | if nums[i] < nums[i-1] { 28 | return false 29 | } 30 | } 31 | return true 32 | } 33 | 34 | func isMonotoneDecreasing(nums []int) bool { 35 | for i := 1; i < len(nums); i++ { 36 | if nums[i] > nums[i-1] { 37 | return false 38 | } 39 | } 40 | return true 41 | } 42 | -------------------------------------------------------------------------------- /LinkedList/BinaryTreeToDoublyLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/ 2 | 3 | class BinaryTreeToDoublyLinkedList { 4 | public: 5 | Node* treeToDoublyList(Node* root) { 6 | if (!root) return NULL; 7 | 8 | helper(root); 9 | // close DLL 10 | last->right = first; 11 | first->left = last; 12 | return first; 13 | } 14 | 15 | private: 16 | // the smallest (first) and the largest (last) nodes 17 | Node* first = NULL; 18 | Node* last = NULL; 19 | 20 | void helper(Node* node) { 21 | if (node) { 22 | // left 23 | helper(node->left); 24 | // node 25 | if (last) { 26 | // link the previous node (last) 27 | // with the current one (node) 28 | last->right = node; 29 | node->left = last; 30 | } 31 | else { 32 | // keep the smallest node 33 | // to close DLL later on 34 | first = node; 35 | } 36 | last = node; 37 | // right 38 | helper(node->right); 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /Graph/FindCenterOfGraph.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/find-center-of-star-graph/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class FindCenterOfGraph { 8 | public: 9 | int findCenter(vector>& edges) { 10 | int MAX_NODES = 100000; 11 | vector edge_size; 12 | edge_size.resize(MAX_NODES + 1, 0); 13 | int max_edge = INT_MIN; 14 | int max_edge_index = -1; 15 | for (int i = 0; i < edges.size(); i++) { 16 | edge_size[edges[i][0]]++; 17 | edge_size[edges[i][1]]++; 18 | if (max_edge < edge_size[edges[i][0]]) { 19 | max_edge = edge_size[edges[i][0]]; 20 | max_edge_index = edges[i][0]; 21 | } 22 | if (max_edge < edge_size[edges[i][1]]) { 23 | max_edge = edge_size[edges[i][1]]; 24 | max_edge_index = edges[i][1]; 25 | } 26 | } 27 | return max_edge_index; 28 | } 29 | }; -------------------------------------------------------------------------------- /Tree/IncreasingOrderSearchTree.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/increasing-order-search-tree/ 2 | 3 | // Definition for a binary tree node. 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 11 | }; 12 | 13 | class IncreasingOrderSearchTree { 14 | public: 15 | TreeNode* increasingBST(TreeNode* root) { 16 | if (root == nullptr) return root; 17 | TreeNode* leftTree = root; 18 | if (root->left != nullptr) { 19 | leftTree = increasingBST(root->left); 20 | TreeNode* rightMostNode = leftTree; 21 | while (rightMostNode->right != nullptr) rightMostNode = rightMostNode->right; 22 | rightMostNode->right = root; 23 | root->left = nullptr; 24 | } 25 | if (root->right != nullptr) root->right = increasingBST(root->right); 26 | return leftTree; 27 | } 28 | }; -------------------------------------------------------------------------------- /Tree/ConvertToBST.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Definition for a binary tree node. 8 | struct TreeNode { 9 | int val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 13 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 14 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 15 | }; 16 | 17 | class ConvertToBST { 18 | public: 19 | TreeNode* sortedArrayToBST(vector& nums) { 20 | return recurse(nums, 0, nums.size() - 1); 21 | } 22 | 23 | TreeNode* recurse(vector& nums, int s, int e) { 24 | if (s > e) return nullptr; 25 | int mid = (s + e) / 2; 26 | TreeNode* node = new TreeNode(nums[mid]); 27 | node->right = recurse(nums, mid + 1, e); 28 | node->left = recurse(nums, s, mid - 1); 29 | return node; 30 | } 31 | }; -------------------------------------------------------------------------------- /String/GoatLatin.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/goat-latin/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class GoatLatin { 9 | public: 10 | bool isVowel(char ch) { 11 | return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; 12 | } 13 | 14 | string toGoatLatin(string sentence) { 15 | string result; 16 | stringstream ss(sentence); 17 | string word; 18 | int index = 0; 19 | while (getline(ss, word, ' ')) { 20 | if (word.empty()) continue; 21 | string currWord = word; 22 | ++index; 23 | if (not isVowel(tolower(word[0]))) { 24 | currWord.append(1, currWord[0]); 25 | currWord.erase(currWord.begin()); 26 | } 27 | currWord += "ma"; 28 | currWord.append(index, 'a'); 29 | result += currWord + " "; 30 | } 31 | result.pop_back(); 32 | return result; 33 | } 34 | }; -------------------------------------------------------------------------------- /Array/DecompressRLE/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/decompress-run-length-encoded-list/ 2 | ```text 3 | We are given a list nums of integers representing a list compressed with run-length encoding. 4 | 5 | Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. 6 | 7 | Return the decompressed list. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [1,2,3,4] 14 | Output: [2,4,4,4] 15 | Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. 16 | The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. 17 | At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. 18 | Example 2: 19 | 20 | Input: nums = [1,1,2,3] 21 | Output: [1,3,3] 22 | 23 | 24 | Constraints: 25 | 26 | 2 <= nums.length <= 100 27 | nums.length % 2 == 0 28 | 1 <= nums[i] <= 100 29 | ``` -------------------------------------------------------------------------------- /DynamicProgramming/EggDrop.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class EggDrop { 8 | public: 9 | int twoEggDrop(int n) { 10 | memset(dp, -1, sizeof(dp)); 11 | return eggDropUtil(2, n); 12 | } 13 | 14 | private: 15 | int eggDropUtil(int eggs, int floors) { 16 | if (floors <= 1) return floors; 17 | if (floors == 2) return 2; 18 | if (eggs == 1) return floors; 19 | if (dp[eggs][floors] != -1) return dp[eggs][floors]; 20 | 21 | int result = INT_MAX; 22 | for (int i = 1; i <= floors; ++i) { 23 | result = min(result, 1 + 24 | max(eggDropUtil(eggs - 1, i - 1), // Egg breaks on Ith floor. 25 | eggDropUtil(eggs, floors - i))); // Egg doesn't break on the Ith floor. 26 | } 27 | dp[eggs][floors] = result; 28 | return dp[eggs][floors]; 29 | } 30 | 31 | int dp[3][1001]; 32 | }; -------------------------------------------------------------------------------- /HashTable/AlienDictionaryValidator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class AlienDictionaryValidator { 7 | public: 8 | 9 | bool isAlienSorted(vector& words, string order) { 10 | unordered_map order_map; 11 | for (int i = 0; i < order.size(); ++i) { 12 | order_map[order[i]] = i; 13 | } 14 | for (int i = 0; i < words.size() - 1; ++i) { 15 | if (not isSorted(words[i], words[i + 1], order_map)) return false; 16 | } 17 | return true; 18 | } 19 | 20 | private: 21 | bool isSorted(const string& word1, const string& word2, unordered_map& order_map) { 22 | for (int i = 0; i < min(word1.size(), word2.size()); ++i) { 23 | int pos1 = order_map[word1[i]]; 24 | int pos2 = order_map[word2[i]]; 25 | if (pos1 < pos2) return true; 26 | if (pos1 > pos2) return false; 27 | } 28 | return word1.size() <= word2.size(); 29 | } 30 | 31 | }; -------------------------------------------------------------------------------- /Miscellaneous/RomanToInteger.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/roman-to-integer/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class RomanToInteger { 8 | public: 9 | int romanToInt(const string& s) { 10 | int sum = 0; 11 | int i = 0; 12 | for (i = 0; i < s.size() - 1; ++i) { 13 | char c1 = s[i]; 14 | char c2 = s[i + 1]; 15 | if (isSmaller(c1, c2)) { 16 | sum += translateChar(c2) - translateChar(c1); 17 | ++i; 18 | } else sum += translateChar(c1); 19 | } 20 | if (i == s.size() - 1) { 21 | char c1 = s[i]; 22 | sum += translateChar(c1); 23 | } 24 | return sum; 25 | } 26 | 27 | private: 28 | int translateChar(char ch) { 29 | switch (ch) { 30 | case 'I': return 1; 31 | case 'V': return 5; 32 | case 'X': return 10; 33 | case 'L': return 50; 34 | case 'C': return 100; 35 | case 'D': return 500; 36 | case 'M': return 1000; 37 | } 38 | return 0; 39 | } 40 | 41 | bool isSmaller(char c1, char c2) { 42 | return (translateChar(c1) < translateChar(c2)); 43 | } 44 | }; -------------------------------------------------------------------------------- /Stack/MinStack.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/min-stack/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Node { 8 | Node(int v, int mv) : _val(v), _min_val(mv) {} 9 | int _val; 10 | int _min_val; 11 | }; 12 | 13 | /** 14 | * Your MinStack object will be instantiated and called as such: 15 | * MinStack* obj = new MinStack(); 16 | * obj->push(val); 17 | * obj->pop(); 18 | * int param_3 = obj->top(); 19 | * int param_4 = obj->getMin(); 20 | */ 21 | class MinStack { 22 | public: 23 | /** initialize your data structure here. */ 24 | MinStack() {} 25 | 26 | void push(int val) { 27 | int min_val = val; 28 | if (not this->_st.empty()) { 29 | min_val = min(val, this->_st.top()._min_val); 30 | } 31 | this->_st.push(Node(val, min_val)); 32 | } 33 | 34 | void pop() { this->_st.pop(); } 35 | int top() { return this->_st.top()._val; } 36 | int getMin() { return this->_st.top()._min_val; } 37 | 38 | private: 39 | stack _st; 40 | }; -------------------------------------------------------------------------------- /Array/LCISFinder/go/LCISFinder_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_findLengthOfLCIS(t *testing.T) { 8 | type args struct { 9 | nums []int 10 | } 11 | tests := []struct { 12 | name string 13 | args args 14 | want int 15 | }{ 16 | { 17 | name: "Test 1", 18 | args: args{ 19 | nums: []int{1, 3, 5, 4, 7}, 20 | }, 21 | want: 3, 22 | }, 23 | { 24 | name: "Test 2", 25 | args: args{ 26 | nums: []int{1, 3, 5, 7, 9, 11, 13, 15}, 27 | }, 28 | want: 8, 29 | }, 30 | { 31 | name: "Test 3", 32 | args: args{ 33 | nums: []int{1, 1, 1, 1, 1}, 34 | }, 35 | want: 1, 36 | }, 37 | } 38 | for _, tt := range tests { 39 | t.Run(tt.name, func(t *testing.T) { 40 | if got := findLengthOfLCIS(tt.args.nums); got != tt.want { 41 | t.Errorf("findLengthOfLCIS() = %v, want %v", got, tt.want) 42 | } 43 | if got := findLengthOfLCIS2(tt.args.nums); got != tt.want { 44 | t.Errorf("findLengthOfLCIS2() = %v, want %v", got, tt.want) 45 | } 46 | }) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /DynamicProgramming/CountSortedVowelStrings.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/count-sorted-vowel-strings/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class CountSortedVowelStrings { 8 | public: 9 | int countVowelStrings(int n) { 10 | vector> memo; 11 | for (int i = 0; i <= n; ++i) { 12 | memo.push_back({}); 13 | for (int j = 0; j <= 5; ++j) { 14 | int num = -1; 15 | if (i == 0 || j == 0) num = 0; 16 | else if (i == 1) num = j; 17 | else if (j == 1) num = 1; 18 | memo.back().push_back(num); 19 | } 20 | } 21 | return countVowelUtil(n, 5, memo); 22 | } 23 | 24 | private: 25 | int countVowelUtil(int n, int vowels, vector>& memo) { 26 | if (memo[n][vowels] != -1) return memo[n][vowels]; 27 | memo[n][vowels] = countVowelUtil(n - 1, vowels, memo) + countVowelUtil(n, vowels - 1, memo); 28 | return memo[n][vowels]; 29 | } 30 | }; -------------------------------------------------------------------------------- /HashTable/OrderedStream.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/design-an-ordered-stream/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | /** 9 | * Your OrderedStream object will be instantiated and called as such: 10 | * OrderedStream* obj = new OrderedStream(n); 11 | * vector param_1 = obj->insert(idKey,value); 12 | */ 13 | class OrderedStream { 14 | public: 15 | OrderedStream(int n) { 16 | size_ = n; 17 | seen_.resize(size_, false); 18 | stream_.resize(size_, ""); 19 | } 20 | 21 | vector insert(int idKey, string value) { 22 | stream_[idKey - 1] = value; 23 | seen_[idKey - 1] = true; 24 | vector result; 25 | while(curr_ < size_ && seen_[curr_]) { 26 | result.push_back(stream_[curr_]); 27 | curr_++; 28 | } 29 | return result; 30 | } 31 | 32 | private: 33 | int size_; 34 | int curr_ = 0; 35 | vector seen_; 36 | vector stream_; 37 | }; -------------------------------------------------------------------------------- /Miscellaneous/LongestConsecutiveSequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class LongestConsecutiveSequence { 6 | public: 7 | int longestConsecutive(vector& nums) { 8 | // Step-I: De-duplicate elements. 9 | unordered_set nums_set; 10 | for (const int num : nums) nums_set.insert(num); 11 | int max_len = 0; 12 | 13 | // Step-II: For each num, find the longest groups (ascending, descending). 14 | for (const int num : nums) { 15 | int steps = 1; 16 | int curr_len = 1; 17 | // Step-II(a): Go up. 18 | while (nums_set.find(num + steps) != nums_set.end()) { 19 | nums_set.erase(num + steps); 20 | ++curr_len; 21 | ++steps; 22 | } 23 | // Step-II(b): Go down. 24 | steps = 1; 25 | while (nums_set.find(num - steps) != nums_set.end()) { 26 | nums_set.erase(num - steps); 27 | ++curr_len; 28 | ++steps; 29 | } 30 | max_len = std::max(max_len, curr_len); 31 | } 32 | return max_len; 33 | } 34 | }; -------------------------------------------------------------------------------- /String/BuddyStringFinder.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/buddy-strings/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class BuddyStringFinder { 8 | public: 9 | bool buddyStrings(string s, string goal) { 10 | if (s.size() != goal.size()) return false; 11 | int count = 0; 12 | vector chars_s, chars_goal; 13 | unordered_map char_count; 14 | int max_char_len = 0; 15 | for (int i = 0; i < s.size(); ++i) { 16 | char_count[s[i]]++; 17 | if (max_char_len < char_count[s[i]]) { 18 | max_char_len = char_count[s[i]]; 19 | } 20 | if (s[i] != goal[i]) { 21 | count++; 22 | chars_s.push_back(s[i]); 23 | chars_goal.push_back(goal[i]); 24 | } 25 | if (count > 2) break; 26 | } 27 | if (count == 2) { 28 | if ((chars_s.at(0) == chars_goal.at(1)) && (chars_s.at(1) == chars_goal.at(0))) { 29 | return true; 30 | } 31 | } 32 | if (count == 0) return max_char_len > 1; 33 | return false; 34 | } 35 | }; -------------------------------------------------------------------------------- /Tree/RemoveNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | 3 | // Definition for singly-linked list. 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode() : val(0), next(nullptr) {} 8 | ListNode(int x) : val(x), next(nullptr) {} 9 | ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | }; 11 | 12 | class RemoveNthNodeFromEndOfList { 13 | public: 14 | ListNode* removeNthFromEnd(ListNode* head, int n) { 15 | ListNode* p1 = head; 16 | ListNode* p2 = p1; 17 | int count = 0; 18 | // Maintaining a delta of n between p1 & p2. 19 | while (count < n) { 20 | p2 = p2->next; 21 | ++count; 22 | } 23 | // Moving p2 to the end of the list. 24 | while (p2 && p2->next) { 25 | p1 = p1->next; 26 | p2 = p2->next; 27 | } 28 | ListNode* tmp = p1->next; 29 | p1->next = tmp->next; 30 | tmp = nullptr; 31 | return head; 32 | } 33 | }; -------------------------------------------------------------------------------- /Backtracking/ParanthesesGenerator.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/generate-parentheses/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class ParanthesesGenerator { 9 | public: 10 | vector generateParenthesis(int n) { 11 | vector result; 12 | string curr; 13 | generateAll(result, n, 0, 0, curr); 14 | return result; 15 | } 16 | 17 | void generateAll(vector& result, int n, int open, int closed, string& curr) { 18 | if (closed == n) { 19 | result.push_back(curr); 20 | return; 21 | } 22 | 23 | if (open < n) { 24 | curr += "("; 25 | generateAll(result, n, open + 1, closed, curr); 26 | curr.erase(curr.size() - 1, 1); 27 | } 28 | 29 | if (closed < open) { 30 | curr += ")"; 31 | generateAll(result, n, open, closed + 1, curr); 32 | curr.erase(curr.size() - 1, 1); 33 | } 34 | } 35 | }; -------------------------------------------------------------------------------- /Graph/EmployeeImportance.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/employee-importance/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Definition for Employee. 9 | struct Employee { 10 | int id; 11 | int importance; 12 | vector subordinates; 13 | }; 14 | 15 | class EmployeeImportance { 16 | public: 17 | int getImportance(vector employees, int id) { 18 | unordered_map h_map; 19 | for (int i = 0; i < employees.size(); ++i) { 20 | Employee* employee = employees[i]; 21 | h_map[employee->id] = employee; 22 | } 23 | return dfs(h_map, id); 24 | } 25 | 26 | int dfs(const unordered_map & h_map, int id) { 27 | Employee* employee = h_map.at(id); 28 | int importance = employee->importance; 29 | for (int i = 0; i < employee->subordinates.size(); ++i) { 30 | importance += dfs(h_map, employee->subordinates[i]); 31 | } 32 | return importance; 33 | } 34 | }; -------------------------------------------------------------------------------- /Miscellaneous/MovingAverage.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/moving-average-from-data-stream/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | /** 8 | * Your MovingAverage object will be instantiated and called as such: 9 | * MovingAverage* obj = new MovingAverage(size); 10 | * double param_1 = obj->next(val); 11 | */ 12 | class MovingAverage { 13 | public: 14 | MovingAverage(int size) { 15 | _sum = 0; 16 | _max_size = size; 17 | _curr_size = 0; 18 | } 19 | 20 | double next(int val) { 21 | if (_buffer.size() < _max_size) { 22 | _sum += val; 23 | _buffer.push_back(val); 24 | ++_curr_size; 25 | } else { 26 | _sum += val - _buffer[0]; 27 | _buffer.erase(_buffer.begin()); 28 | _buffer.push_back(val); 29 | } 30 | return (double)_sum/(double)_curr_size; 31 | } 32 | 33 | private: 34 | vector _buffer; 35 | int _sum; 36 | int _max_size; 37 | int _curr_size; 38 | }; -------------------------------------------------------------------------------- /Concurrency/ReaderWriterLock.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://www.educative.io/blog/top-five-concurrency-interview-questions-for-software-engineers 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class ReaderWriterLock { 10 | public: 11 | ReaderWriterLock(): num_readers_(0), num_writers_(0) {} 12 | 13 | void AcquireReadLock() { 14 | mtx_.lock(); 15 | ++num_readers_; 16 | mtx_.unlock(); 17 | } 18 | 19 | void AcquireWriteLock() { 20 | std::unique_lock lock(mtx_); 21 | cond.wait(lock, [this] { 22 | return num_readers_ == 0; 23 | }); 24 | ++num_writers_; 25 | } 26 | 27 | void ReleaseReadLock() { 28 | mtx_.lock(); 29 | --num_readers_; 30 | if (num_readers_ == 0) cond.notify_all(); 31 | mtx_.unlock(); 32 | } 33 | 34 | void ReleaseWriteLock() { 35 | --num_writers_; 36 | mtx_.unlock(); 37 | } 38 | 39 | private: 40 | std::condition_variable cond; 41 | std::mutex mtx_; 42 | int num_readers_; 43 | int num_writers_; 44 | }; 45 | 46 | -------------------------------------------------------------------------------- /Greedy/CanPlaceFlowers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class CanPlaceFlowers { 6 | public: 7 | bool canPlaceFlowers(vector& flowerbed, int n) { 8 | vector canPlace; 9 | int numPlaced = 0; 10 | for (int index = 0; index < flowerbed.size(); ++index) canPlace.push_back(true); 11 | for (int index = 0; index < flowerbed.size(); ++index) { 12 | if (flowerbed[index] == 1) { 13 | canPlace[index] = false; 14 | if (index > 0) canPlace[index - 1] = false; 15 | if (index < flowerbed.size() - 1) canPlace[index + 1] = false; 16 | } 17 | } 18 | for (int index = 0; index < flowerbed.size(); ++index) { 19 | if (canPlace[index]) { 20 | canPlace[index] = false; 21 | if (index < flowerbed.size() - 1) { 22 | canPlace[index + 1] = false; 23 | } 24 | ++numPlaced; 25 | } 26 | } 27 | return numPlaced >= n; 28 | } 29 | }; -------------------------------------------------------------------------------- /BitManipulation/SubsetXORSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/sum-of-all-subset-xor-totals/ 2 | 3 | #include 4 | 5 | class SubsetXORSum { 6 | public: 7 | int subsetXORSum(vector& nums) { 8 | vector subset; 9 | int sum = 0; 10 | for (int i = 0; i < nums.size(); ++i) subset.push_back(false); 11 | getNext(0, nums, subset, sum); 12 | return sum; 13 | } 14 | 15 | private: 16 | void getNext(int index, vector& nums, vector& subset, int& sum) { 17 | if (index >= subset.size()) return; 18 | subset[index] = true; 19 | getNext(index + 1, nums, subset, sum); 20 | sum += getXOR(nums, subset); 21 | subset[index] = false; 22 | getNext(index + 1, nums, subset, sum); 23 | } 24 | 25 | int getXOR(const vector& nums, const vector& subset) { 26 | int result = 0; 27 | for (int i = 0; i < subset.size(); ++i) { 28 | if (subset[i]) result ^= nums[i]; 29 | } 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Greedy/MaximumUnitsTruck.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/maximum-units-on-a-truck/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class MaximumUnitsTruck { 9 | public: 10 | int maximumUnits(vector>& boxTypes, int truckSize) { 11 | // Flatten 12 | vector units; 13 | for (int i = 0; i < boxTypes.size(); ++i) { 14 | const vector boxUnits = boxTypes.at(i); 15 | for (int j = 0; j < boxUnits.at(0); ++j) { 16 | units.push_back(boxUnits.at(1)); 17 | } 18 | } 19 | // Sort 20 | std::sort(units.begin(), units.end(), std::greater()); 21 | 22 | // Run Greedy. 23 | int total_units = 0; 24 | int curr_size = 0; 25 | for (int i = 0; i < units.size(); ++i) { 26 | if (curr_size == truckSize) break; 27 | total_units += units.at(i); 28 | curr_size++; 29 | } 30 | return total_units; 31 | } 32 | }; -------------------------------------------------------------------------------- /Array/KthPositiveElement/go/KthPositiveElement.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // findKthPositive inc k if there is any missing number or less than k 4 | // TimeComplexity: O(n) 5 | // SpaceComplexity: O(1) 6 | func findKthPositive(arr []int, k int) int { 7 | for _, v := range arr { 8 | if v <= k { 9 | k++ 10 | } else { 11 | break 12 | } 13 | } 14 | return k 15 | } 16 | 17 | // findKthPositive2 at any index number of missing values = current value at index - index - 1, now you can binary search 18 | // example: 2 3 4 7 11 k =5, max right should be 5 but there is 11, diff = 11 - 5 = 6, which means 6 number is missing in the array, go left 19 | // example: 1 2 3 4 k=2, max right should be 2 but there is 4, diff = 4 - 4 = 0, which means 0 number is missing in the array, go right 20 | // TimeComplexity: O(logn) 21 | // SpaceComplexity: O(1) 22 | func findKthPositive2(arr []int, k int) int { 23 | l, r := 0, len(arr)-1 24 | for l <= r { 25 | mid := l + (r-l)/2 26 | if arr[mid]-mid > k { 27 | r = mid - 1 28 | } else { 29 | l = mid + 1 30 | } 31 | } 32 | return k + l 33 | } 34 | -------------------------------------------------------------------------------- /Array/ArrayIntersection/go/ArrayIntersection_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_intersection(t *testing.T) { 9 | type args struct { 10 | nums1 []int 11 | nums2 []int 12 | } 13 | tests := []struct { 14 | name string 15 | args args 16 | want []int 17 | }{ 18 | { 19 | name: "Test 1", 20 | args: args{ 21 | nums1: []int{1, 2, 2, 1}, 22 | nums2: []int{2, 2}, 23 | }, 24 | want: []int{2}, 25 | }, 26 | { 27 | name: "Test 2", 28 | args: args{ 29 | nums1: []int{4, 9, 5}, 30 | nums2: []int{9, 4, 9, 8, 4}, 31 | }, 32 | want: []int{9, 4}, 33 | }, 34 | } 35 | for _, tt := range tests { 36 | t.Run(tt.name, func(t *testing.T) { 37 | if got := intersection(tt.args.nums1, tt.args.nums2); !reflect.DeepEqual(got, tt.want) { 38 | t.Errorf("intersection() = %v, want %v", got, tt.want) 39 | } 40 | if got := intersection2(tt.args.nums1, tt.args.nums2); !reflect.DeepEqual(got, tt.want) { 41 | t.Errorf("intersection()2 = %v, want %v", got, tt.want) 42 | } 43 | }) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Array/IntervalListIntersections/go/IntervalListIntersections.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // intervalIntersection check the intersection of two interval lines and once it collide, append the overlap to the result 4 | // Time complexity: O(m + n) 5 | // Space complexity: O(m + n) 6 | func intervalIntersection(firstList [][]int, secondList [][]int) [][]int { 7 | m, n := len(firstList), len(secondList) 8 | i, j := 0, 0 9 | result := make([][]int, 0) 10 | for i < m && j < n { 11 | if intersects(firstList[i], secondList[j]) { 12 | result = append(result, overlap(firstList[i], secondList[j])) 13 | } 14 | if firstList[i][1] < secondList[j][1] { 15 | i++ 16 | } else { 17 | j++ 18 | } 19 | } 20 | return result 21 | } 22 | func intersects(a, b []int) bool { 23 | return a[0] <= b[1] && b[0] <= a[1] 24 | } 25 | func overlap(a, b []int) []int { 26 | return []int{max(a[0], b[0]), min(a[1], b[1])} 27 | } 28 | func max(a, b int) int { 29 | if a > b { 30 | return a 31 | } 32 | return b 33 | } 34 | func min(a, b int) int { 35 | if a < b { 36 | return a 37 | } 38 | return b 39 | } 40 | -------------------------------------------------------------------------------- /Array/LCISFinder/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/longest-continuous-increasing-subsequence/ 2 | 3 | ```text 4 | 5 | Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. 6 | 7 | A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [1,3,5,4,7] 14 | Output: 3 15 | Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3. 16 | Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 17 | 4. 18 | Example 2: 19 | 20 | Input: nums = [2,2,2,2,2] 21 | Output: 1 22 | Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly 23 | increasing. 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 104 29 | -109 <= nums[i] <= 109 30 | ``` -------------------------------------------------------------------------------- /Array/LCISFinder/go/LCISFinder.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // typically check the continuos increasing subarray and store the max in a third var 4 | // Time complexity: O(n) 5 | // Space complexity: O(1) 6 | func findLengthOfLCIS(nums []int) int { 7 | if len(nums) <= 1 { 8 | return len(nums) 9 | } 10 | ans, count := 1, 1 11 | for i := 0; i < len(nums)-1; i++ { 12 | if nums[i] < nums[i+1] { 13 | count++ 14 | ans = max(ans, count) 15 | } else { 16 | count = 1 17 | } 18 | } 19 | return ans 20 | } 21 | func max(a, b int) int { 22 | if a > b { 23 | return a 24 | } 25 | return b 26 | } 27 | 28 | // just used an extra storage to store all those states 29 | // Time complexity: O(n) 30 | // Space complexity: O(n) 31 | func findLengthOfLCIS2(nums []int) int { 32 | if len(nums) <= 1 { 33 | return len(nums) 34 | } 35 | dp := make([]int, len(nums)) 36 | dp[0] = 1 37 | ans := 1 38 | for i := 1; i < len(nums); i++ { 39 | if nums[i] > nums[i-1] { 40 | dp[i] = dp[i-1] + 1 41 | } else { 42 | dp[i] = 1 43 | } 44 | ans = max(ans, dp[i]) 45 | } 46 | return ans 47 | } 48 | -------------------------------------------------------------------------------- /Array/HIndexCalculator/go/HIndexCalculator.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | // hIndex store the index for all of citation, if greater than length inc else inc the value one 8 | // Time complexity: O(n) 9 | // Space complexity: O(n) 10 | func hIndex(citations []int) int { 11 | bucket := make(map[int]int, len(citations)+1) 12 | for _, v := range citations { 13 | if v > len(citations) { 14 | bucket[len(citations)]++ 15 | } else { 16 | bucket[v]++ 17 | } 18 | } 19 | count := 0 20 | for i := len(citations); i >= 0; i-- { 21 | count += bucket[i] 22 | if count >= i { 23 | return i 24 | } 25 | } 26 | return 0 27 | } 28 | 29 | // hIndex2 sort the citation and binary search 30 | // Time complexity: O(nlog(n)) 31 | // Space complexity: O(1) 32 | func hIndex2(citations []int) int { 33 | low, high := 0, len(citations)-1 34 | sort.Ints(citations) 35 | for low <= high { 36 | mid := low + (high-low)/2 37 | if citations[mid] >= len(citations)-mid { 38 | high = mid - 1 39 | } else { 40 | low = mid + 1 41 | } 42 | } 43 | return len(citations) - low 44 | } 45 | -------------------------------------------------------------------------------- /DynamicProgramming/CountDifferSubstrings.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/count-substrings-that-differ-by-one-character/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class CountDifferSubstrings { 8 | public: 9 | int countSubstrings(string s, string t) { 10 | int dp[s.size() + 1][t.size() + 1][2]; 11 | for (int i = 0; i <= s.size(); ++i) { 12 | for (int j = 0; j <= t.size(); ++j) { 13 | dp[i][j][0] = 0; 14 | dp[i][j][1] = 0; 15 | } 16 | } 17 | int sum = 0; 18 | for (int i = 1; i <= s.size(); ++i) { 19 | for (int j = 1; j <= t.size(); ++j) { 20 | if (s[i - 1] == t[j - 1]) { 21 | dp[i][j][0] = dp[i-1][j-1][0] + 1; 22 | dp[i][j][1] = dp[i-1][j-1][1]; 23 | } else { 24 | dp[i][j][0] = 0; 25 | dp[i][j][1] = dp[i-1][j-1][0] + 1; 26 | } 27 | sum += dp[i][j][1]; 28 | } 29 | } 30 | return sum; 31 | } 32 | }; -------------------------------------------------------------------------------- /Sorting/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class HeapSort { 6 | public: 7 | void sort(vector& nums) { 8 | vector result; 9 | int size = nums.size(); 10 | for (int i = size / 2 - 1; i >= 0; --i) { 11 | heapify(nums, nums.size(), i); 12 | } 13 | for (int i = size - 1; i >= 0; --i) { 14 | swap(nums, i, 0); 15 | heapify(nums, i, 0); 16 | } 17 | } 18 | 19 | private: 20 | void heapify(vector& nums, int size, int index) { 21 | int l = 2 * index + 1; 22 | int r = 2 * index + 2; 23 | int largest = index; 24 | if (l < size && nums[largest] < nums[l]) largest = l; 25 | if (r < size && nums[largest] < nums[r]) largest = r; 26 | if (largest != index) { 27 | swap(nums, largest, index); 28 | heapify(nums, size, largest); 29 | } 30 | } 31 | void swap(vector& nums, int i, int j) { 32 | int tmp = nums.at(i); 33 | nums[i] = nums[j]; 34 | nums[j] = tmp; 35 | } 36 | 37 | }; -------------------------------------------------------------------------------- /Tree/ElementsInBinaryTrees.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Definition for a binary tree node. 9 | struct TreeNode { 10 | int val; 11 | TreeNode *left; 12 | TreeNode *right; 13 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 | }; 17 | 18 | class ElementsInBinaryTrees { 19 | public: 20 | vector getAllElements(TreeNode* root1, TreeNode* root2) { 21 | vector result; 22 | parse(root1, result); 23 | parse(root2, result); 24 | sort(result.begin(), result.end()); 25 | return result; 26 | } 27 | 28 | void parse(TreeNode* root, vector& result) { 29 | if (root == nullptr) return; 30 | result.push_back(root->val); 31 | parse(root->left, result); 32 | parse(root->right, result); 33 | } 34 | }; -------------------------------------------------------------------------------- /Backtracking/Combinations.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/combinations/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Combinations { 8 | public: 9 | bool taken[20]; 10 | 11 | vector getCombination(int n) { 12 | vector result; 13 | for (int i = 0; i < n; ++i) { 14 | if (taken[i]) result.push_back(i + 1); 15 | } 16 | return result; 17 | } 18 | 19 | vector> combine(int n, int k) { 20 | memset(taken, false, sizeof(taken)); 21 | vector> result; 22 | next(0, n, k, result); 23 | return result; 24 | } 25 | 26 | void next(int index, int n, int k, vector>& result) { 27 | if (k < 0) return; 28 | if (k == 0) { 29 | result.push_back(getCombination(n)); 30 | return; 31 | } 32 | if (index >= n) return; 33 | taken[index] = true; 34 | next(index + 1, n, k -1, result); 35 | taken[index] = false; 36 | next(index + 1, n, k, result); 37 | } 38 | }; -------------------------------------------------------------------------------- /Array/HIndexCalculator/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/h-index/ 2 | ```text 3 | Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index. 4 | 5 | According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. 6 | 7 | If there are several possible values for h, the maximum one is taken as the h-index. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: citations = [3,0,6,1,5] 14 | Output: 3 15 | Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. 16 | Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. 17 | Example 2: 18 | 19 | Input: citations = [1,3,1] 20 | Output: 1 21 | 22 | 23 | Constraints: 24 | 25 | n == citations.length 26 | 1 <= n <= 5000 27 | 0 <= citations[i] <= 1000 28 | ``` -------------------------------------------------------------------------------- /Heap/KClosestPointsToOrigin.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/k-closest-points-to-origin/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Point { 9 | public: 10 | Point (int x, int y) { 11 | _x = x; 12 | _y = y; 13 | _distance = pow(_x, 2) + pow(_y, 2); 14 | } 15 | 16 | int _x; 17 | int _y; 18 | double _distance; 19 | }; 20 | 21 | struct ComparePointDistance { 22 | inline bool operator()(const Point& p1, const Point& p2) { 23 | return p1._distance > p2._distance; 24 | } 25 | }; 26 | 27 | class KClosestPointsToOrigin { 28 | public: 29 | vector> kClosest(vector>& points, int k) { 30 | vector> output; 31 | priority_queue, ComparePointDistance> pq; 32 | for (int i = 0; i < points.size(); ++i) { 33 | pq.push(Point(points[i][0], points[i][1])); 34 | } 35 | for (int i = 1; i <= k; ++i) { 36 | Point p = pq.top(); 37 | vector v; 38 | v.push_back(p._x); 39 | v.push_back(p._y); 40 | output.push_back(v); 41 | pq.pop(); 42 | } 43 | return output; 44 | } 45 | }; -------------------------------------------------------------------------------- /Sorting/HighFive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class HighFive { 6 | public: 7 | struct CompareScore { 8 | inline bool operator()(const vector& s1, const vector& s2) { 9 | if (s1[0] < s2[0]) return true; 10 | else if (s1[0] == s2[0]) return (s1[1] > s2[1]); 11 | return false; 12 | } 13 | }; 14 | 15 | vector> highFive(vector>& items) { 16 | vector> average_scores; 17 | sort(items.begin(), items.end(), CompareScore()); 18 | int prev_index = 0; 19 | for (int i = 0; i < items.size() - 4; ++i) { 20 | if (prev_index == items[i][0]) continue; 21 | int average = (items[i][1] + items[i + 1][1] + items[i + 2][1] + items[i + 3][1] + items[i + 4][1]) / 5; 22 | vector values; 23 | values.push_back(items[i][0]); 24 | values.push_back(average); 25 | average_scores.push_back(values); 26 | prev_index = items[i][0]; 27 | } 28 | return average_scores; 29 | } 30 | }; -------------------------------------------------------------------------------- /Array/FixedPoint/go/FixedPoint_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_fixedPoint(t *testing.T) { 8 | type args struct { 9 | nums []int 10 | } 11 | tests := []struct { 12 | name string 13 | args args 14 | want int 15 | }{ 16 | { 17 | name: "Test 1", 18 | args: args{ 19 | nums: []int{1, 3, -1, -3, 5, 3, 6, 7}, 20 | }, 21 | want: 6, 22 | }, 23 | { 24 | name: "Test 2", 25 | args: args{ 26 | nums: []int{1, 2, 3}, 27 | }, 28 | want: -1, 29 | }, 30 | { 31 | name: "Test 3", 32 | args: args{ 33 | nums: []int{0, 1, 2, 3, 4}, 34 | }, 35 | want: 0, 36 | }, 37 | { 38 | name: "Test 4", 39 | args: args{ 40 | nums: []int{}, 41 | }, 42 | want: -1, 43 | }, 44 | } 45 | for _, tt := range tests { 46 | t.Run(tt.name, func(t *testing.T) { 47 | if got := fixedPoint(tt.args.nums); got != tt.want { 48 | t.Errorf("fixedPoint() = %v, want %v", got, tt.want) 49 | } 50 | if got := fixedPoint2(tt.args.nums); got != tt.want { 51 | t.Errorf("fixedPoint()2 = %v, want %v", got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Array/SortByIncreasingFrequency.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/sort-array-by-increasing-frequency/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Elem { 8 | Elem(int v, int f) : val(v), freq(f) {} 9 | int val; 10 | int freq; 11 | }; 12 | 13 | struct CompElem { 14 | bool operator()(const Elem& l, const Elem& r) { 15 | if (l.freq != r.freq) return l.freq > r.freq; 16 | return l.val < r.val; 17 | } 18 | }; 19 | 20 | class SortByIncreasingFrequency { 21 | public: 22 | vector frequencySort(vector& nums) { 23 | vector result; 24 | unordered_map m; 25 | for (int i : nums) m[i]++; 26 | priority_queue, CompElem> pq; 27 | unordered_map::iterator it; 28 | for (it = m.begin(); it != m.end(); ++it) { 29 | pq.push(Elem(it->first, it->second)); 30 | } 31 | while (not pq.empty()) { 32 | Elem e = pq.top(); pq.pop(); 33 | result.insert(result.end(), e.freq, e.val); 34 | } 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /HashTable/Logger.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/logger-rate-limiter/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | /** 8 | * Your Logger object will be instantiated and called as such: 9 | * Logger* obj = new Logger(); 10 | * bool param_1 = obj->shouldPrintMessage(timestamp,message); 11 | */ 12 | class Logger { 13 | public: 14 | /** Initialize your data structure here. */ 15 | Logger() {} 16 | 17 | /** 18 | * Returns true if the message should be printed in the given timestamp, otherwise returns false. 19 | * If this method returns false, the message will not be printed. 20 | * The timestamp is in seconds granularity. 21 | */ 22 | bool shouldPrintMessage(int timestamp, string message) { 23 | if (this->_tstamp.find(message) != this->_tstamp.end()) { 24 | int old_tstamp = this->_tstamp[message]; 25 | if (timestamp - old_tstamp >= 10) { 26 | this->_tstamp[message] = timestamp; 27 | return true; 28 | } 29 | return false; 30 | } 31 | this->_tstamp[message] = timestamp; 32 | return true; 33 | } 34 | 35 | private: 36 | unordered_map _tstamp; 37 | }; -------------------------------------------------------------------------------- /Matrix/MinimumPathSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-path-sum/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class MinimumPathSum { 10 | private: 11 | string getKey(int x, int y) { 12 | return std::to_string(x) + "," + std::to_string(y); 13 | } 14 | 15 | public: 16 | int minPathSum(vector>& grid) { 17 | unordered_map cost_map; 18 | return minPathSumInt(grid, 0, 0, cost_map); 19 | } 20 | 21 | int minPathSumInt(vector>& grid, int x, int y, unordered_map& cost_map) { 22 | if (x == (grid.size() - 1) && (y == grid[0].size())) return 0; 23 | if ((x >= grid.size()) || (y >= grid[0].size())) return INT_MAX; 24 | const string key = getKey(x, y); 25 | if (cost_map.find(key) != cost_map.end()) return cost_map[key]; 26 | cost_map[key] = grid[x][y] + 27 | std::min( 28 | minPathSumInt(grid, x + 1, y, cost_map), 29 | minPathSumInt(grid, x, y + 1, cost_map) 30 | ); 31 | return cost_map[key]; 32 | 33 | 34 | } 35 | }; -------------------------------------------------------------------------------- /Array/MissingRangeFinder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class MissingRanges { 7 | public: 8 | vector findMissingRanges(vector& nums, int lower, int upper) { 9 | vector out_ranges; 10 | nums.insert(nums.begin(), lower - 1); 11 | nums.push_back(upper + 1); 12 | int num_nums = nums.size(); 13 | int last_num, curr_num = 0; 14 | for (int index = 1; index < nums.size(); ++index) { 15 | last_num = nums.at(index - 1); 16 | curr_num = nums.at(index); 17 | string out_range; 18 | if (curr_num > last_num) { 19 | if (curr_num == last_num + 1) { 20 | continue; 21 | } else if (curr_num == last_num + 2) { 22 | out_range = to_string(last_num + 1); 23 | } else { 24 | out_range = to_string(last_num + 1) + "->" + to_string(curr_num - 1); 25 | } 26 | out_ranges.push_back(out_range); 27 | } 28 | } 29 | return out_ranges; 30 | } 31 | }; -------------------------------------------------------------------------------- /Array/ProductExceptSelf.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/product-of-array-except-self/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class ProductExceptSelf { 8 | public: 9 | vector productExceptSelf(vector& nums) { 10 | vector product; 11 | int overallProduct = 1; 12 | int num_zeros = 0; 13 | for (int i = 0; i < nums.size(); ++i) { 14 | if (nums[i] != 0) { 15 | overallProduct *= nums[i]; 16 | } else { 17 | ++num_zeros; 18 | } 19 | } 20 | for (int i = 0; i < nums.size(); ++i) { 21 | if (num_zeros > 1) { 22 | product.push_back(0); 23 | continue; 24 | } else if (nums[i] == 0) { 25 | product.push_back(overallProduct); 26 | } else { 27 | if (num_zeros >0) { 28 | product.push_back(0); 29 | } else { 30 | product.push_back(overallProduct/nums[i]); 31 | } 32 | } 33 | } 34 | return product; 35 | } 36 | }; -------------------------------------------------------------------------------- /Graph/NumberProvinces.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/number-of-provinces/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class NumberProvinces { 10 | public: 11 | int findCircleNum(vector>& isConnected) { 12 | int num_nodes = isConnected.size(); 13 | unordered_set seen; 14 | int num_provinces = 0; 15 | for (int i = 0; i < num_nodes; ++i) { 16 | if (seen.find(i) != seen.end()) continue; 17 | ++num_provinces; 18 | queue nodes; 19 | nodes.push(i); 20 | while (not nodes.empty()) { 21 | int curr_node = nodes.front(); nodes.pop(); 22 | seen.insert(curr_node); 23 | for (int j = 0; j < num_nodes; ++j) { 24 | if (isConnected[curr_node][j]) { 25 | if (seen.find(j) == seen.end()) { 26 | nodes.push(j); 27 | } 28 | } 29 | } 30 | } 31 | } 32 | return num_provinces; 33 | } 34 | }; -------------------------------------------------------------------------------- /HashTable/TwoSumStream.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/two-sum-iii-data-structure-design/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | /** 9 | * Your TwoSum object will be instantiated and called as such: 10 | * TwoSum* obj = new TwoSum(); 11 | * obj->add(number); 12 | * bool param_2 = obj->find(value); 13 | */ 14 | class TwoSumStream { 15 | public: 16 | /** Initialize your data structure here. */ 17 | TwoSum() {} 18 | 19 | /** Add the number to an internal data structure.. */ 20 | void add(int number) { nums_[number]++; } 21 | 22 | /** Find if there exists any pair of numbers which sum is equal to the value. */ 23 | bool find(int value) { 24 | unordered_map::iterator it; 25 | for (it = nums_.begin(); it != nums_.end(); ++it) { 26 | long int curr = it->first; 27 | long int complement = value - curr; 28 | if (curr == complement) { 29 | if (it->second > 1) return true; 30 | } else { 31 | if (nums_.find(complement) != nums_.end()) return true; 32 | } 33 | } 34 | return false; 35 | } 36 | 37 | private: 38 | unordered_map nums_; 39 | }; 40 | -------------------------------------------------------------------------------- /Heap/MedianFinder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /** 8 | * Your MedianFinder object will be instantiated and called as such: 9 | * MedianFinder* obj = new MedianFinder(); 10 | * obj->addNum(num); 11 | * double param_2 = obj->findMedian(); 12 | */ 13 | 14 | class MedianFinder { 15 | public: 16 | MedianFinder() {} 17 | void addNum(int num) { 18 | // Step-I: Add to Max-Heap. 19 | max_heap.push(num); 20 | 21 | // Step-II: Balance the trees. 22 | min_heap.push(max_heap.top()); 23 | max_heap.pop(); 24 | 25 | // Step-III: Keep the max-heap size larger. 26 | if (max_heap.size() < min_heap.size()) { 27 | max_heap.push(min_heap.top()); 28 | min_heap.pop(); 29 | } 30 | 31 | } 32 | 33 | double findMedian() { 34 | if (max_heap.size() > min_heap.size()) return max_heap.top(); 35 | return (0.5) * (double)(min_heap.top() + max_heap.top()); 36 | } 37 | 38 | private: 39 | priority_queue max_heap; 40 | priority_queue, std::greater> min_heap; 41 | }; -------------------------------------------------------------------------------- /String/StringFinder.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/implement-strstr/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class StringFinder { 8 | public: 9 | int strStr(string haystack, string needle) { 10 | int needle_size = needle.size(); 11 | int haystack_size = haystack.size(); 12 | 13 | // Edge Conditions. 14 | if (needle_size == 0) return 0; 15 | if (haystack_size < needle_size) return -1; 16 | 17 | // Looping Through. 18 | for (int index = 0; index < haystack.size(); ++index) { 19 | if (needle_size > (haystack_size - index)) break; 20 | if (compare(haystack, needle, index)) return index; 21 | } 22 | return -1; 23 | } 24 | private: 25 | bool compare(string haystack, string needle, int start_index) { 26 | for (int n_index = 0; n_index < needle.size(); ++n_index) { 27 | if (start_index + n_index >= haystack.size()) return false; 28 | if (haystack[start_index + n_index] != needle[n_index]) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | }; -------------------------------------------------------------------------------- /DynamicProgramming/DecodeWays.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/decode-ways/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class DecodeWays { 8 | public: 9 | int numDecodings(string s) { return numDecodingsWithMemo(s, 0); } 10 | 11 | int numDecodingsWithMemo(string s, int i) { 12 | // If you have reached the end of a string, then return 1 as success. 13 | if (i == s.size()) return 1; 14 | 15 | // String that starts with '0' has no decodings. 16 | if (s.at(i) == '0') return 0; 17 | 18 | // If you have reached the end of a string, then return 1 as success. 19 | if (i == (s.size() - 1)) return 1; 20 | 21 | // If you have seen the string in the past, return the string. 22 | if (memo.find(i) != memo.end()) return memo[i]; 23 | 24 | // The number of decodings is sum of two cases. 25 | // Case I: Take one leading character out. 26 | // Case II: Take two leading characters out. 27 | int ans = numDecodingsWithMemo(s, i + 1); 28 | if (stoi(s.substr(i, 2)) <= 26) { 29 | ans += numDecodingsWithMemo(s, i + 2); 30 | } 31 | memo[i] = ans; 32 | return ans; 33 | } 34 | 35 | private: 36 | unordered_map memo; 37 | }; -------------------------------------------------------------------------------- /LinkedList/LinkedListIntersection.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/intersection-of-two-linked-lists/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Definition for singly-linked list. 8 | struct ListNode { 9 | int val; 10 | ListNode *next; 11 | ListNode(int x) : val(x), next(NULL) {} 12 | }; 13 | 14 | class LinkedListIntersection { 15 | public: 16 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 17 | stack s1 = toStack(headA); 18 | stack s2 = toStack(headB); 19 | ListNode* intersection = nullptr; 20 | while (not s1.empty() && not s2.empty()) { 21 | ListNode* n1 = s1.top(); s1.pop(); 22 | ListNode* n2 = s2.top(); s2.pop(); 23 | if (n1 == n2) intersection = n1; 24 | else break; 25 | } 26 | return intersection; 27 | } 28 | 29 | stack toStack(ListNode* head) { 30 | stack st; 31 | ListNode* curr = head; 32 | while (curr != nullptr) { 33 | st.push(curr); 34 | curr = curr->next; 35 | } 36 | return st; 37 | } 38 | }; -------------------------------------------------------------------------------- /Array/AddToArrayForm/go/AddToArrayForm.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | // space complexity: O(n), time complexity: O(n) 4 | // convert the array to integer, add it and convert it back to array 5 | // for large output it can fail, we can use uint64 or big.NewInt type 6 | func addToArrayForm(num []int, k int) []int { 7 | if k == 0 { 8 | return num 9 | } 10 | var sliceToInt, op int 11 | sliceToInt, op = 0, 1 12 | 13 | for i := len(num) - 1; i >= 0; i-- { 14 | sliceToInt += op * num[i] 15 | op *= 10 16 | } 17 | newNum := sliceToInt + k 18 | 19 | var intToSlice []int 20 | 21 | for newNum > 0 { 22 | intToSlice = append([]int{newNum % 10}, intToSlice...) 23 | newNum /= 10 24 | } 25 | 26 | return intToSlice 27 | } 28 | 29 | // space complexity: O(1), time complexity: O(n) 30 | // calculate the carry and add it to the array 31 | // 274 + 181 -> 2,7,185 -> 2,7+18,5 -> 2+2,5,5 = 455 32 | func addToArrayForm2(num []int, k int) []int { 33 | if k == 0 { 34 | return num 35 | } 36 | for i := len(num) - 1; i >= 0; i-- { 37 | num[i] += k 38 | k = num[i] / 10 39 | num[i] %= 10 40 | } 41 | for k > 0 { 42 | num = append([]int{k % 10}, num...) 43 | k /= 10 44 | } 45 | return num 46 | } 47 | -------------------------------------------------------------------------------- /Tree/MinDepth.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/ 2 | 3 | // Definition for a binary tree node. 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 11 | }; 12 | 13 | class MinDepth { 14 | public: 15 | int minDepth(TreeNode* root) { 16 | if (root == nullptr) return 0; 17 | if (root->left == nullptr && root->right == nullptr) return 1; 18 | int min_depth = INT_MAX; 19 | if (root->left != nullptr) min_depth = min(min_depth, minDepthUtil(root->left)); 20 | if (root->right != nullptr) min_depth = min(min_depth, minDepthUtil(root->right)); 21 | return 1 + min_depth; 22 | } 23 | 24 | int minDepthUtil(TreeNode* root) { 25 | if (root->left == nullptr && root->right == nullptr) return 1; 26 | if (root->left == nullptr) return 1 + minDepthUtil(root->right); 27 | if (root->right == nullptr) return 1 + minDepthUtil(root->left); 28 | return 1 + min(minDepthUtil(root->left), minDepthUtil(root->right)); 29 | } 30 | }; -------------------------------------------------------------------------------- /Heap/SortCharactersByFrequency.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/sort-characters-by-frequency/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct CharCount { 10 | CharCount(char c, int count) : ch(c), count (count) {} 11 | char ch; 12 | int count; 13 | }; 14 | 15 | struct compareCharCount { 16 | inline bool operator()(const CharCount& l, const CharCount& r) { 17 | return l.count < r.count; 18 | 19 | } 20 | }; 21 | 22 | class SortCharactersByFrequency { 23 | public: 24 | string frequencySort(string s) { 25 | string out = ""; 26 | priority_queue, compareCharCount> p_queue; 27 | unordered_map char_count_map; 28 | for (int index = 0; index < s.size(); ++index) { 29 | char_count_map[s[index]]++; 30 | } 31 | unordered_map::iterator it; 32 | for (it = char_count_map.begin(); it != char_count_map.end(); ++it) { 33 | p_queue.push(CharCount(it->first, it->second)); 34 | } 35 | while (not p_queue.empty()) { 36 | CharCount cc = p_queue.top(); 37 | p_queue.pop(); 38 | out.append(cc.count, cc.ch); 39 | } 40 | return out; 41 | } 42 | }; -------------------------------------------------------------------------------- /Matrix/IslandPerimeter.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/island-perimeter/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class IslandPerimeter { 8 | public: 9 | int islandPerimeter(vector>& grid) { 10 | int max_rows = grid.size(); 11 | int max_cols = grid[0].size(); 12 | int count = 0; 13 | for (int r = 0; r < max_rows; ++r) { 14 | for (int c = 0; c < max_cols; ++c) { 15 | int curr = grid[r][c]; 16 | if (curr == 0) continue; 17 | count += getVal(grid, r, c + 1, max_rows, max_cols) + 18 | getVal(grid, r + 1, c, max_rows, max_cols) + 19 | getVal(grid, r - 1, c, max_rows, max_cols) + 20 | getVal(grid, r, c - 1, max_rows, max_cols); 21 | } 22 | } 23 | return count; 24 | } 25 | private: 26 | int getVal(vector>& grid, int row, int col, int max_rows, int max_cols) { 27 | if (row < 0 || col < 0 || 28 | row >= max_rows || col >= max_cols || 29 | (grid[row][col] == 0)) return 1; 30 | return 0; 31 | } 32 | }; -------------------------------------------------------------------------------- /HashTable/TwoSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/two-sum/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class TwoSum { 9 | public: 10 | vector twoSum(vector& nums, int target) { 11 | std::unordered_map sums; 12 | vector results; 13 | for (int i = 0; i < nums.size(); ++i) { 14 | int rem = target - nums[i]; 15 | sums[rem] = i; 16 | 17 | } 18 | for (int i = 0; i < nums.size(); ++i) { 19 | // Finding the 20 | if (sums.find(nums[i]) != sums.end()) { 21 | // Handling the case when the same element is searced. 22 | if (sums[nums[i]] != i) { 23 | // Ensuring that the results are sorted. 24 | // Pushing the smaller element first. 25 | results.push_back(std::min(i, sums[nums[i]])); 26 | // Pushing the bigger element second. 27 | results.push_back(std::max(i, sums[nums[i]])); 28 | break; 29 | } 30 | } 31 | } 32 | return results; 33 | } 34 | }; -------------------------------------------------------------------------------- /Array/IntervalListIntersections/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/interval-list-intersections/ 2 | ```text 3 | You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. 4 | 5 | Return the intersection of these two interval lists. 6 | 7 | A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. 8 | 9 | The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3]. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | 16 | Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] 17 | Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] 18 | Example 2: 19 | 20 | Input: firstList = [[1,3],[5,9]], secondList = [] 21 | Output: [] 22 | 23 | Constraints: 24 | 25 | 0 <= firstList.length, secondList.length <= 1000 26 | firstList.length + secondList.length >= 1 27 | 0 <= starti < endi <= 109 28 | endi < starti+1 29 | 0 <= startj < endj <= 109 30 | endj < startj+1 31 | ``` -------------------------------------------------------------------------------- /Array/IntervalListIntersections/cpp/IntervalListIntersections.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/interval-list-intersections/ 2 | #include 3 | 4 | using namespace std; 5 | 6 | class IntervalListIntersections { 7 | public: 8 | vector> intervalIntersection(vector>& firstList, 9 | vector>& secondList) { 10 | int i1 = 0; 11 | int i2 = 0; 12 | vector> result; 13 | while (i1 < firstList.size() && i2 < secondList.size()) { 14 | vector it1 = firstList[i1]; 15 | vector it2 = secondList[i2]; 16 | if (intersects(it1, it2)) { 17 | vector overlap = findOverlap(it1, it2); 18 | result.push_back(overlap); 19 | } 20 | if (it1[1] == it2[1]) { ++i2; ++i1; } 21 | else if (it1[1] > it2[1]) ++i2; 22 | else ++i1; 23 | } 24 | return result; 25 | } 26 | 27 | bool intersects(vector& i1, vector& i2) { 28 | if ((i1[1] < i2[0]) || (i2[1] < i1[0])) return false; 29 | return true; 30 | } 31 | 32 | vector findOverlap(vector& i1, vector& i2) { 33 | vector overlap; 34 | overlap.push_back(max(i1[0], i2[0])); 35 | overlap.push_back(min(i1[1], i2[1])); 36 | return overlap; 37 | } 38 | }; -------------------------------------------------------------------------------- /Array/AddToArrayForm/cpp/AddToArrayForm.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/add-to-array-form-of-integer/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class AddToArrayForm { 8 | public: 9 | vector addToArrayForm(vector& num, int k) { 10 | int index = 0; 11 | int carry = 0; 12 | vector sum; 13 | int curr_sum = 0; 14 | int size = num.size(); 15 | while (k > 0) { 16 | curr_sum = carry; 17 | if (index < size) curr_sum += num[size-index-1]; 18 | curr_sum += k - k/10 * 10; 19 | carry = curr_sum > 9 ? 1 : 0; 20 | if (curr_sum > 9) curr_sum = curr_sum - curr_sum/10 *10; 21 | sum.insert(sum.begin(), curr_sum); 22 | ++index; 23 | k /= 10; 24 | } 25 | while (index < size) { 26 | curr_sum = num[size-index-1] + carry; 27 | carry = curr_sum > 9 ? 1 : 0; 28 | if (curr_sum > 9) curr_sum = curr_sum - curr_sum/10 *10; 29 | sum.insert(sum.begin(), curr_sum); 30 | ++index; 31 | } 32 | if (carry > 0) sum.insert(sum.begin(), 1); 33 | return sum; 34 | } 35 | }; -------------------------------------------------------------------------------- /Array/DecompressRLE/go/DecompressRLE_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_decompressRLElist(t *testing.T) { 9 | type args struct { 10 | nums []int 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want []int 16 | }{ 17 | { 18 | name: "Test 1", 19 | args: args{ 20 | nums: []int{1, 2, 3, 4}, 21 | }, 22 | want: []int{2, 4, 4, 4}, 23 | }, 24 | { 25 | name: "Test 2", 26 | args: args{ 27 | nums: []int{1, 1, 2, 3}, 28 | }, 29 | want: []int{1, 3, 3}, 30 | }, 31 | { 32 | name: "Test 3", 33 | args: args{ 34 | nums: []int{1, 1, 1, 1}, 35 | }, 36 | want: []int{1, 1}, 37 | }, 38 | { 39 | name: "Test 4", 40 | args: args{ 41 | nums: []int{}, 42 | }, 43 | want: []int{}, 44 | }, 45 | { 46 | name: "Test 5", 47 | args: args{ 48 | nums: []int{0, 0, 0, 0}, 49 | }, 50 | want: []int{}, 51 | }, 52 | } 53 | for _, tt := range tests { 54 | t.Run(tt.name, func(t *testing.T) { 55 | if got := decompressRLElist(tt.args.nums); !reflect.DeepEqual(got, tt.want) { 56 | t.Errorf("decompressRLElist() = %v, want %v", got, tt.want) 57 | } 58 | }) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Array/LineChecker/cpp/LineChecker.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/check-if-it-is-a-straight-line/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Slope { 8 | double val = 0.0; 9 | bool is_vertical = false; 10 | }; 11 | 12 | class LineChecker { 13 | public: 14 | bool checkStraightLine(vector>& coordinates) { 15 | vector fp = coordinates[0]; 16 | vector sp = coordinates[1]; 17 | Slope slope = getSlope(fp, sp); 18 | for (int index = 2; index < coordinates.size(); ++index) { 19 | if (not compareSlopes(getSlope(fp, coordinates[index]), slope)) return false; 20 | } 21 | return true; 22 | } 23 | 24 | private: 25 | bool compareSlopes(Slope s1, Slope s2) { 26 | return s1.is_vertical == s2.is_vertical && s1.val == s2.val; 27 | } 28 | 29 | Slope getSlope(vector p1, vector p2) { 30 | Slope sp; 31 | if (p1[0] == p2[0]) { 32 | sp.is_vertical = true; 33 | sp.val = p1[0]; 34 | } else { 35 | sp.val = ((double)(p1[1] - p2[1]) / (double)(p1[0] - p2[0])); 36 | } 37 | return sp; 38 | } 39 | 40 | 41 | }; -------------------------------------------------------------------------------- /DynamicProgramming/MinCostTickets.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-cost-for-tickets/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class MinCostTickets { 8 | public: 9 | int mincostTickets(vector& days, vector& costs) { 10 | // Maximum number of days. 11 | int dp[366]; 12 | dp[0] = 0; 13 | int prev_day = 0; 14 | for (int i = 0; i < days.size(); ++i) { 15 | int day = days[i]; 16 | // Filling all the days in between. 17 | // If a day doesn't exist, then the cost of that day remains the same. 18 | for (int j = prev_day; j < day; ++j) { 19 | dp[j] = dp[prev_day]; 20 | } 21 | // dp[i] = min(cost[0] + dp[i - 1], cost[1] + dp[i-7], cost[2] + dp[i-30]) 22 | dp[day] = getMin(costs[0] + dp[max(0, day - 1)], 23 | costs[1] + dp[max(0, day - 7)], 24 | costs[2] + dp[max(0, day - 30)]); 25 | prev_day = day; 26 | } 27 | return dp[days.back()]; 28 | } 29 | 30 | private: 31 | int getMin(int a, int b, int c) { 32 | return min(a, min(b, c)); 33 | } 34 | }; -------------------------------------------------------------------------------- /DynamicProgramming/PartitionEqualSubsetSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/partition-equal-subset-sum/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class PartitionEqualSubsetSum { 10 | public: 11 | bool canPartition(vector& nums) { 12 | int sum = getSum(nums); 13 | unordered_map dp; 14 | if ((sum % 2) == 1) return false; 15 | return canPartitionUtil(nums, nums.size() - 1, sum / 2, dp); 16 | } 17 | 18 | bool canPartitionUtil(vector& nums, int index, int target, unordered_map& dp) { 19 | if (target == 0) return true; 20 | if (target < 0 || index < 0) return false; 21 | string key = to_string(index) + ":" + to_string(target); 22 | if (dp.find(key) != dp.end()) return dp[key]; 23 | dp[key] = 24 | canPartitionUtil(nums, index - 1, target - nums[index], dp) || 25 | canPartitionUtil(nums, index - 1, target, dp); 26 | return dp[key]; 27 | } 28 | 29 | int getSum(vector& nums) { 30 | int sum = 0; 31 | for (int elem : nums) sum += elem; 32 | return sum; 33 | } 34 | }; -------------------------------------------------------------------------------- /Matrix/BestMeetingSpot.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/best-meeting-point/ 2 | #include 3 | 4 | using namespace std; 5 | 6 | class BestMeetingSpot { 7 | public: 8 | int minTotalDistance(vector>& grid) { 9 | int max_rows = grid.size(); 10 | int max_cols = grid[0].size(); 11 | vector row; 12 | vector col; 13 | row.resize(max_cols, 0); 14 | col.resize(max_rows, 0); 15 | for (int r = 0; r < max_rows; ++r) { 16 | for (int c = 0; c < max_cols; ++c) { 17 | if (grid[r][c] == 0) continue; 18 | row[c]++; col[r]++; 19 | } 20 | } 21 | return getMinDist(row) + getMinDist(col); 22 | } 23 | 24 | private: 25 | int getMinDist(vector& nums) { 26 | int min_dist = INT_MAX; 27 | for (int i = 0; i < nums.size(); ++i) { 28 | int curr_dist = 0; 29 | for (int j = 0; j < nums.size(); ++j) { 30 | curr_dist += nums[j] * abs(j - i); 31 | } 32 | min_dist = min(min_dist, curr_dist); 33 | } 34 | return min_dist; 35 | } 36 | }; -------------------------------------------------------------------------------- /Stack/AsteroidCollision.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/asteroid-collision/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class AsteroidCollision { 9 | public: 10 | vector asteroidCollision(vector& asteroids) { 11 | stack st; 12 | vector result; 13 | for (int i = 0; i < asteroids.size(); ++i) { 14 | updateStack(st, asteroids[i]); 15 | } 16 | while (!st.empty()) { 17 | result.insert(result.begin(), st.top()); 18 | st.pop(); 19 | } 20 | return result; 21 | } 22 | 23 | void updateStack(stack& st, int val) { 24 | if (st.empty()) { 25 | st.push(val); 26 | return; 27 | } 28 | int v_top = st.top(); 29 | if (val < 0 && v_top > 0) { 30 | st.pop(); 31 | if (abs(val) == v_top) return; 32 | int final_size; 33 | if (abs(val) < v_top) final_size = v_top; 34 | else final_size = val; 35 | updateStack(st, final_size); 36 | return; 37 | } 38 | st.push(val); 39 | } 40 | }; -------------------------------------------------------------------------------- /Array/GoodPairs/go/GoodPairs.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | // GoodPairs check for each pair 8 | // Time complexity: O(n) 9 | // Space complexity: O(1) 10 | func numIdenticalPairs(nums []int) int { 11 | count := 0 12 | for i := 0; i < len(nums); i++ { 13 | for j := i + 1; j < len(nums); j++ { 14 | if nums[i] == nums[j] { 15 | count++ 16 | } 17 | } 18 | } 19 | return count 20 | } 21 | 22 | // numIdenticalPairs2 store the indexes in hashmap 23 | // Time complexity: O(n) 24 | // Space complexity: O(n) 25 | func numIdenticalPairs2(nums []int) int { 26 | m := make(map[int]int) 27 | for _, v := range nums { 28 | m[v]++ 29 | } 30 | count := 0 31 | for _, v := range m { 32 | count += v * (v - 1) / 2 33 | } 34 | return count 35 | } 36 | 37 | // numIdenticalPairs3 sort the array and calculate the pair 38 | // Time complexity: O(nlog(n)) 39 | // Space complexity: O(1) 40 | func numIdenticalPairs3(nums []int) int { 41 | count, ans := 0, 0 42 | sort.Ints(nums) 43 | for i := 0; i < len(nums)-1; i++ { 44 | if nums[i] == nums[i+1] { 45 | count++ 46 | } else { 47 | ans += count * (count + 1) / 2 48 | count = 0 49 | } 50 | } 51 | ans += count * (count + 1) / 2 52 | return ans 53 | } 54 | -------------------------------------------------------------------------------- /Intervals/MeetingRooms.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minMeetingRooms(vector>& intervals) { 8 | std::sort(intervals.begin(), intervals.end(), 9 | [](const std::vector& a, const std::vector& b) { return a[0] < b[0]; }); 10 | int num_rooms = 0; 11 | priority_queue, std::greater> pq; 12 | for (int i = 0; i < intervals.size(); ++i) { 13 | const vector& currInterval = intervals.at(i); 14 | while (!pq.empty() && pq.top() <= currInterval.at(0)) pq.pop(); 15 | pq.push(currInterval.at(1)); 16 | num_rooms = std::max(num_rooms, (int)pq.size()); 17 | } 18 | num_rooms = std::max(num_rooms, (int)pq.size()); 19 | return num_rooms; 20 | } 21 | 22 | private: 23 | bool hasOverlap(const vector& i1, const vector& i2) { 24 | const int s1 = i1.at(0); 25 | const int e1 = i1.at(1); 26 | const int s2 = i2.at(0); 27 | const int e2 = i2.at(1); 28 | if (s2 >= s1 && s2 < e1) return true; 29 | if (s1 >= s2 && s1 < e2) return true; 30 | return false; 31 | } 32 | }; -------------------------------------------------------------------------------- /Array/IsMonotone/go/IsMonotone_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_isMonotonic(t *testing.T) { 8 | type args struct { 9 | nums []int 10 | } 11 | tests := []struct { 12 | name string 13 | args args 14 | want bool 15 | }{ 16 | { 17 | name: "Test 1", 18 | args: args{ 19 | nums: []int{1, 2, 2, 3}, 20 | }, 21 | want: true, 22 | }, 23 | { 24 | name: "Test 2", 25 | args: args{ 26 | nums: []int{6, 5, 4, 4}, 27 | }, 28 | want: true, 29 | }, 30 | { 31 | name: "Test 3", 32 | args: args{ 33 | nums: []int{1, 3, 2}, 34 | }, 35 | want: false, 36 | }, 37 | { 38 | name: "Test 4", 39 | args: args{ 40 | nums: []int{5}, 41 | }, 42 | want: true, 43 | }, 44 | { 45 | name: "Test 5", 46 | args: args{ 47 | nums: []int{}, 48 | }, 49 | want: true, 50 | }, 51 | } 52 | for _, tt := range tests { 53 | t.Run(tt.name, func(t *testing.T) { 54 | if got := isMonotonic(tt.args.nums); got != tt.want { 55 | t.Errorf("isMonotonic() = %v, want %v", got, tt.want) 56 | } 57 | if got := isMonotonic2(tt.args.nums); got != tt.want { 58 | t.Errorf("isMonotonic()2 = %v, want %v", got, tt.want) 59 | } 60 | }) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Tree/BinaryTreeDiameter.cpp: -------------------------------------------------------------------------------- 1 | //Problem: https://leetcode.com/problems/diameter-of-binary-tree/ 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 BinaryTreeDiameter { 13 | public: 14 | int diameterOfBinaryTree(TreeNode* root) { 15 | if (root == nullptr) return 0; 16 | int diameter = 0; 17 | diameter = max(diameter, (1 + getHeight(root->left) + 1 + getHeight(root->right))); 18 | diameter = max(diameter, diameterOfBinaryTree(root->left)); 19 | diameter = max(diameter, diameterOfBinaryTree(root->right)); 20 | return diameter; 21 | } 22 | 23 | private: 24 | int getHeight(TreeNode* root) { 25 | if (root == nullptr) return -1; 26 | int height = 0; 27 | if (root->left != nullptr) height = max(height, 1 + getHeight(root->left)); 28 | if (root->right != nullptr) height = max(height, 1 + getHeight(root->right)); 29 | return height; 30 | } 31 | }; -------------------------------------------------------------------------------- /Array/HIndexCalculator/go/HIndexCalculator_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_hIndex(t *testing.T) { 8 | type args struct { 9 | citations []int 10 | } 11 | tests := []struct { 12 | name string 13 | args args 14 | want int 15 | }{ 16 | { 17 | name: "Test 1", 18 | args: args{ 19 | citations: []int{3, 0, 6, 1, 5}, 20 | }, 21 | want: 3, 22 | }, 23 | { 24 | name: "Test 2", 25 | args: args{ 26 | citations: []int{1, 1, 1, 1}, 27 | }, 28 | want: 1, 29 | }, 30 | { 31 | name: "Test 3", 32 | args: args{ 33 | citations: []int{1, 2, 3}, 34 | }, 35 | want: 2, 36 | }, 37 | { 38 | name: "Test 4", 39 | args: args{ 40 | citations: []int{}, 41 | }, 42 | want: 0, 43 | }, 44 | { 45 | name: "Test 5", 46 | args: args{ 47 | citations: []int{1}, 48 | }, 49 | want: 1, 50 | }, 51 | } 52 | for _, tt := range tests { 53 | t.Run(tt.name, func(t *testing.T) { 54 | if got := hIndex(tt.args.citations); got != tt.want { 55 | t.Errorf("hIndex() = %v, want %v", got, tt.want) 56 | } 57 | if got := hIndex2(tt.args.citations); got != tt.want { 58 | t.Errorf("hIndex()2 = %v, want %v", got, tt.want) 59 | } 60 | }) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Backtracking/GenerateSubsets.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/subsets/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class GenerateSubsets { 8 | public: 9 | vector> subsets(vector& nums) { 10 | vector taken; 11 | taken.resize(nums.size(), false); 12 | vector> result; 13 | result.push_back({}); 14 | generate(nums, taken, result, 0); 15 | return result; 16 | } 17 | 18 | void generate(const vector& nums, vector& taken, vector>& result, int index) { 19 | if (index == nums.size()) { 20 | vector r; 21 | generateResult(nums, taken, r); 22 | if (not r.empty()) result.push_back(r); 23 | return; 24 | } 25 | 26 | taken[index] = true; 27 | generate(nums, taken, result, index + 1); 28 | 29 | taken[index] = false; 30 | generate(nums, taken, result, index + 1); 31 | } 32 | 33 | void generateResult(const vector& nums, const vector& taken, vector& result) { 34 | for (int index = 0; index < nums.size(); ++index) { 35 | if (taken[index]) result.push_back(nums[index]); 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /Tree/SubtreeCheck.cpp: -------------------------------------------------------------------------------- 1 | // Problem-Link: https://leetcode.com/problems/subtree-of-another-tree/ 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 SubtreeCheck { 13 | public: 14 | bool isSubtree(TreeNode* root, TreeNode* subRoot) { 15 | if (isIdentical(root, subRoot)) return true; 16 | if (root) { 17 | if (isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot)) return true; 18 | } 19 | return false; 20 | } 21 | 22 | private: 23 | bool isIdentical(TreeNode* first, TreeNode* second) { 24 | if (first == nullptr && second == nullptr) return true; 25 | if (first != nullptr && second != nullptr) { 26 | if (first->val == second->val) { 27 | return 28 | isIdentical(first->left, second->left) && 29 | isIdentical(first->right, second->right); 30 | } 31 | } 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /Tree/ClosestBinarySearchTreeValue.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/closest-binary-search-tree-value/ 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 ClosestBinarySearchTreeValue { 13 | public: 14 | int closestValue(TreeNode* root, double target) { 15 | double delta = abs(target - (double)root->val); 16 | int clValue = root->val; 17 | if (root->left != nullptr) { 18 | int l = closestValue(root->left, target); 19 | if (abs((double)l - target) < delta) { 20 | clValue = l; 21 | delta = abs((double)l - target); 22 | } 23 | } 24 | if (root->right != nullptr) { 25 | int r = closestValue(root->right, target); 26 | if (abs((double)r - target) < delta) { 27 | clValue = r; 28 | delta = abs((double)r - target); 29 | } 30 | } 31 | return clValue; 32 | } 33 | }; -------------------------------------------------------------------------------- /Graph/FindIfPathExists.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/find-if-path-exists-in-graph/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class FindIfPathExists { 10 | public: 11 | bool validPath(int n, vector>& edges, int start, int end) { 12 | int MAX_NODES = 2 * 100000; 13 | queue nq; 14 | vector> node_map; 15 | node_map.resize(MAX_NODES + 1, {}); 16 | unordered_set seen; 17 | for (int i = 0; i < edges.size(); ++i) { 18 | node_map[edges[i][0]].push_back(edges[i][1]); 19 | node_map[edges[i][1]].push_back(edges[i][0]); 20 | } 21 | nq.push(start); 22 | while (not nq.empty()) { 23 | int source_node_id = nq.front(); nq.pop(); 24 | if (source_node_id == end) return true; 25 | for (int i = 0; i < node_map[source_node_id].size(); ++i) { 26 | int dest_node_id = node_map[source_node_id][i]; 27 | if (seen.find(dest_node_id) != seen.end()) continue; 28 | nq.push(dest_node_id); 29 | } 30 | seen.insert(source_node_id); 31 | } 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /Array/MakeTwoArraysEqual/Problem.md: -------------------------------------------------------------------------------- 1 | # Problem https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ 2 | 3 | ```text 4 | You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. 5 | 6 | Return true if you can make arr equal to target or false otherwise. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: target = [1,2,3,4], arr = [2,4,1,3] 13 | Output: true 14 | Explanation: You can follow the next steps to convert arr to target: 15 | 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3] 16 | 2- Reverse sub-array [4,2], arr becomes [1,2,4,3] 17 | 3- Reverse sub-array [4,3], arr becomes [1,2,3,4] 18 | There are multiple ways to convert arr to target, this is not the only way to do so. 19 | Example 2: 20 | 21 | Input: target = [7], arr = [7] 22 | Output: true 23 | Explanation: arr is equal to target without any reverses. 24 | Example 3: 25 | 26 | Input: target = [3,7,9], arr = [3,7,11] 27 | Output: false 28 | Explanation: arr does not have value 9 and it can never be converted to target. 29 | 30 | 31 | Constraints: 32 | 33 | target.length == arr.length 34 | 1 <= target.length <= 1000 35 | 1 <= target[i] <= 1000 36 | 1 <= arr[i] <= 1000 37 | 38 | ``` -------------------------------------------------------------------------------- /DynamicProgramming/PalindromicSubstrings.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/palindromic-substrings/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class PalindromicSubstrings { 9 | private: 10 | string ToString(int i, int j) { 11 | return std::to_string(i) + "," + std::to_string(j); 12 | } 13 | 14 | public: 15 | int countSubstrings(string s) { 16 | unordered_map memo; 17 | int result = 0; 18 | for (int len = 0; len <= s.size(); ++len) { 19 | for (int index = 0; index <= (s.size() - len); ++index) { 20 | bool isPalindrome = false; 21 | const string key = ToString(len, index); 22 | // All strings of length = 0 are palindromes by default. 23 | if (len == 0) { 24 | memo[key] = true; 25 | continue; 26 | } 27 | // All strings of length = 1 are palindromes by default. 28 | if (len == 1) { 29 | isPalindrome = true; 30 | } else { 31 | // IsPalindrome(index, len) = IsPalindrome(index + 1, len -2) && s[index] == s[index + len] 32 | isPalindrome = memo[ToString(len - 2, index + 1)] && (s[index] == s[index + len - 1]); 33 | } 34 | if (isPalindrome) { 35 | ++result; 36 | } 37 | memo[key] = isPalindrome; 38 | } 39 | } 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /Graph/ParallelCourses.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/parallel-courses/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class ParallelCourses { 9 | public: 10 | int minimumSemesters(int n, vector>& relations) { 11 | vector incoming; 12 | vector> outgoing; 13 | queue nodes; 14 | queue next_nodes; 15 | incoming.resize(n + 1, 0); 16 | outgoing.resize(n + 1, {}); 17 | int count = 0; 18 | for (int i = 0; i < relations.size(); ++i) { 19 | incoming[relations[i][1]]++; 20 | outgoing[relations[i][0]].push_back(relations[i][1]); 21 | } 22 | for (int i = 1; i <= n; ++i) { 23 | if (incoming[i] == 0) { nodes.push(i); } 24 | } 25 | while (nodes.size() > 0) { 26 | queue next_nodes; 27 | while (nodes.size() > 0) { 28 | int curr = nodes.front(); nodes.pop(); 29 | for (int j = 0; j < outgoing[curr].size(); ++j) { 30 | incoming[outgoing[curr][j]]--; 31 | if (incoming[outgoing[curr][j]] == 0) next_nodes.push(outgoing[curr][j]); 32 | } 33 | } 34 | nodes = next_nodes; 35 | ++count; 36 | } 37 | // There should be no node with any incoming edge. 38 | for (int i = 1; i <= n; ++i) { 39 | if (incoming[i] > 0) return -1; 40 | } 41 | return count; 42 | } 43 | }; -------------------------------------------------------------------------------- /DynamicProgramming/TargetSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/target-sum/ 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class TargetSum { 11 | public: 12 | string toString(int index, int target) { 13 | return to_string(index) + ":" + to_string(target); 14 | } 15 | 16 | int findTargetSumWays(vector& nums, int target) { 17 | unordered_map dp; 18 | string key = toString(nums.size() - 1, target); 19 | dp[key] = findTargetSumWaysUtil(nums, nums.size() - 1, target, dp); 20 | return dp[key]; 21 | } 22 | 23 | int findTargetSumWaysUtil(const vector& nums, int index, 24 | int target, unordered_map& dp) { 25 | if (index < 0) { 26 | if (target == 0) return 1; 27 | return 0; 28 | } 29 | string key = toString(index, target); 30 | if (dp.find(key) != dp.end()) return dp[key]; 31 | dp[key] = 32 | findTargetSumWaysUtil(nums, index - 1, target + nums[index], dp) + 33 | findTargetSumWaysUtil(nums, index - 1, target - nums[index], dp); 34 | return dp[key]; 35 | } 36 | }; -------------------------------------------------------------------------------- /Graph/PathsFromSourceToTarget.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/all-paths-from-source-to-target/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class PathsFromSourceToTarget { 9 | public: 10 | vector> allPathsSourceTarget(vector>& graph) { 11 | vector> paths; 12 | unordered_set seen; 13 | vector path; 14 | dfs(graph, seen, paths, path, 0 /* current */, graph.size() - 1 /* target */); 15 | return paths; 16 | } 17 | 18 | void dfs(const vector>& graph, unordered_set& seen, 19 | vector>& paths, vector& path, int current, int target) { 20 | if (seen.find(current) != seen.end()) return; 21 | if (current == target) { 22 | path.push_back(current); 23 | paths.push_back(path); 24 | path.pop_back(); 25 | return; 26 | } 27 | path.push_back(current); 28 | seen.insert(current); 29 | for (int i = 0; i < graph[current].size(); ++i) { 30 | int next = graph[current][i]; 31 | dfs(graph, seen, paths, path, next, target); 32 | } 33 | seen.erase(current); 34 | path.pop_back(); 35 | } 36 | }; -------------------------------------------------------------------------------- /DynamicProgramming/WordBreak.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/word-break/ 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class WordBreak { 11 | public: 12 | bool wordBreak(string s, vector& wordDict) { 13 | // Convert vector to set. 14 | unordered_set wordSet; 15 | for (const auto& word : wordDict) wordSet.insert(word); 16 | unordered_map memo; 17 | return wordBreakWithMemo(s, 0, wordSet, memo); 18 | } 19 | 20 | private: 21 | bool wordBreakWithMemo(const string& s, int start, 22 | const unordered_set& wordSet, unordered_map& memo) { 23 | // End of the string, yes -> we have found a way to break the string. 24 | if (start == s.size()) return true; 25 | // If we have seen this pivot, then return the value; 26 | if (memo.find(start) != memo.end()) return memo[start]; 27 | 28 | string curr = ""; 29 | for (int i = start; i < s.size(); ++i) { 30 | curr.append(1, s.at(i)); 31 | if (wordSet.find(curr) != wordSet.end()) { 32 | if (wordBreakWithMemo(s, i + 1, wordSet, memo)) { 33 | memo[start] = true; 34 | return true; 35 | } 36 | } 37 | } 38 | memo[start] = false; 39 | return false; 40 | } 41 | }; -------------------------------------------------------------------------------- /LinkedList/PalindromeLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/palindrome-linked-list/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Definition for singly-linked list. 8 | struct ListNode { 9 | int val; 10 | ListNode *next; 11 | ListNode() : val(0), next(nullptr) {} 12 | ListNode(int x) : val(x), next(nullptr) {} 13 | ListNode(int x, ListNode *next) : val(x), next(next) {} 14 | }; 15 | 16 | class PalindromLinkedList { 17 | public: 18 | bool isPalindrome(ListNode* head) { 19 | // Step-I: Find size. 20 | int size = 0; 21 | ListNode* curr = head; 22 | while (curr != nullptr) { 23 | ++size; 24 | curr = curr->next; 25 | } 26 | 27 | // Step-II: Push elements in the stack. 28 | stack st; 29 | int mid = size/2; 30 | curr = head; 31 | for (int i = 0; i < size; ++i, curr = curr->next) { 32 | if (((size %2) == 1) && (i == mid)) continue; 33 | else if (i < mid) st.push(curr); 34 | else { 35 | ListNode* node = st.top(); 36 | st.pop(); 37 | if (node->val != curr->val) return false; 38 | } 39 | } 40 | return true; 41 | } 42 | }; -------------------------------------------------------------------------------- /LinkedList/TwoNumbersList.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/add-two-numbers/ 2 | // Definition for singly-linked list. 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class TwoNumbersList { 12 | public: 13 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 14 | ListNode* curr1 = l1; 15 | ListNode* curr2 = l2; 16 | ListNode* result = nullptr; 17 | ListNode* prevNode = nullptr; 18 | int carry_over = 0; 19 | while (true) { 20 | int sum = carry_over; 21 | if (curr1 != nullptr) { sum += curr1->val; curr1 = curr1->next; } 22 | if (curr2 != nullptr) { sum += curr2->val; curr2 = curr2->next; } 23 | carry_over = sum / 10; 24 | if (sum >= 10) sum -= 10; 25 | ListNode* newNode = new ListNode(sum); 26 | if (result == nullptr) result = newNode; 27 | else prevNode->next = newNode; 28 | prevNode = newNode; 29 | if (curr1 == nullptr && curr2 == nullptr) { 30 | if (carry_over == 1) { 31 | ListNode* newNode = new ListNode(1); 32 | if (result == nullptr) result = newNode; 33 | else prevNode->next = newNode; 34 | } 35 | break; 36 | } 37 | } 38 | return result; 39 | } 40 | }; -------------------------------------------------------------------------------- /Stack/MakeStringValid.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class MakeStringValid { 9 | public: 10 | string minRemoveToMakeValid(string s) { 11 | stack s_stack; 12 | string output = ""; 13 | // Forward Pass 14 | for (int i = 0; i < s.size(); ++i) { 15 | char ch = s[i]; 16 | if (ch == ')') { 17 | if (s_stack.empty()) continue; 18 | s_stack.pop(); 19 | } 20 | if (ch == '(') s_stack.push(ch); 21 | output.append(1, ch); 22 | } 23 | while (not s_stack.empty()) s_stack.pop(); 24 | vector to_erase; 25 | // Backward Pass 26 | for (int i = output.size() - 1; i >= 0; --i) { 27 | char ch = output[i]; 28 | if (ch == '(') { 29 | if (s_stack.empty()) to_erase.push_back(i); 30 | else s_stack.pop(); 31 | } else if (ch == ')') { 32 | s_stack.push(ch); 33 | } 34 | } 35 | for (int i = 0; i < to_erase.size(); ++i) { 36 | output.erase(to_erase[i], 1); 37 | } 38 | return output; 39 | } 40 | }; -------------------------------------------------------------------------------- /Array/ArrayIntersection/go/ArrayIntersection.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | // mark the occurrence of elements in num1 and check if it is present in num2 8 | // Space Complexity: O(n) 9 | // Time Complexity: O(n) 10 | func intersection(nums1 []int, nums2 []int) []int { 11 | m := make(map[int]bool) 12 | for _, n := range nums1 { 13 | m[n] = true 14 | } 15 | res := make([]int, 0) 16 | for _, n := range nums2 { 17 | if _, ok := m[n]; ok { 18 | res = append(res, n) 19 | delete(m, n) 20 | } 21 | } 22 | return res 23 | } 24 | 25 | // sort the nums1 and nums2 and then iterate through them 26 | // use two pointer to keep track of the current index in nums1 and nums2 27 | // Space Complexity: O(1) 28 | // Time Complexity: O(nlog(n)) 29 | func intersection2(nums1 []int, nums2 []int) []int { 30 | sort.Ints(nums1) 31 | sort.Ints(nums2) 32 | res := make([]int, 0) 33 | i, j := 0, 0 34 | for i < len(nums1) && j < len(nums2) { 35 | if nums1[i] == nums2[j] { 36 | // if the element is already in the result, skip it 37 | if len(res) > 0 && res[len(res)-1] != nums2[j] || len(res) == 0 { 38 | res = append([]int{nums1[i]}, res...) 39 | } 40 | i++ 41 | j++ 42 | } else if nums1[i] < nums2[j] { 43 | i++ 44 | } else { 45 | j++ 46 | } 47 | } 48 | return res 49 | } 50 | -------------------------------------------------------------------------------- /Heap/KFrequentElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Elem { 8 | Elem(int value, int count) { this->value = value; this->count = count; } 9 | int value; 10 | int count; 11 | }; 12 | 13 | struct ComparisonClass { 14 | bool operator() (const Elem& l, const Elem& r) { 15 | return l.count < r.count; 16 | } 17 | }; 18 | 19 | 20 | class KFrequentElement { 21 | public: 22 | vector topKFrequent(vector& nums, int k) { 23 | unordered_map count_map; 24 | unordered_map::iterator it; 25 | priority_queue, ComparisonClass> pq; 26 | 27 | // Build Map. 28 | for (int i = 0; i < nums.size(); ++i) { 29 | count_map[nums.at(i)]++; 30 | } 31 | 32 | // Build Queue. 33 | for (it = count_map.begin(); it != count_map.end(); ++it) { 34 | pq.push(Elem(it->first, it->second)); 35 | } 36 | 37 | // Get Elements. 38 | vector result; 39 | int count = 0; 40 | while (count < k && pq.size() > 0) { 41 | result.push_back(pq.top().value); 42 | pq.pop(); 43 | count++; 44 | } 45 | return result; 46 | } 47 | }; -------------------------------------------------------------------------------- /Tree/BinaryTreeMaximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/binary-tree-maximum-path-sum/ 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 BinaryTreeMaximumPathSum { 13 | public: 14 | int maxPathSum(TreeNode* root) { 15 | maxSum(root); 16 | return this->_msum; 17 | } 18 | 19 | private: 20 | int maxSum(TreeNode* node) { 21 | // Handling the base-case. 22 | if (node == nullptr) return 0; 23 | 24 | // Max-sum through children node. 25 | int maxSumLeft = std::max(maxSum(node->left), 0); 26 | int maxSumRight = std::max(maxSum(node->right), 0); 27 | 28 | // Calculating the sum through the root-node. 29 | int node_sum = node->val + maxSumLeft + maxSumRight; 30 | if (node_sum > this->_msum) this->_msum = node_sum; 31 | 32 | // Returning the sum assuming this node is part of the path. 33 | return node->val + max(maxSumLeft , maxSumRight); 34 | } 35 | 36 | int _msum = INT_MIN; 37 | }; -------------------------------------------------------------------------------- /Array/ConsecutiveOnes/go/ConsecutiveOnes_test.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_findMaxConsecutiveOnes(t *testing.T) { 8 | type args struct { 9 | nums []int 10 | } 11 | tests := []struct { 12 | name string 13 | args args 14 | want int 15 | }{ 16 | { 17 | name: "Test 1", 18 | args: args{ 19 | nums: []int{1, 1, 0, 1, 1, 1}, 20 | }, 21 | want: 3, 22 | }, 23 | { 24 | name: "Test 2", 25 | args: args{ 26 | nums: []int{0, 1, 0, 1, 1, 1, 1}, 27 | }, 28 | want: 4, 29 | }, 30 | { 31 | name: "Test 3", 32 | args: args{ 33 | nums: []int{1, 1, 1, 1, 1, 1, 1}, 34 | }, 35 | want: 7, 36 | }, 37 | { 38 | name: "Test 4", 39 | args: args{ 40 | nums: []int{}, 41 | }, 42 | want: 0, 43 | }, 44 | { 45 | name: "Test 5", 46 | args: args{ 47 | nums: []int{0, 0, 0}, 48 | }, 49 | want: 0, 50 | }, 51 | } 52 | for _, tt := range tests { 53 | t.Run(tt.name, func(t *testing.T) { 54 | if got := findMaxConsecutiveOnes(tt.args.nums); got != tt.want { 55 | t.Errorf("findMaxConsecutiveOnes() = %v, want %v", got, tt.want) 56 | } 57 | if got := findMaxConsecutiveOnes2(tt.args.nums); got != tt.want { 58 | t.Errorf("findMaxConsecutiveOnes()2 = %v, want %v", got, tt.want) 59 | } 60 | }) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Graph/TilePossibilities.cpp: -------------------------------------------------------------------------------- 1 | // Problem: https://leetcode.com/problems/letter-tile-possibilities/ 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class TilePossibilities { 9 | public: 10 | int numTilePossibilities(const string& tiles) { 11 | unordered_set combinations; 12 | combinations.insert(""); 13 | string tile; 14 | generateNext(tiles, 0, combinations); 15 | return combinations.size() - 1; 16 | } 17 | 18 | void generateNext( 19 | const string& tiles, int index, unordered_set& combinations) { 20 | if (index == tiles.size()) return; 21 | generateNext(tiles, index + 1, combinations); 22 | char ch = tiles[index]; 23 | unordered_set::iterator it; 24 | unordered_set tmp = combinations; 25 | for (it = combinations.begin(); it != combinations.end(); ++it) stringCombinations(*it, ch, tmp); 26 | combinations = tmp; 27 | } 28 | 29 | void stringCombinations(const string& st, char ch, unordered_set& combinations) { 30 | for (int i = 0; i <= st.size(); ++i) { 31 | string new_st = st; 32 | new_st.insert(new_st.begin() + i, ch); 33 | combinations.insert(new_st); 34 | } 35 | } 36 | }; -------------------------------------------------------------------------------- /Graph/GraphValidTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool validTree(int n, vector>& edges) { 8 | // Base Case. 9 | if (edges.size() != (n - 1)) return false; 10 | 11 | // Step-1: Build adjacency-list. 12 | vector emptyVec; 13 | vector> adjacencyList(n, emptyVec); 14 | for (const auto& edge : edges) { 15 | adjacencyList[edge[0]].push_back(edge[1]); 16 | adjacencyList[edge[1]].push_back(edge[0]); 17 | } 18 | 19 | // Step-II: DFS. 20 | unordered_set seen; 21 | return dfs(0, -1, adjacencyList, seen) && seen.size() == n; 22 | } 23 | 24 | private: 25 | bool dfs(int node, int parent, 26 | const vector>& adjacencyList, unordered_set& seen) { 27 | if (seen.find(node) != seen.end()) return false; 28 | seen.insert(node); 29 | 30 | const vector& neighbors = adjacencyList.at(node); 31 | for (const int neighbor : neighbors) { 32 | if (parent != neighbor) { 33 | if (not dfs(neighbor, node, adjacencyList, seen)) { 34 | return false; 35 | } 36 | } 37 | } 38 | return true; 39 | } 40 | }; --------------------------------------------------------------------------------