├── .gitignore ├── Arrays ├── Kth_Largest_Element_in_an_Array.cpp ├── distributecandiestopeople.cpp ├── fibonaccinumber.cpp ├── findduplicatenumber.cpp ├── insertintervals.cpp ├── intersectionoftwoarrays.cpp ├── intersectionoftwoarraysii.cpp ├── largestrectangleinhistogram.cpp ├── maximumconsecutiveonesiii.cpp ├── maximumgap.cpp ├── maximumsubarray.cpp ├── medianoftwosortedarray.cpp ├── mergeintervals.cpp ├── minimumsizesubarray.cpp ├── moveZeros.cpp ├── moveposneg.cpp ├── nextpermutation.cpp ├── numberofmatchingsubsequences.cpp ├── productofarrayexceptself.cpp ├── reversearray.cpp ├── rotatearray.cpp ├── runningsumof1darray.cpp ├── sortarraybyparityii.cpp ├── subarraysumequalsk.cpp └── zerosumsubarrays.cpp ├── BackTracking ├── combinations.cpp ├── combinationsum.cpp ├── combinationsumii.cpp ├── graycode.cpp ├── knightstourproblem.cpp ├── lettercombinationofphonenumber.cpp ├── nqueens.cpp ├── nqueensii.cpp ├── palindromepartitioning.cpp ├── permutations.cpp ├── permutationsii.cpp ├── permutationwithspaces.cpp ├── ratinamaze.cpp ├── subsets.cpp ├── subsetsii.cpp ├── wordbreakii.cpp └── wordsearch.cpp ├── BinarySearch ├── aggressivecows.cpp ├── allocatebooks.cpp ├── allocateminimumnumberofpages.cpp ├── capacitytoshippackageswithinddays.cpp ├── checkifnanditsdoubleexist.cpp ├── countnegativenumbersinasortedmatrix.cpp ├── countrotationinsortedarray.cpp ├── findfirstandlastpositionofelementinsortedarray.cpp ├── findminimuminrotatedsortedarray.cpp ├── findpeakelement.cpp ├── findthesmallestdivisorgivenathreshold.cpp ├── kokoeatingbananas.cpp ├── painterspartitionproblem.cpp ├── searchinbitonicarray.cpp ├── searchinrotatedsortedarray.cpp ├── thekweakestrowsinamatrix.cpp └── validtrianglenumber.cpp ├── BinarySearchTrees ├── binarytreetobst.cpp ├── brothersfromdifferentroots.cpp ├── constructbinarysearchtreefrompreordertraversal.cpp ├── convertsortedarraytobinarysearchtree.cpp ├── countbstnodethatlieinagivenrange.cpp ├── deletenodeinabst.cpp ├── insertintoabinarysearchtree.cpp ├── kthsmallestelementinabst.cpp ├── leafatsamelevel.cpp ├── lowestcommonancestorofabinarysearchtree.cpp ├── populatingnextrightpointerineachnode.cpp ├── preordertopostorder.cpp ├── rangesumofbst.cpp ├── searchinabinarytree.cpp └── validatebinarysearchtree.cpp ├── BinaryTrees ├── balancedbinarytree.cpp ├── binarytreeinordertraversal.cpp ├── binarytreelevelordertraversal.cpp ├── binarytreelevelordertraversalii.cpp ├── binarytreemaximumpathsum.cpp ├── binarytreepaths.cpp ├── binarytreepostordertraversal.cpp ├── binarytreepreordertraversal.cpp ├── binarytreerightsideview.cpp ├── binarytreezigzaglevelordertraversal.cpp ├── checkwhetherbstcontainsdeadend.cpp ├── constructbinarytreefrominorderandpostorder.cpp ├── constructbinarytreefrompreorderandinorder.cpp ├── constructstringfrombinarytree.cpp ├── cousinsinbinarytrees.cpp ├── diameterofbinarytree.cpp ├── findbottomlefttreevalue.cpp ├── flattenbinarytreetolinkedlist.cpp ├── invertbinarytree.cpp ├── lowestcommonancestorofabinarytree.cpp ├── lowestcommonancestorofbst.cpp ├── maximumdepthofbinarytree.cpp ├── maximumdepthofn-arytree.cpp ├── mergetwobinarytrees.cpp ├── pathsum.cpp ├── pathsumii.cpp ├── populatingnextrightpointersineachnode.cpp ├── sametree.cpp ├── sumroottoleafnumbers.cpp └── symmetrictree.cpp ├── BitManipulation ├── countingbits.cpp ├── numberof1bits.cpp ├── powerof2.cpp ├── reversebits.cpp ├── singlenumber.cpp ├── singlenumberii.cpp └── singlenumberiii.cpp ├── DynamicProgramming ├── besttimetobuyandsellstockiii.cpp ├── besttimetobuysellstock.cpp ├── besttimetobuysellstockii.cpp ├── burstballoons.cpp ├── cherrypickupii.cpp ├── climbingstairs.cpp ├── coinchange.cpp ├── coinchange2.cpp ├── combinationsumiv.cpp ├── countnumberofsubsetwithgivendifference.cpp ├── countsubsetwithgivensum.cpp ├── distinctsubsequences.cpp ├── dungeongame.cpp ├── editdistance.cpp ├── evaluateexpressiontotrue.cpp ├── houserobber.cpp ├── interleavingstring.cpp ├── issubsequence.cpp ├── jumpgame.cpp ├── kinversepairsarray.cpp ├── knapsackproblem.cpp ├── knightprobabilityinchessboard.cpp ├── largestdivisiblesubset.cpp ├── laststoneweightii.cpp ├── longestcommonsubsequence.cpp ├── longestcommonsubstring.cpp ├── longestincreasingsubsequence.cpp ├── longestpalindromicsubsequence.cpp ├── longestrepeatingsubsequence.cpp ├── matrixchainmultiplication.cpp ├── maximalsquare.cpp ├── maximumlengthofpairchain.cpp ├── maximumlengthofrepeatedsubarray.cpp ├── minimumasciideletesumfor2strings.cpp ├── minimumcostclimbingstairs.cpp ├── minimumfallingpathsum.cpp ├── minimuminsertionstomakeastringpalindrome.cpp ├── minimumnumberofdeletionsandinsertions.cpp ├── minimumnumberofdeletionsinastringtomakeitapalindrome.cpp ├── minimumpathsum.cpp ├── minimumsubsetsumdifference.cpp ├── outofboundarypaths.cpp ├── palindromepartitioningii.cpp ├── palindromicsubstrings.cpp ├── partitionequalsubsetsum.cpp ├── printinglongestcommonsubsequence.cpp ├── rodcuttingproblem.cpp ├── scramblestring.cpp ├── shortestcommonsupersequence.cpp ├── shortestcommonsupersequencei.cpp ├── stonegamevii.cpp ├── subsetsum.cpp ├── supereggdrop.cpp ├── targetsum.cpp ├── triangle.cpp ├── unboundedknapsack.cpp ├── uniquepaths.cpp ├── uniquepathsii.cpp └── wordbreak.cpp ├── Graph ├── 01matrix.cpp ├── accountsmerge.cpp ├── allpathfromsourcetotarget.cpp ├── asfarfromlandaspossible.cpp ├── bellmanfordalgorithm.cpp ├── bfs.cpp ├── cheapestflightswithinkstops.cpp ├── clonegraph.cpp ├── connectedcomponentsinanundirectedgraph.cpp ├── courseschedule.cpp ├── coursescheduleii.cpp ├── detectcycleindirectedgraph.cpp ├── detectcycleinundirectedgraph.cpp ├── dfs.cpp ├── dijkstrasalgorithmusingpriorityqueuestl.cpp ├── disjointset.cpp ├── findeventualsafestates.cpp ├── findthecitywiththesmallestnumberofneighborsatathresholddistance.cpp ├── floodfill.cpp ├── floydwarshallalgorithm.cpp ├── implementingdijkstra.cpp ├── isgraphbipartite.cpp ├── jumpgameiii.cpp ├── keysandrooms.cpp ├── krushkalsalgorithm.cpp ├── maxareaofisland.cpp ├── minimumheighttrees.cpp ├── negativeweightcycle.cpp ├── networkdelaytime.cpp ├── numberofislands.cpp ├── numberofoperationstomakenetworkconnected.cpp ├── numberofprovinces.cpp ├── numbersoftrianglesindirectedandundirectedgraph.cpp ├── possiblebipartition.cpp ├── primsalgotihms.cpp ├── printstronglyconnectedcomponents.cpp ├── ratinamazeproblem-i.cpp ├── redundantconnection.cpp ├── rottingoranges.cpp ├── satisfiabilityofequalityequations.cpp ├── shortestpathinbinarymatrix.cpp ├── stronglyconnectedcomponents(kosaraju'salgo).cpp ├── stronglyconnectedcomponents.cpp ├── surroundedregions.cpp └── topologicalsort.cpp ├── Greedy ├── carpooling.cpp ├── fractionalknapsack.cpp ├── gasstation.cpp ├── huffmanencoding.cpp ├── minimumdeletionstomakecharacterfrequenciesunique.cpp ├── minimumnumberofcoins.cpp ├── minimumplatforms.cpp ├── nmeetingsinoneroom.cpp └── wigglesubsequence.cpp ├── HashMap ├── isomorphicstrings.cpp ├── longestconsecutivesequence.cpp ├── lrucache.cpp ├── majorityelement.cpp ├── majorityelementii.cpp └── reducearraysizetothehalf.cpp ├── Heap ├── kclosestpointstoorigin.cpp ├── klargestelements.cpp ├── kthsmallestelement.cpp ├── kthsmallestelementinsortedmatrix.cpp ├── minimumnumberofrefuelingstops.cpp ├── topkfrequentelements.cpp └── topkfrequentwords.cpp ├── LICENSE ├── LinkedList ├── addtwonumbers.cpp ├── deleteloopinlinkedlist.cpp ├── intersectionoftwolinkedlist.cpp ├── linkedlistcycle.cpp ├── linkedlistcycleii.cpp ├── mergeksortedlist.cpp ├── mergetwosortedlist.cpp ├── middleofthelinkedlist.cpp ├── nextgreaternodeinlinkedlist.cpp ├── oddevenlinkedlist.cpp ├── palindromelinkedlist.cpp ├── removeduplicatesfromsortedlist.cpp ├── removeduplicatesfromsortedlistii.cpp ├── removenthnodefromendoflinkedlist.cpp ├── reorderlist.cpp ├── reverselinkedlist.cpp ├── reverselinkedlistii.cpp ├── reversenodesinkgroup.cpp ├── rotatelist.cpp ├── sortList.cpp ├── sumofleftleaves.cpp └── swapnodesinpairs.cpp ├── Maths ├── minimumoperationstomakearrayequal.cpp ├── powerofthree.cpp └── poweroftwo.cpp ├── Matrix ├── determinewhetherthematrixcanbeobtainedbyrotation.cpp ├── kthsmallestelementinasortedmatrix.cpp ├── maximumsumrectangle.cpp ├── reshapethematrix.cpp ├── rotateimage.cpp ├── searcha2dmatrix.cpp ├── searcha2dmatrixii.cpp ├── setmatrixzeroes.cpp ├── spiralmatrix.cpp └── validsudoku.cpp ├── README.md ├── Recursion ├── deletemiddleelementofastack.cpp ├── findthewinnerofthecirculargame.cpp ├── finduniquebinarystring.cpp ├── generateparantheses.cpp ├── kthsymbolingrammar.cpp ├── lettercasepermutation.cpp ├── printnbitbinarynumbershavingmore1than0.cpp ├── sortastack.cpp └── uniquepathsiii.cpp ├── Searching&Sorting ├── countinversion.cpp ├── mergesortedarray.cpp └── nonoverlappingintervals.cpp ├── SlidingWindow ├── countoccurrencesofanagrams.cpp ├── findallanagramsinastring.cpp ├── firstnegativeineverywindowofsizek.cpp ├── longestkuniquecharacterssubstring.cpp ├── longestsubarraywithsumk.cpp ├── longestsubstringwithoutrepeatingcharacters.cpp ├── maximumerasurevalue.cpp ├── maximumofallsubarraysofsizek.cpp ├── maximumsumsubarrayofsizek.cpp ├── minimumwindowsubstring.cpp ├── numberofsubarraysofsizekavggreaterthanorequaltothreshold.cpp ├── slidingwindowmaximum.cpp └── subarraywithkdifferentintegers.cpp ├── Stack&Queues ├── asteroidcollision.cpp ├── evaluationofpostfixexpression.cpp ├── firstnegativeintegerineverywindowofsizek.cpp ├── gamewithstring.cpp ├── implementqueueusingstack.cpp ├── implementstackusingqueues.cpp ├── minimumremovetomakevalidparanthesis.cpp ├── minstack.cpp ├── queuereversal.cpp ├── reversefirstkelementsofqueue.cpp ├── reversesubstringbetweeneachpairofparantheses.cpp ├── simplifypath.cpp ├── sortastack.cpp └── validparanthesis.cpp ├── String ├── addstrings.cpp ├── boardgameproblem.cpp ├── checkifonestringswapcanmakestringsequal.cpp ├── checkiftwostringsareequal.cpp ├── editdistance.cpp ├── excelsheetcolumnnumber.cpp ├── groupanagrams.cpp ├── longestcommonprefix.cpp ├── longestpalindromicsubstring.cpp ├── maximumproductofwordlengths.cpp ├── minimumaddtomakeparanthesisvalid.cpp ├── possiblepermutationsofstring.cpp ├── reverseonlyletters.cpp ├── reversestring.cpp ├── rotatestring.cpp ├── sortingthesentence.cpp └── stringtointeger.cpp ├── Trie ├── designaddandsearchwordsdatastructure.cpp ├── distinctsubstrings.cpp ├── implementtrie.cpp ├── maximumxoroftwonumbersinanarray.cpp └── maximumxorwithanelementfromanarray.cpp └── Two Pointers ├── 3sum.cpp ├── 3sumclosest.cpp ├── 4sum.cpp ├── containerwithmostwater.cpp ├── mergesortedarray.cpp ├── sortColors.cpp ├── trappingrainwater.cpp ├── twosum.cpp └── twosumii.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | #MAC 2 | .DS_Store 3 | 4 | # Prerequisites 5 | *.d 6 | 7 | # Compiled Object files 8 | *.slo 9 | *.lo 10 | *.o 11 | *.obj 12 | 13 | # Precompiled Headers 14 | *.gch 15 | *.pch 16 | 17 | # Compiled Dynamic libraries 18 | *.so 19 | *.dylib 20 | *.dll 21 | 22 | # Fortran module files 23 | *.mod 24 | *.smod 25 | 26 | # Compiled Static libraries 27 | *.lai 28 | *.la 29 | *.a 30 | *.lib 31 | 32 | # Executables 33 | *.exe 34 | a.out 35 | *.out 36 | *.app 37 | 38 | build/ -------------------------------------------------------------------------------- /Arrays/Kth_Largest_Element_in_an_Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 215. Kth Largest Element in an Array 3 | https://leetcode.com/problems/kth-largest-element-in-an-array/ 4 | */ 5 | //Solution 1 6 | class Solution 7 | { 8 | public: 9 | int findKthLargest(vector &nums, int k) 10 | { 11 | 12 | 13 | sort(nums.begin(), nums.end()); 14 | return nums[nums.size() - k]; 15 | } 16 | }; 17 | 18 | //Solution 2 19 | class Solution 20 | { 21 | public: 22 | int findKthLargest(vector &nums, int k) 23 | { 24 | 25 | priority_queue pq; 26 | 27 | for (int i = 0; i < nums.size(); i++) 28 | pq.push(nums[i]); 29 | 30 | //remove the k-1 elements from top 31 | for (int i = 0; i < k - 1; i++) 32 | pq.pop(); 33 | 34 | //required element will come on top 35 | return pq.top(); 36 | } 37 | }; -------------------------------------------------------------------------------- /Arrays/distributecandiestopeople.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1103. Distribute Candies to People 3 | https://leetcode.com/problems/distribute-candies-to-people/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector distributeCandies(int candies, int num_people) 10 | { 11 | vector result(num_people, 0); 12 | 13 | int i = 0, k = 1; 14 | 15 | while (candies > 0){ 16 | if (candies - k >= 0) 17 | result[i % num_people] += k; 18 | else 19 | result[i % num_people] += candies; 20 | 21 | candies -= k; 22 | i++; 23 | k++; 24 | } 25 | return result; 26 | } 27 | }; -------------------------------------------------------------------------------- /Arrays/fibonaccinumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 509. Fibonacci Number 3 | https://leetcode.com/problems/fibonacci-number/ 4 | */ 5 | 6 | //Recusrion 7 | class Solution 8 | { 9 | public: 10 | //Time: O(2^N), Space: O(N) 11 | int fib(int n) 12 | { 13 | if (n == 0 || n == 1) 14 | return n; 15 | return fib(n - 1) + fib(n - 2); 16 | } 17 | }; 18 | 19 | //Memoization - TopDown 20 | class Solution 21 | { 22 | public: 23 | //Time: O(N), Space: O(N) 24 | int fib(int n) 25 | { 26 | if (n == 0 || n == 1) 27 | return n; 28 | vector dp(n + 1, 0); 29 | dp[0] = 0; 30 | dp[1] = 1; 31 | return helper(dp, n); 32 | } 33 | 34 | int helper(vector &dp, int n) 35 | { 36 | for (int i = 2; i <= n; i++) 37 | { 38 | dp[i] = dp[i - 1] + dp[i - 2]; 39 | } 40 | return dp[n]; 41 | } 42 | }; 43 | 44 | //Bottom Up 45 | class Solution 46 | { 47 | public: 48 | //Time: O(N), Space: O(N) 49 | int fib(int n) 50 | { 51 | vector _fib(n + 1, 0); 52 | 53 | for (int i = 0; i <= n; i++) 54 | { 55 | if (i == 0 || i == 1) 56 | _fib[i] = i; 57 | else 58 | _fib[i] = _fib[i - 1] + _fib[i - 2]; 59 | } 60 | return _fib[n]; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /Arrays/findduplicatenumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 287. Find the Duplicate Number 3 | https://leetcode.com/problems/find-the-duplicate-number/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int findDuplicate(vector &nums) 10 | { 11 | //Time: O(n), Space: O(n) 12 | set s; 13 | 14 | for (int i = 0; i < nums.size(); i++){ 15 | if (s.find(nums[i]) == s.end()) 16 | s.insert(nums[i]); 17 | else 18 | return nums[i]; 19 | } 20 | return false; 21 | } 22 | }; 23 | 24 | //Todo: Convert this problem into Linked List Cycle problem -------------------------------------------------------------------------------- /Arrays/insertintervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 57. Insert Interval 3 | https://leetcode.com/problems/insert-interval/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //O(nlogn) 10 | static bool comp(vector a, vector b) 11 | { 12 | return a[0] < b[0]; 13 | } 14 | 15 | vector> insert(vector> &intervals, vector &newInterval) 16 | { 17 | 18 | intervals.push_back(newInterval); 19 | sort(intervals.begin(), intervals.end()); 20 | 21 | int index = 0; 22 | for (int i = 1; i < intervals.size(); i++){ 23 | //overlap situation 24 | if (intervals[index][1] >= intervals[i][0]){ 25 | intervals[index][0] = min(intervals[index][0], intervals[i][0]); 26 | intervals[index][1] = max(intervals[index][1], intervals[i][1]); 27 | } 28 | else{ 29 | ++index; 30 | intervals[index] = intervals[i]; 31 | } 32 | } 33 | 34 | vector> result; 35 | 36 | for (int i = 0; i <= index; i++){ 37 | result.push_back(intervals[i]); 38 | } 39 | 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /Arrays/intersectionoftwoarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 349. Intersection of Two Arrays 3 | https://leetcode.com/problems/intersection-of-two-arrays/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector intersection(vector &nums1, vector &nums2) 10 | { 11 | 12 | //Time: O(n) 13 | set s1; 14 | set s2; 15 | vector result; 16 | 17 | //insert all the unique values to the set 18 | for (int i = 0; i < nums1.size(); i++) 19 | s1.insert(nums1[i]); 20 | 21 | //check all the element from nums2 that are present in s1 22 | //and put in the s2 23 | for (int i = 0; i < nums2.size(); i++){ 24 | if (s1.find(nums2[i]) != s1.end()) 25 | s2.insert(nums2[i]); 26 | } 27 | 28 | //push the elements from set to the vector 29 | set::iterator itr; 30 | for (itr = s2.begin(); itr != s2.end(); itr++) 31 | result.push_back(*itr); 32 | 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /Arrays/intersectionoftwoarraysii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 350. Intersection of Two Arrays II 3 | https://leetcode.com/problems/intersection-of-two-arrays-ii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector intersect(vector &nums1, vector &nums2) 10 | { 11 | sort(nums1.begin(), nums1.end()); 12 | sort(nums2.begin(), nums2.end()); 13 | 14 | int i = 0, j = 0; 15 | vector result; 16 | 17 | while (i < nums1.size() && j < nums2.size()){ 18 | if (nums1[i] == nums2[j]){ 19 | result.push_back(nums1[i]); 20 | i++; 21 | j++; 22 | } 23 | else if (nums1[i] > nums2[j]){ 24 | j++; 25 | } 26 | else 27 | i++; 28 | } 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /Arrays/maximumconsecutiveonesiii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1004. Max Consecutive Ones III 3 | https://leetcode.com/problems/max-consecutive-ones-iii/ 4 | */ 5 | 6 | /* 7 | The idea is simple, use two pointer approach, when you encounter one increase the pointer by 1 8 | and when you encounter 0 decrease k and increase the pointer untill it becomes 0, then take 9 | the length and store it. Again if k = 0, then move the left pointer till k = 1, inorder to 10 | create a new window. 11 | */ 12 | class Solution 13 | { 14 | public: 15 | //Time: O(N), Space: O(1) 16 | int longestOnes(vector &nums, int k) 17 | { 18 | int i = 0, j = 0; 19 | int n = nums.size(); 20 | int len = 0; 21 | while (j < n) 22 | { 23 | //if nums[j] = 1 24 | if (nums[j]) 25 | j++; 26 | else 27 | { 28 | //if nums[j] = 0, there could be two possible situation, k=0 or k!=0 29 | if (k == 0) 30 | { 31 | len = max(len, j - i); 32 | 33 | //to create a new window shift the left pointer till k = 1 34 | while (k == 0) 35 | { 36 | if (nums[i]) 37 | i++; 38 | else 39 | k++, i++; 40 | } 41 | } 42 | else //decrease the k value and increase the pointer 43 | k--, j++; 44 | } 45 | } 46 | //return the maximum length 47 | len = max(len, (j - i)); 48 | return len; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Arrays/maximumgap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 164. Maximum Gap 3 | https://leetcode.com/problems/maximum-gap/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int maximumGap(vector &nums) 10 | { 11 | if (nums.size() < 2) 12 | return 0; 13 | 14 | sort(nums.begin(), nums.end()); 15 | int global_max_diff = 0, curr_max_diff = 0; 16 | 17 | int i = 0; 18 | while (i < nums.size() - 1){ 19 | curr_max_diff = abs(nums[i] - nums[i + 1]); 20 | if (global_max_diff < curr_max_diff) 21 | global_max_diff = curr_max_diff; 22 | curr_max_diff = 0; 23 | i++; 24 | } 25 | return global_max_diff; 26 | } 27 | }; -------------------------------------------------------------------------------- /Arrays/maximumsubarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 53. Maximum Subarray 3 | https://leetcode.com/problems/maximum-subarray/ 4 | */ 5 | 6 | // Brute Froce 7 | class Solution 8 | { 9 | public: 10 | // Time: O(N^2), Space: O(1) 11 | int maxSubArray(vector &nums) 12 | { 13 | int maxSum = INT_MIN; 14 | for (int i = 0; i < nums.size(); i++) 15 | { 16 | int sum = 0; 17 | for (int j = i; j < nums.size(); j++) 18 | { 19 | sum += nums[j]; 20 | maxSum = max(sum, maxSum); 21 | } 22 | } 23 | return maxSum; 24 | } 25 | }; 26 | 27 | // Kadane's Algorithm - Dynamic Programming 28 | class Solution 29 | { 30 | public: 31 | // Time: O(N), Space: O(1) 32 | int maxSubArray(vector &nums) 33 | { 34 | int maxSoFar = nums[0]; 35 | int globalMax = nums[0]; 36 | 37 | for (int i = 1; i < nums.size(); i++) 38 | { 39 | maxSoFar = max(nums[i], nums[i] + maxSoFar); 40 | globalMax = max(globalMax, maxSoFar); 41 | } 42 | return globalMax; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Arrays/medianoftwosortedarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 4. Median of Two Sorted Arrays 3 | https://leetcode.com/problems/median-of-two-sorted-arrays/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | double findMedianSortedArrays(vector &nums1, vector &nums2) 10 | { 11 | vector temp; 12 | 13 | int m = nums1.size(), n = nums2.size(); 14 | int i = 0, j = 0; 15 | 16 | while (i < m && j < n){ 17 | if (nums1[i] <= nums2[j]){ 18 | temp.push_back(nums1[i]); 19 | i++; 20 | } 21 | else{ 22 | temp.push_back(nums2[j]); 23 | j++; 24 | } 25 | } 26 | 27 | while (i < m){ 28 | temp.push_back(nums1[i]); 29 | i++; 30 | } 31 | while (j < n){ 32 | temp.push_back(nums2[j]); 33 | j++; 34 | } 35 | 36 | int l = temp.size(); 37 | double sum = 0, median = 0; 38 | if (l % 2 == 0){ 39 | int idx = l / 2; 40 | sum = temp[idx] + temp[idx - 1]; 41 | median = sum / 2; 42 | } 43 | else{ 44 | int idx = l / 2; 45 | median = temp[idx]; 46 | } 47 | return median; 48 | } 49 | }; -------------------------------------------------------------------------------- /Arrays/mergeintervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 56. Merge Intervals 3 | https://leetcode.com/problems/merge-intervals/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //O(nlogn) 10 | //Todo: why put static 11 | static bool comp(vector a, vector b) 12 | { 13 | return a[0] < b[0]; 14 | } 15 | 16 | vector> merge(vector> &intervals) 17 | { 18 | 19 | // if(intervals.size() <= 1) 20 | // return intervals; 21 | 22 | sort(intervals.begin(), intervals.end(), comp); 23 | int index = 0; 24 | 25 | for (int i = 1; i < intervals.size(); i++){ 26 | //overlap situation 27 | if (intervals[index][1] >= intervals[i][0]){ 28 | intervals[index][0] = min(intervals[index][0], intervals[i][0]); 29 | intervals[index][1] = max(intervals[index][1], intervals[i][1]); 30 | } 31 | else{ 32 | ++index; 33 | intervals[index] = intervals[i]; 34 | } 35 | } 36 | 37 | vector> result; 38 | 39 | for (int i = 0; i <= index; i++){ 40 | result.push_back(intervals[i]); 41 | } 42 | 43 | return result; 44 | } 45 | }; -------------------------------------------------------------------------------- /Arrays/minimumsizesubarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 209. Minimum Size Subarray Sum 3 | https://leetcode.com/problems/minimum-size-subarray-sum/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int minSubArrayLen(int s, vector &nums) 10 | { 11 | //two pointer approach 12 | int left = 0; 13 | int sum = 0; 14 | int result = INT_MAX; 15 | 16 | for (int i = 0; i < nums.size(); i++){ 17 | sum += nums[i]; 18 | 19 | while (sum >= s){ 20 | result = min(result, i + 1 - left); 21 | sum -= nums[left++]; 22 | } 23 | } 24 | if (result != INT_MAX) 25 | return result; 26 | else 27 | return 0; 28 | } 29 | }; -------------------------------------------------------------------------------- /Arrays/moveZeros.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 283. Move Zeroes 3 | https://leetcode.com/problems/move-zeroes/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | void moveZeroes(vector &nums) 10 | { 11 | for (int lastNonzero = 0, current = 0; current < nums.size(); current++){ 12 | if (nums[current] != 0){ 13 | swap(nums[lastNonzero], nums[current]); 14 | lastNonzero++; 15 | } 16 | } 17 | } 18 | }; -------------------------------------------------------------------------------- /Arrays/moveposneg.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Move all negative numbers to beginning and positive to end with constant extra space 3 | Input: -12, 11, -13, -5, 6, -7, 5, -3, -6 4 | Output: -12 -13 -5 -7 -3 -6 11 6 5 5 | https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/ 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | int n; 14 | cin>>n; 15 | 16 | int arr[n]; 17 | 18 | for(int i=0; i>arr[i]; 20 | } 21 | 22 | //two pointer approach 23 | int left = 0, right = n-1; 24 | 25 | while(left <= right){ 26 | if(arr[left] < 0 && arr[right] < 0) 27 | left++; 28 | 29 | else if(arr[left] > 0 && arr[right] < 0){ 30 | swap(arr[left], arr[right]); 31 | left++; right--; 32 | } 33 | else if(arr[left] > 0 && arr[right] > 0){ 34 | right--; 35 | } 36 | else if(arr[left] < 0 && arr[right] > 0){ 37 | left++; 38 | right--; 39 | } 40 | } 41 | 42 | //display the array 43 | for(int i=0; i &nums) 10 | { 11 | int i = nums.size() - 2; 12 | //checking every element is sorted 13 | while (i >= 0 && nums[i] >= nums[i + 1]){ 14 | i--; 15 | } 16 | if (i >= 0){ 17 | int j = nums.size() - 1; 18 | while (j >= 0 && nums[j] <= nums[i]){ 19 | j--; 20 | } 21 | swap(nums, i, j); 22 | } 23 | reverse(nums, i + 1); 24 | } 25 | 26 | void reverse(vector &nums, int start) 27 | { 28 | int i = start, j = nums.size() - 1; 29 | 30 | while (i < j){ 31 | swap(nums, i, j); 32 | i++; 33 | j--; 34 | } 35 | } 36 | 37 | void swap(vector &nums, int i, int j) 38 | { 39 | int temp = nums[i]; 40 | nums[i] = nums[j]; 41 | nums[j] = temp; 42 | } 43 | }; -------------------------------------------------------------------------------- /Arrays/reversearray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Input : arr[] = {1, 2, 3, 4, 5, 6} 3 | Output : arr[] = {6, 5, 4, 3, 2, 1} 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | void reverseArray(int arr[], int n) 10 | { 11 | 12 | for (int i = 0; i < n / 2; i++){ 13 | int temp = arr[i]; 14 | arr[i] = arr[n - i - 1]; 15 | arr[n - i - 1] = temp; 16 | } 17 | 18 | //print the array 19 | for (int i = 0; i < n; i++) 20 | cout << arr[i] << " "; 21 | cout << endl; 22 | } 23 | 24 | int main() 25 | { 26 | int n; 27 | cin >> n; 28 | 29 | int arr[n]; 30 | 31 | for (int i = 0; i < n; i++){ 32 | cin >> arr[i]; 33 | } 34 | 35 | reverseArray(arr, n); 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Arrays/rotatearray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 189. Rotate Array 3 | https://leetcode.com/problems/rotate-array/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | void rotate(vector &nums, int k) 10 | { 11 | reverse(nums, 0, nums.size() - 1); 12 | k = k % nums.size(); // k could be more than the size of the array 13 | reverse(nums, 0, k - 1); 14 | reverse(nums, k, nums.size() - 1); 15 | } 16 | 17 | void reverse(vector &nums, int start, int end) 18 | { 19 | while (start < end){ 20 | int temp = nums[start]; 21 | nums[start] = nums[end]; 22 | nums[end] = temp; 23 | 24 | start++; 25 | end--; 26 | } 27 | } 28 | }; -------------------------------------------------------------------------------- /Arrays/runningsumof1darray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1480. Running Sum of 1d Array 3 | https://leetcode.com/problems/running-sum-of-1d-array/ 4 | */ 5 | 6 | //Solution 1 7 | class Solution 8 | { 9 | public: 10 | //Time: O(n^2), Space: O(n) 11 | vector runningSum(vector &nums) 12 | { 13 | int sum = 0; 14 | vector result; 15 | for (int i = 0; i < nums.size(); i++) 16 | { 17 | sum = 0; 18 | for (int j = 0; j <= i; j++) 19 | { 20 | sum += nums[j]; 21 | } 22 | result.push_back(sum); 23 | } 24 | return result; 25 | } 26 | }; 27 | 28 | //Solution 2 29 | class Solution 30 | { 31 | public: 32 | //Time: O(n), Space: O(n) 33 | vector runningSum(vector &nums) 34 | { 35 | int sum = 0; 36 | vector result; 37 | for (int i = 0; i < nums.size(); i++) 38 | { 39 | sum += nums[i]; 40 | result.push_back(sum); 41 | } 42 | return result; 43 | } 44 | }; 45 | 46 | //Solution 3 47 | class Solution 48 | { 49 | public: 50 | //Time: O(n), Space: O(1) 51 | vector runningSum(vector &nums) 52 | { 53 | for (int i = 1; i < nums.size(); i++) 54 | { 55 | nums[i] = nums[i] + nums[i - 1]; 56 | } 57 | return nums; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Arrays/sortarraybyparityii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 922. Sort Array By Parity II 3 | https://leetcode.com/problems/sort-array-by-parity-ii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector sortArrayByParityII(vector &A) 10 | { 11 | vector odd; 12 | vector even; 13 | int n = A.size(); 14 | // vector result; //can use one extra array also 15 | 16 | for (int i = 0; i < n; i++){ 17 | if (A[i] % 2 == 0){ 18 | even.push_back(A[i]); 19 | } 20 | else 21 | odd.push_back(A[i]); 22 | } 23 | A.clear(); 24 | for (int i = 0; i < n / 2; i++){ 25 | A.push_back(even[i]); 26 | A.push_back(odd[i]); 27 | } 28 | return A; 29 | } 30 | }; -------------------------------------------------------------------------------- /Arrays/subarraysumequalsk.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 560. Subarray Sum Equals K 3 | https://leetcode.com/problems/subarray-sum-equals-k/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int subarraySum(vector &nums, int k) 10 | { 11 | unordered_map mp; 12 | mp[0] = 1; 13 | int count = 0, sum = 0; 14 | for (int i = 0; i < nums.size(); i++){ 15 | sum += nums[i]; 16 | 17 | if (mp[sum - k]) 18 | count += mp[sum - k]; 19 | 20 | mp[sum]++; 21 | } 22 | return count; 23 | } 24 | }; -------------------------------------------------------------------------------- /Arrays/zerosumsubarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Zero Sum Subarrays 3 | https://practice.geeksforgeeks.org/problems/zero-sum-subarrays1825/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Function to count subarrays with sum equal to 0. 10 | /*the basic idea is to use the hashmap and store the count 11 | of 0 sum and traverse the array and add each element and check 12 | every time whether it is present in the map or not, if yes then 13 | add to the count and return else go through the loop. 14 | Time: O(N), Space: O(N)*/ 15 | ll findSubarray(vector arr, int n) 16 | { 17 | //code here 18 | ll count = 0; 19 | unordered_map mp; 20 | mp[0] = 1; 21 | ll sum = 0; 22 | for (int i = 0; i < n; i++) 23 | { 24 | sum += arr[i]; 25 | if (mp.find(sum) != mp.end()) 26 | { 27 | count += mp[sum]; 28 | mp[sum]++; 29 | } 30 | else 31 | { 32 | //creating the new pair 33 | mp[sum]++; 34 | } 35 | } 36 | return count; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /BackTracking/graycode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 89. Gray Code 3 | https://leetcode.com/problems/gray-code/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector grayCode(int n) 10 | { 11 | vector temp = getGrayCode(n); 12 | vector result; 13 | for (auto s : temp) 14 | { 15 | result.push_back(stoi(s, 0, 2)); 16 | } 17 | return result; 18 | } 19 | 20 | vector getGrayCode(int n) 21 | { 22 | if (n == 1) 23 | return {"0", "1"}; 24 | 25 | // get the gray code of the previous number 26 | vector previousNumberGrayCode = getGrayCode(n - 1); 27 | vector currentNumberGrayCode; 28 | int size = previousNumberGrayCode.size(); 29 | // add 0s in front to all the digits 30 | for (auto i : previousNumberGrayCode) 31 | { 32 | currentNumberGrayCode.push_back("0" + i); 33 | } 34 | 35 | // add 1s in front to all the digits but in reverse order 36 | for (int i = size - 1; i >= 0; i--) 37 | { 38 | currentNumberGrayCode.push_back("1" + previousNumberGrayCode[i]); 39 | } 40 | 41 | return currentNumberGrayCode; 42 | } 43 | }; -------------------------------------------------------------------------------- /BackTracking/permutationsii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 47. Permutations II 3 | https://leetcode.com/problems/permutations-ii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N.N! + NlogN), Space: O(N) 10 | vector > permutations; 11 | vector > permuteUnique(vector &nums) 12 | { 13 | sort(nums.begin(), nums.end()); 14 | generatePermutations(nums, 0); 15 | return permutations; 16 | } 17 | 18 | void generatePermutations(vector nums, int idx) 19 | { 20 | if (idx == nums.size()) 21 | { 22 | permutations.push_back(nums); 23 | return; 24 | } 25 | for (int i = idx; i < nums.size(); i++) 26 | { 27 | if (idx != i && nums[i] == nums[idx]) 28 | continue; 29 | swap(nums[idx], nums[i]); 30 | generatePermutations(nums, idx + 1); 31 | // swap(nums[idx], nums[i]); 32 | } 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /BackTracking/permutationwithspaces.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutation with Spaces 3 | https://practice.geeksforgeeks.org/problems/permutation-with-spaces3627/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector result; 10 | void helper(string S, string op) 11 | { 12 | if (S.size() == 0) 13 | { 14 | result.push_back(op); 15 | return; 16 | } 17 | 18 | string op1 = op; 19 | string op2 = op; 20 | 21 | //two choices 22 | //with spaces 23 | op1.push_back(' '); 24 | op1.push_back(S[0]); 25 | 26 | //without spaces 27 | op2.push_back(S[0]); 28 | 29 | S.erase(S.begin() + 0); 30 | 31 | helper(S, op1); 32 | helper(S, op2); 33 | } 34 | vector permutation(string S) 35 | { 36 | string op; 37 | op.push_back(S[0]); 38 | S.erase(S.begin() + 0); 39 | helper(S, op); 40 | return result; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /BackTracking/wordsearch.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 79. Word Search 3 | https://leetcode.com/problems/word-search/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | bool findWord(vector > &board, string word, int idx, int i, int j) 10 | { 11 | // base case or bound check 12 | if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || board[i][j] == '.' || board[i][j] != word[idx]) 13 | return false; 14 | 15 | if (idx == word.size() - 1) 16 | return true; 17 | char temp = board[i][j]; 18 | board[i][j] = '.'; 19 | 20 | bool found = findWord(board, word, idx + 1, i + 1, j) || 21 | findWord(board, word, idx + 1, i - 1, j) || 22 | findWord(board, word, idx + 1, i, j + 1) || 23 | findWord(board, word, idx + 1, i, j - 1); 24 | 25 | board[i][j] = temp; 26 | return found; 27 | } 28 | bool exist(vector > &board, string word) 29 | { 30 | int m = board.size(); 31 | int n = board[0].size(); 32 | 33 | for (int i = 0; i < m; i++) 34 | { 35 | for (int j = 0; j < n; j++) 36 | { 37 | // if(board[i][j] == word[0]) 38 | if (findWord(board, word, 0, i, j)) 39 | return true; 40 | } 41 | } 42 | return false; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /BinarySearch/aggressivecows.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | AGGRCOW - Aggressive cows 3 | https://www.spoj.com/problems/AGGRCOW/ 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | bool isValidDistance(vector &dist, int cows, int distance) 10 | { 11 | int cow = 1; 12 | int prevCow = v[0]; 13 | for (int i = 1; i < v.size(); i++) 14 | { 15 | if (v[i] - prevCow >= distance) 16 | { 17 | cow++; 18 | prevCow = v[i]; 19 | } 20 | if (cow >= cows) 21 | return true; 22 | } 23 | return false; 24 | } 25 | 26 | void solve() 27 | { 28 | int n, cows; 29 | cin >> n >> cows; 30 | vector dist(n); 31 | 32 | for (int i = 0; i < n; i++) 33 | { 34 | cin >> dist[i]; 35 | } 36 | 37 | sort(dist.begin(), dist.end()); 38 | int low = dist[0], high = dist[n - 1] - dist[0]; 39 | int res = -1; 40 | while (low <= high) 41 | { 42 | int mid = low + (high - low) / 2; 43 | if (isValidDistance(dist, cows, mid)) 44 | { 45 | res = mid; 46 | low = mid + 1; 47 | } 48 | else 49 | { 50 | high = mid - 1; 51 | } 52 | } 53 | cout << res << endl; 54 | } 55 | 56 | int main() 57 | { 58 | int t; 59 | cin >> t; 60 | while (t--) 61 | { 62 | solve(); 63 | } 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /BinarySearch/allocatebooks.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | InterviewBit Question Allocate Books 3 | https://www.interviewbit.com/problems/allocate-books/ 4 | */ 5 | 6 | bool isValid(vector &A, int B, int max) 7 | { 8 | int students = 1; 9 | int pages = 0; //Number of pages assigned to students 10 | for (auto page : A) 11 | { 12 | pages += page; //page is number of page for any book 13 | 14 | /*if the number of paegs assigned to a single student is more than the max 15 | then increase the number of students and also assign page to pages which 16 | caused increase in number of pages for previous student*/ 17 | if (pages > max) 18 | { 19 | students++; 20 | pages = page; 21 | } 22 | //if number of students is more than the number of students given in question 23 | if (students > B) 24 | return false; 25 | } 26 | //if everything goes alright 27 | return true; 28 | } 29 | 30 | int Solution::books(vector &A, int B) 31 | { 32 | if (A.size() < B) 33 | return -1; 34 | 35 | int low = INT_MIN, high = 0; 36 | for (auto x : A) 37 | { 38 | low = max(low, x); 39 | high += x; 40 | } 41 | 42 | int result = -1; 43 | while (low <= high) 44 | { 45 | int mid = low + (high - low) / 2; 46 | if (isValid(A, B, mid)) 47 | { 48 | result = mid; 49 | high = mid - 1; 50 | } 51 | else 52 | low = mid + 1; 53 | } 54 | return result; 55 | } 56 | -------------------------------------------------------------------------------- /BinarySearch/allocateminimumnumberofpages.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Allocate minimum number of pages 3 | https://practice.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(NlogN), Space: O(1) 10 | bool isValid(int A[], int N, int M, int mid) 11 | { 12 | int students = 1; 13 | int pages = 0; 14 | for (int i = 0; i < N; i++) 15 | { 16 | pages += A[i]; 17 | if (pages > mid) 18 | { 19 | students++; 20 | pages = A[i]; 21 | } 22 | if (students > M) 23 | return false; 24 | } 25 | return true; 26 | } 27 | 28 | int findPages(int A[], int N, int M) 29 | { 30 | if (N < M) 31 | return -1; 32 | int low = INT_MIN, high = 0; 33 | 34 | for (int i = 0; i < N; i++) 35 | { 36 | low = max(low, A[i]); 37 | high += A[i]; 38 | } 39 | 40 | int res = -1; 41 | while (low <= high) 42 | { 43 | int mid = low + (high - low) / 2; 44 | 45 | if (isValid(A, N, M, mid)) 46 | { 47 | res = mid; 48 | high = mid - 1; 49 | } 50 | else 51 | low = mid + 1; 52 | } 53 | return res; 54 | } 55 | }; -------------------------------------------------------------------------------- /BinarySearch/capacitytoshippackageswithinddays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1011. Capacity To Ship Packages Within D Days 3 | https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(NlogN), Space: O(1) 10 | int shipWithinDays(vector &weights, int days) 11 | { 12 | int low = 0, high = 0; 13 | for (auto w : weights) 14 | { 15 | low = max(low, w); 16 | high += w; 17 | } 18 | 19 | int result = -1; 20 | while (low <= high) 21 | { 22 | int mid = low + (high - low) / 2; 23 | 24 | if (isValid(weights, days, mid)) 25 | { 26 | result = mid; 27 | high = mid - 1; 28 | } 29 | else 30 | low = mid + 1; 31 | } 32 | return result; 33 | } 34 | 35 | bool isValid(vector &weights, int days, int max) 36 | { 37 | int day = 1; 38 | int totalWeights = 0; 39 | 40 | for (auto w : weights) 41 | { 42 | totalWeights += w; 43 | if (totalWeights > max) 44 | { 45 | day++; 46 | totalWeights = w; 47 | } 48 | 49 | if (day > days) 50 | return false; 51 | } 52 | return true; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /BinarySearch/checkifnanditsdoubleexist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1346. Check If N and Its Double Exist 3 | https://leetcode.com/problems/check-if-n-and-its-double-exist/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(nlogn + nlogn), Space: O(n) 10 | bool checkIfExist(vector &arr) 11 | { 12 | sort(arr.begin(), arr.end()); 13 | for (int i = 0; i < arr.size(); i++) 14 | { 15 | if (helper(arr, 2 * arr[i], i)) 16 | return true; 17 | } 18 | return false; 19 | } 20 | 21 | int helper(vector &arr, int target, int idx) 22 | { 23 | int low = 0, high = arr.size() - 1; 24 | 25 | while (low <= high) 26 | { 27 | int mid = low + (high - low) / 2; 28 | 29 | if (arr[mid] == target && idx != mid) 30 | return true; 31 | else if (target < arr[mid]) 32 | high = mid - 1; 33 | else 34 | low = mid + 1; 35 | } 36 | return false; 37 | } 38 | }; 39 | 40 | class Solution 41 | { 42 | public: 43 | //Time: O(n), Space: O(n) 44 | bool checkIfExist(vector &arr) 45 | { 46 | unordered_set s; 47 | for (auto x : arr) 48 | { 49 | if (s.find(2 * x) != s.end() || x % 2 == 0 && s.find(x / 2) != s.end()) 50 | return true; 51 | s.insert(x); 52 | } 53 | return false; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /BinarySearch/countrotationinsortedarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rotation 3 | https://practice.geeksforgeeks.org/problems/rotation4723/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(nlogn), Space: O(1) 10 | int findKRotation(int arr[], int n) 11 | { 12 | if (arr[0] < arr[n - 1]) 13 | return 0; 14 | int low = 0, high = n - 1; 15 | int result = 0; 16 | while (low <= high) 17 | { 18 | int mid = low + (high - low) / 2; 19 | int next = (mid + 1) % n; 20 | int prev = (mid + n - 1) % n; 21 | 22 | if (arr[mid] <= arr[next] && arr[mid] <= arr[prev]) 23 | return mid; 24 | else if (arr[mid] > arr[high]) 25 | low = mid + 1; 26 | else if (arr[mid] < arr[high]) 27 | high = mid - 1; 28 | } 29 | return result; 30 | //return INT_MAX; 31 | } 32 | }; -------------------------------------------------------------------------------- /BinarySearch/findfirstandlastpositionofelementinsortedarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 34. Find First and Last Position of Element in Sorted Array 3 | https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public 9 | //Time: O(logN) 10 | vector searchRange(vector &nums, int target) 11 | { 12 | return {findingIndex(nums, target, false), findingIndex(nums, target, true)}; 13 | } 14 | int findingIndex(vector &nums, int target, bool bound) 15 | { 16 | int low = 0, high = nums.size() - 1, result = -1; 17 | 18 | while (low <= high) 19 | { 20 | int mid = low + (high - low) / 2; 21 | 22 | if (nums[mid] == target) 23 | { 24 | result = mid; 25 | 26 | if (bound) 27 | low = mid + 1; 28 | else 29 | high = mid - 1; 30 | } 31 | 32 | else if (nums[mid] < target) 33 | low = mid + 1; 34 | else 35 | high = mid - 1; 36 | } 37 | 38 | return result; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /BinarySearch/findthesmallestdivisorgivenathreshold.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1283. Find the Smallest Divisor Given a Threshold 3 | https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(NlogN), Space: (N) 10 | int smallestDivisor(vector &nums, int threshold) 11 | { 12 | /* 13 | low is 1 atleast 1 will be there as a divisor so that it can divide all the element 14 | and high is maximum ele of nums arr, the reason for this is, if you will check you 15 | will find that the divisor greater than or equal to the max ele of arr will give 16 | result at size of the array. So, at the end high value will be the max of the arr 17 | ele 18 | */ 19 | int low = 1, high = 0; 20 | for (auto n : nums) 21 | high = max(high, n); 22 | 23 | int result = -1; 24 | while (low <= high) 25 | { 26 | int mid = low + (high - low) / 2; 27 | 28 | if (isValid(nums, threshold, mid)) 29 | { 30 | result = mid; 31 | high = mid - 1; 32 | } 33 | else 34 | low = mid + 1; 35 | } 36 | return result; 37 | } 38 | 39 | bool isValid(vector &nums, int threshold, int divisor) 40 | { 41 | int total = 0; 42 | for (auto n : nums) 43 | { 44 | total += (n % divisor) == 0 ? (n / divisor) : (n / divisor) + 1; 45 | } 46 | return total <= threshold; 47 | } 48 | }; -------------------------------------------------------------------------------- /BinarySearch/painterspartitionproblem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Interviewbit Question Painter's Partition Problem 3 | https://www.interviewbit.com/problems/painters-partition-problem/ 4 | */ 5 | 6 | bool isValid(vector &C, int max, int A) 7 | { 8 | int painters = 1; 9 | int boardLength = 0; 10 | 11 | for (auto c : C) 12 | { 13 | boardLength += c; 14 | if (boardLength > max) 15 | { 16 | boardLength = c; 17 | painters++; 18 | } 19 | if (painters > A) 20 | return false; 21 | } 22 | return true; 23 | } 24 | 25 | int Solution::paint(int A, int B, vector &C) 26 | { 27 | int low = 0, high = 0; 28 | for (auto c : C) 29 | { 30 | low = max(low, c); 31 | high += c; 32 | } 33 | 34 | int res = -1; 35 | while (low <= high) 36 | { 37 | int mid = low + (high - low) / 2; 38 | if (isValid(C, mid, A)) 39 | { 40 | res = mid; 41 | high = mid - 1; 42 | } 43 | else 44 | low = mid + 1; 45 | } 46 | return (int)((res * (long)B) % 10000003); 47 | } 48 | -------------------------------------------------------------------------------- /BinarySearch/searchinrotatedsortedarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 33. Search in Rotated Sorted Array 3 | https://leetcode.com/problems/search-in-rotated-sorted-array/ 4 | */ 5 | 6 | /* 7 | See, if the array is rotated, we need to think that one side of the array will be 8 | sorted. So, everytime the bounds are changing, we are checking that which side is 9 | sorted and based on that we are moving. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | // Time: O(logN), Space: O(1) 15 | int search(vector& nums, int target) { 16 | int low = 0, high = nums.size()-1; 17 | 18 | while(low <= high){ 19 | int mid = low + (high - low)/2; 20 | 21 | // if we get the element 22 | if(nums[mid] == target) return mid; 23 | 24 | // if left side is rotated 25 | if(nums[low] <= nums[mid]){ 26 | if(target >= nums[low] && target <= nums[mid]) high = mid-1; 27 | else low = mid+1; 28 | } 29 | // if the right side is rotated i.e. nums[mid] <= nums[high] 30 | else{ 31 | if(target >= nums[mid] && target <= nums[high]) low = mid+1; 32 | else high = mid-1; 33 | } 34 | } 35 | return -1; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /BinarySearch/thekweakestrowsinamatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1337. The K Weakest Rows in a Matrix 3 | https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(mlogn + mlogk), Space: O(k) 10 | vector kWeakestRows(vector > &mat, int k) 11 | { 12 | priority_queue > maxHeap; 13 | 14 | for (int i = 0; i < mat.size(); i++) 15 | { 16 | int count = findOnes(mat[i]); 17 | 18 | maxHeap.push({count, i}); 19 | if (maxHeap.size() > k) 20 | maxHeap.pop(); 21 | } 22 | 23 | vector result; 24 | while (maxHeap.size() > 0) 25 | { 26 | int x = maxHeap.top().second; 27 | maxHeap.pop(); 28 | result.push_back(x); 29 | } 30 | 31 | reverse(result.begin(), result.end()); 32 | return result; 33 | } 34 | 35 | int findOnes(vector &v) 36 | { 37 | if (v[0] == 0) 38 | return 0; 39 | 40 | int low = 0, high = v.size() - 1; 41 | int result = 0; 42 | while (low <= high) 43 | { 44 | int mid = (low + high) / 2; 45 | if (v[mid] == 1) 46 | { 47 | result = mid; 48 | low = mid + 1; 49 | } 50 | else 51 | high = mid - 1; 52 | } 53 | return result + 1; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /BinarySearch/validtrianglenumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 611. Valid Triangle Number 3 | https://leetcode.com/problems/valid-triangle-number/ 4 | */ 5 | 6 | //Brute Force 7 | class Solution 8 | { 9 | public: 10 | //Time: O(n^3), Space: O(1) 11 | int triangleNumber(vector &nums) 12 | { 13 | int count = 0; 14 | for (int i = 0; i < nums.size() - 2; i++) 15 | { 16 | for (int j = i + 1; j < nums.size() - 1; j++) 17 | { 18 | for (int k = j + 1; k < nums.size(); k++) 19 | { 20 | if ((nums[i] + nums[j] > nums[k]) && (nums[i] + nums[k] > nums[j]) && (nums[j] + nums[k] > nums[i])) 21 | count++; 22 | } 23 | } 24 | } 25 | return count; 26 | } 27 | }; 28 | 29 | //Efficient Approach 30 | class Solution 31 | { 32 | public: 33 | //Time: O(n^2) 34 | int triangleNumber(vector &nums) 35 | { 36 | sort(nums.begin(), nums.end()); 37 | int count = 0; 38 | for (int i = 2; i < nums.size(); i++) 39 | { 40 | int low = 0, high = i - 1; 41 | 42 | while (low < high) 43 | { 44 | if (nums[low] + nums[high] > nums[i]) 45 | { 46 | count += high - low; 47 | high--; 48 | } 49 | else 50 | low++; 51 | } 52 | } 53 | return count; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /BinarySearchTrees/binarytreetobst.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree to BST 3 | https://practice.geeksforgeeks.org/problems/binary-tree-to-bst/1# 4 | */ 5 | 6 | /* The Node structure is 7 | struct Node 8 | { 9 | int data; 10 | struct Node *left; 11 | struct Node *right; 12 | 13 | Node(int val) { 14 | data = val; 15 | left = right = NULL; 16 | } 17 | }; 18 | */ 19 | // The given root is the root of the Binary Tree 20 | // Return the root of the generated BST 21 | /*the basic idea is use level order traversal for binary 22 | tree and get the values in the vector and sort it, so we will 23 | have sorted values i.e. inorder form of bst and now create the 24 | bst. Time: O(NlogN), Space: O(N)*/ 25 | Node *createbst(vector &v, int low, int high) 26 | { 27 | if (low > high) 28 | { 29 | return NULL; 30 | } 31 | 32 | int mid = (low + high) / 2; 33 | Node *temp = new Node(v[mid]); 34 | temp->left = createbst(v, low, mid - 1); 35 | temp->right = createbst(v, mid + 1, high); 36 | return temp; 37 | } 38 | 39 | Node *binaryTreeToBST(Node *root) 40 | { 41 | //Your code goes here 42 | vector v; 43 | queue q; 44 | q.push(root); 45 | 46 | while (!q.empty()) 47 | { 48 | Node *temp = q.front(); 49 | q.pop(); 50 | v.push_back(temp->data); 51 | if (temp->left) 52 | q.push(temp->left); 53 | if (temp->right) 54 | q.push(temp->right); 55 | } 56 | sort(v.begin(), v.end()); 57 | int low = 0; 58 | int high = v.size() - 1; 59 | Node *bst = createbst(v, low, high); 60 | return bst; 61 | } -------------------------------------------------------------------------------- /BinarySearchTrees/brothersfromdifferentroots.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Brothers From Different Roots 3 | https://practice.geeksforgeeks.org/problems/brothers-from-different-root/1# 4 | */ 5 | 6 | /*Structure of the Node of the BST is as 7 | struct Node { 8 | int data; 9 | Node* left, *right; 10 | };*/ 11 | // You are required to complete this function 12 | /*the basic idea is take an inorder traversal of the bst 13 | and for every element in the first vector subtract that 14 | from the x and take the resultant and find in the other 15 | vector and if number is found then increase found value. 16 | Time: O(N), Space: O(N)*/ 17 | void inorder(Node *root, vector &v) 18 | { 19 | if (!root) 20 | return; 21 | inorder(root->left, v); 22 | v.push_back(root->data); 23 | inorder(root->right, v); 24 | } 25 | 26 | int countPairs(Node *root1, Node *root2, int x) 27 | { 28 | // Code here 29 | vector v1, v2; 30 | inorder(root1, v1); 31 | inorder(root2, v2); 32 | 33 | int found = 0; 34 | for (auto ele : v1) 35 | { 36 | int complement = x - ele; 37 | if (find(v2.begin(), v2.end(), complement) != v2.end()) 38 | { 39 | found++; 40 | } 41 | } 42 | return found; 43 | } -------------------------------------------------------------------------------- /BinarySearchTrees/convertsortedarraytobinarysearchtree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 108. Convert Sorted Array to Binary Search Tree 3 | https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*we have sorted array i.e. we have inorder traversal and its middle 21 | element is the root, and its left value is left subtree and right value 22 | is right subtree and and recursively call for this. 23 | Time: O(N), Space: O(N)*/ 24 | TreeNode *sortedArrayToBST(vector &nums) 25 | { 26 | 27 | int low = 0; 28 | int high = nums.size() - 1; 29 | 30 | TreeNode *root = helper(nums, low, high); 31 | return root; 32 | } 33 | 34 | TreeNode *helper(vector &nums, int low, int high) 35 | { 36 | if (low > high) 37 | return NULL; 38 | 39 | int mid = (low + high) / 2; 40 | 41 | TreeNode *temp = new TreeNode(nums[mid]); 42 | temp->left = helper(nums, low, mid - 1); 43 | temp->right = helper(nums, mid + 1, high); 44 | 45 | return temp; 46 | } 47 | }; -------------------------------------------------------------------------------- /BinarySearchTrees/insertintoabinarysearchtree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 701. Insert into a Binary Search Tree 3 | https://leetcode.com/problems/insert-into-a-binary-search-tree/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | // Time: O(H) 21 | TreeNode *insertIntoBST(TreeNode *root, int val) 22 | { 23 | if (!root) 24 | { 25 | return new TreeNode(val); 26 | } 27 | if (val < root->val) 28 | { 29 | root->left = insertIntoBST(root->left, val); 30 | } 31 | else if (val > root->val) 32 | { 33 | root->right = insertIntoBST(root->right, val); 34 | } 35 | return root; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /BinarySearchTrees/kthsmallestelementinabst.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 230. Kth Smallest Element in a BST 3 | https://leetcode.com/problems/kth-smallest-element-in-a-bst/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is to traverse the tree in Inorder fashion, 21 | and push the values in result vector till it's size is <= k, 22 | and return the k-1. Time: O(N), Space: O(N)*/ 23 | vector result; 24 | void inOrder(TreeNode *root, int k) 25 | { 26 | if (!root) 27 | return; 28 | inOrder(root->left, k); 29 | if (result.size() <= k) 30 | result.push_back(root->val); 31 | else 32 | return; 33 | inOrder(root->right, k); 34 | } 35 | int kthSmallest(TreeNode *root, int k) 36 | { 37 | inOrder(root, k); 38 | return result[k - 1]; 39 | } 40 | }; -------------------------------------------------------------------------------- /BinarySearchTrees/leafatsamelevel.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leaf at same level 3 | https://practice.geeksforgeeks.org/problems/leaf-at-same-level/1# 4 | */ 5 | 6 | /* The structure of the binary tree is as follows 7 | struct Node 8 | { 9 | int data; 10 | Node* left; 11 | Node* right; 12 | }; 13 | */ 14 | /*the basic idea is traverse every level and count for 15 | left and right subtree and compare them. Time: O(N) 16 | Space: O(h)*/ 17 | bool leaflevels(Node *root, int *level, int currentLevel) 18 | { 19 | if (root == NULL) 20 | return true; 21 | 22 | /*if we encountered the leaf node*/ 23 | if (root->left == NULL && root->right == NULL) 24 | { 25 | if (*level == 0) 26 | { 27 | *level = currentLevel; 28 | return true; 29 | } 30 | else 31 | { 32 | /*this is when we will be having the level value*/ 33 | return (*level == currentLevel); 34 | } 35 | } 36 | 37 | return (leaflevels(root->left, level, currentLevel + 1) && 38 | leaflevels(root->right, level, currentLevel + 1)); 39 | } 40 | /*You are required to complete this method*/ 41 | bool check(Node *root) 42 | { 43 | //Your code here 44 | int level = 0, currentLevel = 0; 45 | return leaflevels(root, &level, currentLevel); 46 | } 47 | -------------------------------------------------------------------------------- /BinarySearchTrees/preordertopostorder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Preorder to Postorder 3 | https://practice.geeksforgeeks.org/problems/preorder-to-postorder4423/1# 4 | */ 5 | 6 | // pre : given preorder if the tree 7 | // size : size of the array 8 | // print postorder traveresal of the tree 9 | /*the basic idea is to create a binary search tree from 10 | preorder traversal. Time: O(N), Space: O(N)*/ 11 | Node *constructTreeUtil(int pre[], int start, int end) 12 | { 13 | if (start > end) 14 | return NULL; 15 | 16 | Node *root = newNode(pre[start]); 17 | 18 | /*traverse through the array untill you 19 | finish the left subtree part, and then call recursively 20 | for left and right subtree*/ 21 | int i; 22 | for (i = start; i <= end; i++) 23 | { 24 | if (pre[i] > root->data) 25 | { 26 | break; 27 | } 28 | } 29 | 30 | root->left = constructTreeUtil(pre, start + 1, i - 1); 31 | root->right = constructTreeUtil(pre, i, end); 32 | return root; 33 | } 34 | 35 | Node *constructTree(int pre[], int size) 36 | { 37 | //code here 38 | return constructTreeUtil(pre, 0, size - 1); 39 | } 40 | -------------------------------------------------------------------------------- /BinarySearchTrees/rangesumofbst.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 938. Range Sum of BST 3 | https://leetcode.com/problems/range-sum-of-bst/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is take a inorder traversal and store the values in 21 | vector, find the low and high index and start the loop and add all those 22 | values within this range. Time: O(N), Space: O(N)*/ 23 | void inorder(TreeNode *root, vector &v) 24 | { 25 | if (!root) 26 | return; 27 | inorder(root->left, v); 28 | v.push_back(root->val); 29 | inorder(root->right, v); 30 | } 31 | int rangeSumBST(TreeNode *root, int low, int high) 32 | { 33 | vector v; 34 | inorder(root, v); 35 | 36 | auto lowIt = find(v.begin(), v.end(), low); 37 | int lowIdx = lowIt - v.begin(); 38 | 39 | auto highIt = find(v.begin(), v.end(), high); 40 | int highIdx = highIt - v.begin(); 41 | 42 | int sum = 0; 43 | for (int i = lowIdx; i <= highIdx; i++) 44 | { 45 | sum += v[i]; 46 | } 47 | return sum; 48 | } 49 | }; -------------------------------------------------------------------------------- /BinarySearchTrees/searchinabinarytree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 700. Search in a Binary Search Tree 3 | https://leetcode.com/problems/search-in-a-binary-search-tree/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*this is a standard problem. Time: O(h)*/ 21 | TreeNode *searchBST(TreeNode *root, int val) 22 | { 23 | if (root == NULL || root->val == val) 24 | return root; 25 | if (val > root->val) 26 | return searchBST(root->right, val); 27 | return searchBST(root->left, val); 28 | } 29 | }; -------------------------------------------------------------------------------- /BinarySearchTrees/validatebinarysearchtree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 98. Validate Binary Search Tree 3 | https://leetcode.com/problems/validate-binary-search-tree/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is to traverse the tree and go to the node once, 21 | keeping track of each node and check that each node's val is more than 22 | min value and less than max value. Time: O(N), Space: O(h)*/ 23 | bool isValidBST(TreeNode *root) 24 | { 25 | 26 | /*initial values of min = LONG_MIN, max = LONG_MAX*/ 27 | return utilBST(root, LONG_MIN, LONG_MAX); 28 | } 29 | 30 | int utilBST(TreeNode *root, long min, long max) 31 | { 32 | 33 | //this is also a valid bst 34 | if (!root) 35 | return 1; 36 | 37 | /*if this happens then binary tree is not a valid bst*/ 38 | if (root->val <= min || root->val >= max) 39 | return 0; 40 | 41 | return utilBST(root->left, min, root->val) && 42 | utilBST(root->right, root->val, max); 43 | } 44 | }; -------------------------------------------------------------------------------- /BinaryTrees/balancedbinarytree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 110. Balanced Binary Tree 3 | https://leetcode.com/problems/balanced-binary-tree/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is to check the left subtree is balanced, 21 | right subtree is balanced and the difference between heights 22 | of left and right subtree is <= 1. Time: O(N)*/ 23 | bool isBalanced(TreeNode *root) 24 | { 25 | if (!root) 26 | return 1; 27 | 28 | int lh = getheight(root->left); 29 | int rh = getheight(root->right); 30 | 31 | return (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)); 32 | } 33 | 34 | int getheight(TreeNode *root) 35 | { 36 | if (!root) 37 | return 0; 38 | int lh = getheight(root->left); 39 | int rh = getheight(root->right); 40 | 41 | return (1 + max(lh, rh)); 42 | } 43 | }; -------------------------------------------------------------------------------- /BinaryTrees/binarytreemaximumpathsum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 124. Binary Tree Maximum Path Sum 3 | https://leetcode.com/problems/binary-tree-maximum-path-sum/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | //Time: O(N) 21 | int maxPathSum(TreeNode *root) 22 | { 23 | int maxPath = INT_MIN; 24 | helper(root, maxPath); 25 | return maxPath; 26 | } 27 | 28 | int helper(TreeNode *root, int &maxPath) 29 | { 30 | if (!root) 31 | return 0; 32 | 33 | int left = helper(root->left, maxPath); 34 | int right = helper(root->right, maxPath); 35 | 36 | //find the maximum sum through the root node 37 | int temp = max(max(left, right) + root->val, root->val); 38 | 39 | //find the maximum sum through the path irrespective of the root node 40 | int ans = max(temp, left + right + root->val); 41 | 42 | //since we will be having the maximum sum stored in ans and now we only have to 43 | //compare with our final answer 44 | maxPath = max(maxPath, ans); 45 | return temp; 46 | } 47 | }; -------------------------------------------------------------------------------- /BinaryTrees/binarytreepaths.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 257. Binary Tree Paths 3 | https://leetcode.com/problems/binary-tree-paths/ 4 | */ 5 | 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 | 18 | /* 19 | The idea is simple, traverse the tree and when you reach the leaf node push the path into the 20 | resultant vector. 21 | */ 22 | class Solution 23 | { 24 | public: 25 | //Time: O(N), Space: O(N) 26 | vector binaryTreePaths(TreeNode *root) 27 | { 28 | vector result; 29 | string curr = ""; 30 | helper(root, result, curr); 31 | return result; 32 | } 33 | 34 | void helper(TreeNode *root, vector &result, string curr) 35 | { 36 | if (!root) 37 | return; //base case 38 | 39 | curr += to_string(root->val); 40 | 41 | //if the node is a leaf node then we are done with that path, we can just push that 42 | //path into result vector; 43 | if (!root->left && !root->right) 44 | result.push_back(curr); 45 | 46 | //recursion call for left and right subtree 47 | helper(root->left, result, curr + "->"); 48 | helper(root->right, result, curr + "->"); 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /BinaryTrees/binarytreerightsideview.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 199. Binary Tree Right Side View 3 | https://leetcode.com/problems/binary-tree-right-side-view/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is follow the level order traversal 21 | and observe it, we are pushing those value to the result 22 | which will be at the end of inner while loop. 23 | Time: O(N), Space:O(N)*/ 24 | vector rightSideView(TreeNode *root) 25 | { 26 | vector result; 27 | if (!root) 28 | { 29 | return result; 30 | } 31 | 32 | queue q; 33 | q.push(root); 34 | 35 | while (!q.empty()) 36 | { 37 | TreeNode *node; 38 | int size = q.size(); 39 | while (size--) 40 | { 41 | node = q.front(); 42 | q.pop(); 43 | if (node->left) 44 | q.push(node->left); 45 | if (node->right) 46 | q.push(node->right); 47 | } 48 | result.push_back(node->val); 49 | } 50 | return result; 51 | } 52 | }; -------------------------------------------------------------------------------- /BinaryTrees/constructstringfrombinarytree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 606. Construct String from Binary Tree 3 | https://leetcode.com/problems/construct-string-from-binary-tree/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is to follow the preorder traversal of a binary tree 21 | and just follow the question. Time: O(N), Space: O(N)*/ 22 | string tree2str(TreeNode *t) 23 | { 24 | if (!t) 25 | return ""; 26 | 27 | string s = to_string(t->val); 28 | 29 | if (t->left) 30 | { 31 | s += '(' + tree2str(t->left) + ')'; 32 | } 33 | else if (t->right) 34 | s += "()"; 35 | 36 | if (t->right) 37 | { 38 | s += '(' + tree2str(t->right) + ')'; 39 | } 40 | return s; 41 | } 42 | }; -------------------------------------------------------------------------------- /BinaryTrees/invertbinarytree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 226. Invert Binary Tree 3 | https://leetcode.com/problems/invert-binary-tree/ 4 | */ 5 | 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 | //Solution 1 18 | class Solution 19 | { 20 | public: 21 | /*the basic idea is to call for the left and right 22 | subtrees and swap the pointers. Time: O(N), Space: O(N)*/ 23 | TreeNode *invertTree(TreeNode *root) 24 | { 25 | if (!root) 26 | return NULL; 27 | 28 | TreeNode *right = root->right; 29 | 30 | root->right = invertTree(root->left); 31 | root->left = invertTree(right); 32 | 33 | return root; 34 | } 35 | }; 36 | 37 | //Solution 2 38 | class Solution 39 | { 40 | public: 41 | /*the basic idea is to call for the left and right 42 | subtrees and swap the pointers. Time: O(N), Space: O(N)*/ 43 | TreeNode *invertTree(TreeNode *root) 44 | { 45 | if (!root) 46 | return NULL; 47 | 48 | TreeNode *right = invertTree(root->right); 49 | TreeNode *left = invertTree(root->left); 50 | root->left = right; 51 | root->right = left; 52 | 53 | return root; 54 | } 55 | }; -------------------------------------------------------------------------------- /BinaryTrees/lowestcommonancestorofbst.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 235. Lowest Common Ancestor of a Binary Search Tree 3 | https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | 16 | class Solution 17 | { 18 | public: 19 | TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) 20 | { 21 | if (!root) 22 | return NULL; 23 | 24 | if (root->val > p->val && root->val > q->val) 25 | return lowestCommonAncestor(root->left, p, q); 26 | 27 | if (root->val < p->val && root->val < q->val) 28 | return lowestCommonAncestor(root->right, p, q); 29 | 30 | return root; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /BinaryTrees/maximumdepthofn-arytree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 559. Maximum Depth of N-ary Tree 3 | https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ 4 | */ 5 | 6 | /* 7 | // Definition for a Node. 8 | class Node { 9 | public: 10 | int val; 11 | vector children; 12 | 13 | Node() {} 14 | 15 | Node(int _val) { 16 | val = _val; 17 | } 18 | 19 | Node(int _val, vector _children) { 20 | val = _val; 21 | children = _children; 22 | } 23 | }; 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | int maxDepth(Node *root) 30 | { 31 | //base case 32 | if (!root) 33 | return 0; 34 | 35 | //check for all children and find the maximum depth 36 | int maxdepth = 0; 37 | vector::iterator itr; 38 | for (itr = root->children.begin(); itr != root->children.end(); itr++) 39 | { 40 | maxdepth = max(maxdepth, maxDepth(*itr)); 41 | } 42 | return maxdepth + 1; 43 | } 44 | }; -------------------------------------------------------------------------------- /BinaryTrees/mergetwobinarytrees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 617. Merge Two Binary Trees 3 | https://leetcode.com/problems/merge-two-binary-trees/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is to traverse the tree and when both nodes exist, 21 | add them and create a node, if one doesn't exist return the other one 22 | call for left and right subtree recursively, here we have to reutrn a new 23 | tree which will be the merged of the both the tree. Time: O(N), Space: O(N)*/ 24 | TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) 25 | { 26 | 27 | if (!root1) 28 | return root2; 29 | if (!root2) 30 | return root1; 31 | 32 | TreeNode *mergedTree = new TreeNode(root1->val + root2->val); 33 | mergedTree->left = mergeTrees(root1->left, root2->left); 34 | mergedTree->right = mergeTrees(root1->right, root2->right); 35 | 36 | return mergedTree; 37 | } 38 | }; -------------------------------------------------------------------------------- /BinaryTrees/pathsum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 112. Path Sum 3 | https://leetcode.com/problems/path-sum/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*the basic idea is to traverse every single path and 21 | check whether the path sum is equal to the sum or not. 22 | Time: O(N), Space: O(N)*/ 23 | bool hasPathSum(TreeNode *root, int sum) 24 | { 25 | 26 | return FindPathSum(root, sum, 0); 27 | } 28 | 29 | bool FindPathSum(TreeNode *root, int sum, int pathsum) 30 | { 31 | if (!root) 32 | return false; 33 | 34 | //adding to the pathsum 35 | pathsum += root->val; 36 | 37 | /* this is will be true if the node will be the 38 | leaf node, then compare it and return the result*/ 39 | if (!root->left && !root->right) 40 | { 41 | return pathsum == sum; 42 | } 43 | 44 | /*traversing for left and right subtree*/ 45 | return ( 46 | FindPathSum(root->left, sum, pathsum) || 47 | FindPathSum(root->right, sum, pathsum)); 48 | } 49 | }; -------------------------------------------------------------------------------- /BinaryTrees/pathsumii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 113. Path Sum II 3 | https://leetcode.com/problems/path-sum-ii/ 4 | */ 5 | 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 Solution 18 | { 19 | public: 20 | /*this is a simple preorder traversal and traverse every single path 21 | Time: O(N), Space: O(H)*/ 22 | vector > result; 23 | vector > pathSum(TreeNode *root, int sum) 24 | { 25 | vector path; 26 | helper(root, sum, 0, path); 27 | return result; 28 | } 29 | 30 | void helper(TreeNode *root, int sum, int pathsum, vector &path) 31 | { 32 | if (!root) 33 | return; 34 | 35 | pathsum += root->val; 36 | path.push_back(root->val); 37 | 38 | //checking if the root is leaf node 39 | if (!root->left && !root->right) 40 | { 41 | 42 | //then check for sum 43 | if (pathsum == sum) 44 | result.push_back(path); 45 | path.pop_back(); 46 | return; 47 | } 48 | 49 | helper(root->left, sum, pathsum, path); 50 | helper(root->right, sum, pathsum, path); 51 | path.pop_back(); 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /BitManipulation/numberof1bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 191. Number of 1 Bits 3 | https://leetcode.com/problems/number-of-1-bits/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int hammingWeight(uint32_t n) 10 | { 11 | int count = 0; 12 | 13 | while (n){ 14 | n = n & (n - 1); 15 | count++; 16 | } 17 | return count; 18 | } 19 | }; -------------------------------------------------------------------------------- /BitManipulation/powerof2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 231. Power of Two 3 | https://leetcode.com/problems/power-of-two/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | bool isPowerOfTwo(int n) 10 | { 11 | 12 | if (n <= 0) 13 | return 0; 14 | return (n & (n - 1)) ? false : true; 15 | //return (n && !(n & n-1)); //first n is for the corner case when n is 0 16 | } 17 | }; -------------------------------------------------------------------------------- /BitManipulation/reversebits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 190. Reverse Bits 3 | https://leetcode.com/problems/reverse-bits/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | uint32_t reverseBits(uint32_t n) 10 | { 11 | int ans = 0; 12 | 13 | for (int i = 0; i < 32; i++) 14 | { 15 | ans = ans << 1; 16 | ans = ans | (n & 1); 17 | n = n >> 1; 18 | } 19 | 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /BitManipulation/singlenumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 136. Single Number 3 | https://leetcode.com/problems/single-number/ 4 | */ 5 | 6 | //Solution 1 7 | class Solution 8 | { 9 | public: 10 | int singleNumber(vector &nums) 11 | { 12 | 13 | 14 | //O(n) 15 | map mp; 16 | for(int i=0; isecond == 1) 22 | return i->first; 23 | } 24 | return 0; 25 | } 26 | }; 27 | 28 | //Solution 2 29 | class Solution 30 | { 31 | public: 32 | //Time: O(n) 33 | int singleNumber(vector &nums) 34 | { 35 | int xorsum = 0; 36 | for (int i = 0; i < nums.size(); i++) 37 | { 38 | xorsum = xorsum ^ nums[i]; 39 | } 40 | return xorsum; 41 | } 42 | }; -------------------------------------------------------------------------------- /BitManipulation/singlenumberiii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 260. Single Number III 3 | https://leetcode.com/problems/single-number-iii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int getBit(int n, int pos) 10 | { 11 | return ((n & (1 << pos)) != 0); 12 | } 13 | 14 | vector singleNumber(vector &nums) 15 | { 16 | int xorsum = 0; 17 | 18 | for (int i = 0; i < nums.size(); i++) 19 | { 20 | xorsum = xorsum ^ nums[i]; 21 | } 22 | 23 | int tempxor = xorsum; 24 | int pos = 0, setbit = 0; 25 | while (setbit != 1) 26 | { 27 | setbit = xorsum & 1; 28 | pos++; 29 | xorsum = xorsum >> 1; //getting the next bit 30 | } 31 | 32 | int newxor = 0; 33 | for (int i = 0; i < nums.size(); i++) 34 | { 35 | if (getBit(nums[i], pos - 1)) 36 | { 37 | newxor = newxor ^ nums[i]; 38 | } 39 | } 40 | vector result; 41 | result.push_back(newxor); 42 | result.push_back((tempxor ^ newxor)); 43 | 44 | return result; 45 | } 46 | }; -------------------------------------------------------------------------------- /DynamicProgramming/besttimetobuysellstock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 121. Best Time to Buy and Sell Stock 3 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 4 | */ 5 | 6 | /* 7 | we have given the prices of a stock at each day, Now we have to decide when we will buy and 8 | when we will sell the stock inorder to maximize the profit. The process is very simple... 9 | 1. Buy the stock only the day when you see minimum price then the previous day. 10 | 2. When the price is more than the price on previous day then sell the stock and find the 11 | maximum profit. 12 | */ 13 | class Solution 14 | { 15 | public: 16 | //Time: O(N), Space: O(1) 17 | int maxProfit(vector &prices) 18 | { 19 | int maxProfit = 0; 20 | int buyStockPrice = INT_MAX; 21 | for (int i = 0; i < prices.size(); i++) 22 | { 23 | //first buy the stock 24 | if (prices[i] < buyStockPrice) 25 | buyStockPrice = prices[i]; 26 | //sell the stock with maximum profit 27 | else if (prices[i] - buyStockPrice > maxProfit) 28 | maxProfit = prices[i] - buyStockPrice; 29 | } 30 | return maxProfit; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /DynamicProgramming/besttimetobuysellstockii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 122. Best Time to Buy and Sell Stock II 3 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 4 | */ 5 | 6 | /* 7 | The question says we can have an infinite transaction and also we can buy one stock at a 8 | time and sell at a time. Scenario could be :- Buy, Sell, Buy, Sell. No overlap transactions. 9 | We are checking the if the current value is more than the previous value or not, i.e. if the 10 | stock price goes up then move the selling date but if the stock price goes down then just 11 | before moving there calculate the profit and move. 12 | */ 13 | class Solution 14 | { 15 | public: 16 | //Time: O(N), Space: O(N) 17 | int maxProfit(vector &prices) 18 | { 19 | int buyDate = 0, sellDate = 0, maxProfit = 0; 20 | for (int i = 1; i < prices.size(); i++) 21 | { 22 | //if stock price goes up 23 | if (prices[i] > prices[i - 1]) 24 | { 25 | sellDate++; 26 | } 27 | else 28 | { 29 | //but if it goes down, calculate the profit and then move to that date 30 | maxProfit += prices[sellDate] - prices[buyDate]; 31 | sellDate = buyDate = i; 32 | } 33 | } 34 | maxProfit += prices[sellDate] - prices[buyDate]; 35 | return maxProfit; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /DynamicProgramming/cherrypickupii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1463. Cherry Pickup II 3 | https://leetcode.com/problems/cherry-pickup-ii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(m*n^2) 10 | vector>> memo; 11 | int cherryPickupImpl(vector> &grid, int x, int y1, int y2) 12 | { 13 | 14 | if (y1 < 0 || y1 >= grid[0].size() || y1 < 0 || y2 >= grid[0].size()) 15 | return 0; 16 | 17 | if (memo[x][y1][y2] != -1) 18 | return memo[x][y1][y2]; 19 | 20 | int sum = 0; 21 | if (y1 != y2) 22 | { 23 | sum += grid[x][y1] + grid[x][y2]; 24 | } 25 | else 26 | { 27 | sum += grid[x][y1]; 28 | } 29 | 30 | if (x != grid.size() - 1) 31 | { 32 | int localMax = 0; 33 | for (int tempY1 = y1 - 1; tempY1 <= y1 + 1; tempY1++) 34 | { 35 | for (int tempY2 = y2 - 1; tempY2 <= y2 + 1; tempY2++) 36 | { 37 | localMax = max(localMax, 38 | cherryPickupImpl(grid, x + 1, tempY1, tempY2)); 39 | } 40 | } 41 | sum += localMax; 42 | } 43 | return memo[x][y1][y2] = sum; 44 | } 45 | 46 | int cherryPickup(vector> &grid) 47 | { 48 | int m = grid.size(); 49 | int n = grid[0].size(); 50 | memo.resize(m, vector>(n, vector(n, -1))); 51 | return cherryPickupImpl(grid, 0, 0, n - 1); 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /DynamicProgramming/largestdivisiblesubset.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 368. Largest Divisible Subset 3 | https://leetcode.com/problems/largest-divisible-subset/ 4 | */ 5 | 6 | /* 7 | This is a 3 step solution. This is a variation of LIS 8 | 1. Sort the array 9 | 2. Get the LIS till every index. 10 | 3. Find the subset 11 | */ 12 | 13 | class Solution 14 | { 15 | public: 16 | // Time: O(NlogN + N^2 + N), Space: O(N + length of subset) 17 | vector largestDivisibleSubset(vector &nums) 18 | { 19 | int n = nums.size(); 20 | sort(nums.begin(), nums.end()); //Step 1 21 | 22 | vector dp(n, 1); 23 | int res = 1; // shows the length of the LIS 24 | for (int i = 0; i < n; i++) //Step 2 25 | { 26 | for (int j = 0; j < i; j++) 27 | { 28 | if (nums[i] % nums[j] == 0) 29 | { 30 | dp[i] = max(dp[i], dp[j] + 1); 31 | } 32 | res = max(res, dp[i]); 33 | } 34 | } 35 | 36 | int prevElement = -1; 37 | vector subset; //Step 3 38 | for (int i = n - 1; i >= 0; i--) 39 | { 40 | if (res == dp[i] && (prevElement == -1 || prevElement % nums[i] == 0)) 41 | { 42 | subset.push_back(nums[i]); 43 | res--; 44 | prevElement = nums[i]; 45 | } 46 | } 47 | return subset; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /DynamicProgramming/longestcommonsubstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Common Substring 3 | https://practice.geeksforgeeks.org/problems/longest-common-substring1452/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*Time: O(m*n), Space: O(m*n)*/ 10 | int longestCommonSubstr(string S1, string S2, int n, int m) 11 | { 12 | int result = 0; 13 | vector > dp(n + 1, vector(m + 1)); 14 | 15 | //initialization 16 | for (int i = 0; i < n + 1; i++) 17 | { 18 | for (int j = 0; j < m + 1; j++) 19 | { 20 | if (i == 0 || j == 0) 21 | dp[i][j] = 0; 22 | } 23 | } 24 | 25 | //solving the subproblems 26 | for (int i = 1; i < n + 1; i++) 27 | { 28 | for (int j = 1; j < m + 1; j++) 29 | { 30 | if (S1[i - 1] == S2[j - 1]) 31 | { 32 | dp[i][j] = 1 + dp[i - 1][j - 1]; 33 | } 34 | else 35 | { 36 | dp[i][j] = 0; 37 | } 38 | // this could be done in separate array but we are doing in 39 | // same loop 40 | // since we want the longest string 41 | result = max(result, dp[i][j]); 42 | } 43 | } 44 | return result; 45 | } 46 | }; -------------------------------------------------------------------------------- /DynamicProgramming/longestrepeatingsubsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Repeating Subsequence 3 | https://practice.geeksforgeeks.org/problems/longest-repeating-subsequence2004/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is, this problem can be reduced to the problem 10 | of LCS and but the only requirement is that the two subsequence 11 | don’t have same string character at same position, except this 12 | everything is same. It can be done using Memoization also 13 | Time: O(m*n), Space: O(m*n)*/ 14 | int LongestRepeatingSubsequence(string str) 15 | { 16 | string X = str; 17 | string Y = str; 18 | int m = str.size(); 19 | int n = m; 20 | vector > dp(m + 1, vector(n + 1)); 21 | 22 | //intializing 23 | for (int i = 0; i < m + 1; i++) 24 | { 25 | for (int j = 0; j < n + 1; j++) 26 | { 27 | if (i == 0 || j == 0) 28 | dp[i][j] = 0; 29 | } 30 | } 31 | 32 | //solving the subproblems 33 | for (int i = 1; i < m + 1; i++) 34 | { 35 | for (int j = 1; j < n + 1; j++) 36 | { 37 | if (X[i - 1] == Y[j - 1] && i != j) 38 | dp[i][j] = 1 + dp[i - 1][j - 1]; 39 | else 40 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 41 | } 42 | } 43 | return dp[m][n]; 44 | } 45 | }; -------------------------------------------------------------------------------- /DynamicProgramming/maximumlengthofpairchain.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 646. Maximum Length of Pair Chain 3 | https://leetcode.com/problems/maximum-length-of-pair-chain/ 4 | */ 5 | 6 | //Another problem similar to LIS 7 | class Solution 8 | { 9 | public: 10 | //Time: O(NlogN + N^2), Space: O(N) 11 | int findLongestChain(vector > &pairs) 12 | { 13 | int n = pairs.size(); 14 | vector dp(n, 1); 15 | int result = 1; 16 | sort(pairs.begin(), pairs.end()); 17 | for (int i = 0; i < n; i++) 18 | { 19 | for (int j = 0; j < i; j++) 20 | { 21 | if (pairs[j][1] < pairs[i][0]) 22 | { 23 | dp[i] = max(dp[i], dp[j] + 1); 24 | } 25 | result = max(result, dp[i]); 26 | } 27 | } 28 | return result; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /DynamicProgramming/minimuminsertionstomakeastringpalindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1312. Minimum Insertion Steps to Make a String Palindrome 3 | https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*Since this question is same as the deletion in place of insertion, if we 10 | observe the question carefully, you will find that min. no. of insertion == 11 | min. no. of deletion to make a string palindrome. So, we have to use the 12 | same code. Time: O(m*n), Space: O(m*n)*/ 13 | int minInsertions(string s) 14 | { 15 | string X = s; 16 | string Y = s; 17 | reverse(Y.begin(), Y.end()); 18 | int m = s.length(); 19 | int n = m; 20 | vector > dp(m + 1, vector(n + 1, -1)); 21 | int insertion = m - longestPalindormeSubsq(X, Y, m, n, dp); 22 | return insertion; 23 | } 24 | 25 | int longestPalindormeSubsq(string &X, string &Y, int m, int n, vector > &dp) 26 | { 27 | if (m == 0 || n == 0) 28 | return 0; 29 | if (dp[m][n] != -1) 30 | return dp[m][n]; 31 | 32 | if (X[m - 1] == Y[n - 1]) 33 | return dp[m][n] = 1 + longestPalindormeSubsq(X, Y, m - 1, n - 1, dp); 34 | else 35 | return dp[m][n] = max( 36 | longestPalindormeSubsq(X, Y, m - 1, n, dp), 37 | longestPalindormeSubsq(X, Y, m, n - 1, dp) 38 | ); 39 | } 40 | }; -------------------------------------------------------------------------------- /DynamicProgramming/minimumnumberofdeletionsandinsertions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum number of deletions and insertions. 3 | https://practice.geeksforgeeks.org/problems/minimum-number-of-deletions-and-insertions0209/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is to find the lcs from both the strings and then 10 | for deletion_count subtract from str1 length and for insertion_count 11 | subtract from str2 length and atlast add insertion and deletion 12 | Time: O(m*n), Space: O(m*n)*/ 13 | int lcs(string &str1, string &str2, int m, int n, vector > &dp) 14 | { 15 | if (m == 0 || n == 0) 16 | return 0; 17 | 18 | if (dp[m][n] != -1) 19 | return dp[m][n]; 20 | 21 | if (str1[m - 1] == str2[n - 1]) 22 | return dp[m][n] = 1 + lcs(str1, str2, m - 1, n - 1, dp); 23 | else 24 | return dp[m][n] = max(lcs(str1, str2, m - 1, n, dp), lcs(str1, str2, m, n - 1, dp)); 25 | } 26 | 27 | int minOperations(string str1, string str2) 28 | { 29 | //length of the strings 30 | int m = str1.size(); 31 | int n = str2.size(); 32 | 33 | //using memoization and initialized wiht -1 34 | vector > dp(m + 1, vector(n + 1, -1)); 35 | 36 | /*make sure to pass the string pass by reference not by value 37 | because everytime we pass different local string to the function*/ 38 | int deletion = m - lcs(str1, str2, m, n, dp); 39 | int insertion = n - lcs(str1, str2, m, n, dp); 40 | 41 | //atlast add the insertion and deletion 42 | return insertion + deletion; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /DynamicProgramming/minimumnumberofdeletionsinastringtomakeitapalindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum number of deletions. 3 | https://practice.geeksforgeeks.org/problems/minimum-number-of-deletions4610/1# 4 | */ 5 | 6 | /*the basic idea is if we observe the question carefully we can reduce 7 | it to the LCS problem, basicallu if you make a copy of str and reverse 8 | it and try to find the LCS from both strings and then subtract LCS length 9 | from the length of the str, we will get the answer. Time: O(m*n) 10 | Space: O(m*n)*/ 11 | int lcs(string &X, string &Y, int m, int n, vector > &dp) 12 | { 13 | if (m == 0 || n == 0) 14 | return 0; 15 | if (dp[m][n] != -1) 16 | return dp[m][n]; 17 | 18 | if (X[m - 1] == Y[n - 1]) 19 | return dp[m][n] = 1 + lcs(X, Y, m - 1, n - 1, dp); 20 | else 21 | return dp[m][n] = max(lcs(X, Y, m - 1, n, dp), lcs(X, Y, m, n - 1, dp)); 22 | } 23 | 24 | int minDeletions(string str, int n) 25 | { 26 | //complete the function here 27 | string X = str; 28 | string Y = str; 29 | //reverse the one string 30 | reverse(Y.begin(), Y.end()); 31 | 32 | int m = n; 33 | //initializing the matrix 34 | vector > dp(m + 1, vector(n + 1, -1)); 35 | int deletions = m - lcs(X, Y, m, n, dp); 36 | return deletions; 37 | } -------------------------------------------------------------------------------- /Graph/allpathfromsourcetotarget.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 797. All Paths From Source to Target 3 | https://leetcode.com/problems/all-paths-from-source-to-target/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(2^n), Space: O(n) 10 | vector > result; 11 | vector > allPathsSourceTarget(vector > &graph) 12 | { 13 | int source = 0; 14 | int size = graph.size() - 1; 15 | vector path; 16 | dfs(graph, source, size, path); 17 | return result; 18 | } 19 | 20 | void dfs(vector > &graph, int source, int size, vector &path) 21 | { 22 | 23 | // add the node to the path 24 | path.push_back(source); 25 | 26 | // base case 27 | if (source == size) 28 | { 29 | result.push_back(path); 30 | return; 31 | } 32 | 33 | for (auto v : graph[source]) 34 | { 35 | dfs(graph, v, size, path); 36 | /*pop here because you need to start from another 37 | edge in order to reach target*/ 38 | path.pop_back(); 39 | } 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Graph/bfs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | BFS of graph 3 | https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Function to return Breadth First Traversal of given graph. 10 | void bfs(int u, vector adj[], vector &result, vector &vis) 11 | { 12 | queue q; 13 | q.push(u); 14 | vis[u] = 1; 15 | 16 | while (!q.empty()) 17 | { 18 | int v = q.front(); 19 | q.pop(); 20 | result.push_back(v); 21 | 22 | for (auto it : adj[v]) 23 | { 24 | if (!vis[it]) 25 | { 26 | q.push(it); 27 | vis[it] = 1; 28 | } 29 | } 30 | } 31 | } 32 | 33 | vector bfsOfGraph(int V, vector adj[]) 34 | { 35 | vector vis(V, false); 36 | vector result; 37 | 38 | bfs(0, adj, result, vis); 39 | // for(int i=0; i adj[], vector &vis, vector &dfsVis) 13 | { 14 | vis[node] = 1; 15 | dfsVis[node] = 1; 16 | 17 | // go for the adjacent node 18 | for (auto it : adj[node]) 19 | { 20 | if (!vis[it]) 21 | { 22 | if (checkCycle(it, adj, vis, dfsVis)) 23 | return true; 24 | } 25 | // if both vis[it] and dfsVis[it] equals 1 then cycle exists 26 | else if (dfsVis[it] == 1) 27 | return true; 28 | } 29 | dfsVis[node] = 0; // when we didn't found a cycle 30 | return false; 31 | } 32 | 33 | bool isCyclic(int V, vector adj[]) 34 | { 35 | vector vis(V, 0); 36 | vector dfsVis(V, 0); 37 | 38 | // graph might be disconnected 39 | for (int i = 0; i < V; i++) 40 | { 41 | if (!vis[i]) 42 | { 43 | if (checkCycle(i, adj, vis, dfsVis)) 44 | return true; 45 | } 46 | } 47 | return false; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Graph/dfs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | DFS of Graph 3 | https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | void dfs(int v, vector adj[], vector &vis, vector &storedfs) 10 | { 11 | storedfs.push_back(v); 12 | vis[v] = true; // mark it visited 13 | // go to the adjacent node and call recursively the adjacent node 14 | for (auto u : adj[v]) 15 | { 16 | if (!vis[u]) 17 | dfs(u, adj, vis, storedfs); 18 | } 19 | } 20 | 21 | vector dfsOfGraph(int V, vector adj[]) 22 | { 23 | vector vis(V + 1, false); 24 | vector storedfs; 25 | dfs(0, adj, vis, storedfs); 26 | // for(int i=0; i<=V; i++){ 27 | // if(!vis[i]){ 28 | // dfs(i, adj, vis, storedfs); 29 | // } 30 | // } 31 | return storedfs; 32 | } 33 | }; -------------------------------------------------------------------------------- /Graph/disjointset.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Snippet for Disjoint set. Union by Rank and Path Compression 3 | */ 4 | 5 | 6 | vector parent(100000); 7 | vector rank(100000); 8 | 9 | void makeSet(){ 10 | int n; 11 | for(int i=0;i<=n;i++){ 12 | parent[i]=i; 13 | rank[i]=0; 14 | } 15 | } 16 | 17 | int findParent(int node){ 18 | if(node == parent[node]){ 19 | return node; 20 | } 21 | //this is a path compression 22 | return parent[node] = findParent(parent[node]); 23 | } 24 | 25 | void union(int u, int v){ 26 | u = findParent(u); 27 | v = findParent(v); 28 | 29 | 30 | //put u under v 31 | if(rank[u] < rank[v]){ 32 | parent[u] = v; 33 | } 34 | //put v under u 35 | else if(rank[u] > rank[v]){ 36 | parent[v] = u; 37 | } 38 | else if(rank[u] == rank[v]){ 39 | parent[v] = u; 40 | rank[u]++; 41 | } 42 | } 43 | 44 | void main(){ 45 | makeSet(); 46 | int m; 47 | cin>>m; 48 | 49 | while(m--){ 50 | int u, v; 51 | cin>>u>>v; 52 | union(u, v); 53 | } 54 | 55 | //if 2 and 3 belongs to same component or not 56 | if(findParent(2) != findParent(3)){ 57 | cout<<"Not in same component"< dijkstra(int V, vector > adj[], int S) 12 | { 13 | // create a distance array 14 | vector dis(V, INT_MAX); 15 | dis[S] = 0; 16 | 17 | priority_queue, vector >, greater > > pq; 18 | //(distance, node) 19 | pq.push({0, S}); 20 | 21 | while (!pq.empty()) 22 | { 23 | int prevdis = pq.top().first; // distance 24 | int prev = pq.top().second; // node 25 | 26 | pq.pop(); 27 | 28 | for (auto it : adj[prev]) 29 | { 30 | // it = [node, wt] 31 | if (prevdis + it[1] < dis[it[0]]) 32 | { 33 | dis[it[0]] = prevdis + it[1]; 34 | pq.push({dis[it[0]], it[0]}); 35 | } 36 | } 37 | } 38 | return dis; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Graph/jumpgameiii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1306. Jump Game III 3 | https://leetcode.com/problems/jump-game-iii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | bool helper(vector &arr, vector &visited, int i) 10 | { 11 | if (i < 0 or i >= arr.size() or visited[i]) 12 | return false; 13 | if (arr[i] == 0) 14 | return true; 15 | visited[i] = true; 16 | 17 | bool ans = helper(arr, visited, i + arr[i]) || helper(arr, visited, i - arr[i]); 18 | return ans; 19 | } 20 | 21 | bool canReach(vector &arr, int start) 22 | { 23 | vector visited(arr.size(), false); 24 | return helper(arr, visited, start); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Graph/keysandrooms.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 841. Keys and Rooms 3 | https://leetcode.com/problems/keys-and-rooms/ 4 | */ 5 | 6 | /* 7 | The crux of the problem is, it asks us to visit all the rooms or we can say visit 8 | all the nodes. But there is catch here, you can't visit all the rooms because all 9 | rooms are closed except 0. 10 | 11 | So, you can visit 0 and then get the keys from there for the next rooms and unlock 12 | them. Or, we can say, get the adjacent nodes and visit them one by one. 13 | 14 | We can use DFS traversal for this because this is a simple DFS traversal problem. 15 | Start from the src node 0 and take dfs call and visit the graph and while visiting 16 | mark the node visited. If every node is visited return true else return false. 17 | */ 18 | class Solution 19 | { 20 | public: 21 | // Time: O(V+E), Space: O(V+E) 22 | bool canVisitAllRooms(vector > &rooms) 23 | { 24 | int n = rooms.size(); 25 | vector visited(n, false); 26 | int source = 0; 27 | dfs(source, rooms, visited); 28 | 29 | for (int i = 0; i < visited.size(); i++) 30 | { 31 | if (!visited[i]) 32 | return false; 33 | } 34 | return true; 35 | } 36 | 37 | void dfs(int v, vector > &rooms, vector &visited) 38 | { 39 | visited[v] = true; 40 | 41 | for (auto itr : rooms[v]) 42 | { 43 | if (!visited[itr]) 44 | { 45 | dfs(itr, rooms, visited); 46 | } 47 | } 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Graph/negativeweightcycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Negative weight cycle 3 | https://practice.geeksforgeeks.org/problems/negative-weight-cycle3504/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is to implement the bellman ford algorithm. Time: O(V*E)*/ 10 | int isNegativeWeightCycle(int n, vector > edges) 11 | { 12 | // Code here 13 | int sourceNode = 0; 14 | vector distance(n, INT_MAX); 15 | distance[sourceNode] = 0; 16 | int e = edges.size(); 17 | 18 | //the relaxation step 19 | for (int i = 0; i <= n - 1; i++) 20 | { 21 | for (int j = 0; j < e; j++) 22 | { 23 | int u = edges[j][0]; 24 | int v = edges[j][1]; 25 | int weight = edges[j][2]; 26 | 27 | if (distance[u] != INT_MAX && distance[v] > distance[u] + weight) 28 | { 29 | distance[v] = distance[u] + weight; 30 | } 31 | } 32 | } 33 | 34 | //finding the negative cycle 35 | for (int i = 0; i < e; i++) 36 | { 37 | int u = edges[i][0]; 38 | int v = edges[i][1]; 39 | int weight = edges[i][2]; 40 | 41 | if (distance[u] != INT_MAX && distance[v] > distance[u] + weight) 42 | { 43 | return 1; 44 | } 45 | } 46 | return 0; 47 | } 48 | }; -------------------------------------------------------------------------------- /Graph/networkdelaytime.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 743. Network Delay Time 3 | https://leetcode.com/problems/network-delay-time/ 4 | */ 5 | 6 | /* 7 | This is an implementation of dijkstra's algorithm 8 | */ 9 | class Solution 10 | { 11 | public: 12 | // Time: O(n + Elogn), Space: O(n) + O(n) 13 | int networkDelayTime(vector > ×, int n, int k) 14 | { 15 | vector > adj[n + 1]; // adjacency list 16 | 17 | // build the directed graph 18 | for (auto edge : times) 19 | { 20 | adj[edge[0]].push_back(make_pair(edge[1], edge[2])); 21 | } 22 | 23 | priority_queue, vector >, greater > > pq; 24 | 25 | vector distance(n + 1, INT_MAX); 26 | distance[k] = 0; // since k is a source node 27 | 28 | //(distance, node) 29 | pq.push({0, k}); 30 | 31 | while (!pq.empty()) 32 | { 33 | int u = pq.top().second; 34 | pq.pop(); 35 | 36 | for (auto neighbour : adj[u]) 37 | { 38 | int v = neighbour.first; 39 | int weight = neighbour.second; 40 | 41 | if (distance[v] > distance[u] + weight) 42 | { 43 | distance[v] = distance[u] + weight; 44 | pq.push({distance[v], v}); 45 | } 46 | } 47 | } 48 | 49 | int result = 0; 50 | for (int i = 1; i <= n; i++) 51 | { 52 | if (distance[i] == INT_MAX) 53 | return -1; 54 | result = max(result, distance[i]); 55 | } 56 | return result; 57 | } 58 | }; -------------------------------------------------------------------------------- /Graph/numberofprovinces.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 547. Number of Provinces 3 | https://leetcode.com/problems/number-of-provinces/ 4 | */ 5 | 6 | /* 7 | The main idea of this question is to find the number of connected components in a graph. 8 | I mean, return the total number of provinces. To do this, we will be using dfs to find the 9 | number of connected components in an undirected graph. 10 | */ 11 | class Solution 12 | { 13 | public: 14 | //Time: O(V+E), Space: O(V) 15 | int findCircleNum(vector > &isConnected) 16 | { 17 | int n = isConnected.size(); 18 | vector visited(n, false); 19 | int count = 0; 20 | for (int i = 0; i < n; i++) 21 | { 22 | if (!visited[i]) 23 | { 24 | dfs(isConnected, visited, i); 25 | count++; 26 | } 27 | } 28 | 29 | //total number of provinces 30 | return count; 31 | } 32 | 33 | void dfs(vector > &isConnected, vector &visited, int v) 34 | { 35 | visited[v] = true; 36 | 37 | for (int u = 0; u < isConnected.size(); u++) 38 | if (isConnected[v][u] == 1 && visited[u] == false) 39 | dfs(isConnected, visited, u); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Graph/ratinamazeproblem-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rat in a Maze Problem - I 3 | https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is we have done simple traversals in all the 4 directions*/ 10 | void helper(vector > &m, int x, int y, int n, vector &result, string path) 11 | { 12 | //doing the bound check 13 | if (x < 0 || x >= n || y < 0 || y >= n || m[x][y] != 1) 14 | return; 15 | 16 | /*once you reach the end and completed the path 17 | push to the result and return*/ 18 | if (x == n - 1 && y == n - 1) 19 | { 20 | result.push_back(path); 21 | return; 22 | } 23 | 24 | m[x][y] = -1; //mark it visited for the current traversal 25 | 26 | /*moving to all the four directions and checking the every 27 | possible path*/ 28 | helper(m, x + 1, y, n, result, path + 'D'); 29 | helper(m, x - 1, y, n, result, path + 'U'); 30 | helper(m, x, y + 1, n, result, path + 'R'); 31 | helper(m, x, y - 1, n, result, path + 'L'); 32 | 33 | m[x][y] = 1; //mark it unvisited for further traversals 34 | } 35 | 36 | vector findPath(vector > &m, int n) 37 | { 38 | // Your code goes here 39 | vector result; 40 | helper(m, 0, 0, n, result, ""); 41 | sort(result.begin(), result.end()); 42 | return result; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Graph/topologicalsort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topological sort 3 | https://practice.geeksforgeeks.org/problems/topological-sort/1/# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Function to return list containing vertices in Topological order. 10 | void toposort(int node, vector adj[], vector &vis, stack &st) 11 | { 12 | vis[node] = 1; // mark it visited 13 | for (auto it : adj[node]) 14 | { 15 | if (!vis[it]) 16 | { 17 | toposort(it, adj, vis, st); 18 | } 19 | } 20 | //when the dfs for 'node' is completed, push it to the stack 21 | st.push(node); 22 | } 23 | 24 | vector topoSort(int V, vector adj[]) 25 | { 26 | vector vis(V, 0); 27 | stack st; 28 | 29 | // graph might be disconnected 30 | for (int i = 0; i < V; i++) 31 | { 32 | if (!vis[i]) 33 | { 34 | // toposort always works for DAG 35 | toposort(i, adj, vis, st); 36 | } 37 | } 38 | 39 | // return the topo sort elements 40 | vector result; 41 | while (!st.empty()) 42 | { 43 | result.push_back(st.top()); 44 | st.pop(); 45 | } 46 | 47 | return result; 48 | } 49 | }; -------------------------------------------------------------------------------- /Greedy/carpooling.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1094. Car Pooling 3 | https://leetcode.com/problems/car-pooling/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(N), Space: O(N) 10 | bool carPooling(vector > &trips, int capacity) 11 | { 12 | vector > v; 13 | 14 | for (auto trip : trips) 15 | { 16 | v.push_back({trip[1], trip[0]}); 17 | v.push_back({trip[2], -trip[0]}); 18 | } 19 | 20 | sort(v.begin(), v.end()); 21 | int seatsFilled = 0; 22 | for (int i = 0; i < v.size(); i++) 23 | { 24 | seatsFilled += v[i].second; 25 | if (seatsFilled > capacity) 26 | return false; 27 | } 28 | return true; 29 | } 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /Greedy/fractionalknapsack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Fractional Knapsack 3 | https://practice.geeksforgeeks.org/problems/fractional-knapsack-1587115620/1# 4 | Article: https://www.geeksforgeeks.org/fractional-knapsack-problem/ 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | //Function to get the maximum total value in the knapsack. 11 | //Time: O(NlogN), Space: O(1) 12 | static bool comp(struct Item a, struct Item b) 13 | { 14 | //calculating the value/weight and sort according to that in 15 | //decreasing order 16 | double r1 = (double)a.value / (double)a.weight; 17 | double r2 = (double)b.value / (double)b.weight; 18 | 19 | return r1 > r2; 20 | } 21 | double fractionalKnapsack(int W, Item arr[], int n) 22 | { 23 | sort(arr, arr + n, comp); 24 | double finalValue = 0.0; 25 | // int currWeight = 0; 26 | 27 | for (int i = 0; i < n; i++) 28 | { 29 | if (arr[i].weight <= W) 30 | { 31 | finalValue += arr[i].value; 32 | W -= arr[i].weight; 33 | continue; 34 | } 35 | else 36 | { 37 | //calculating the value/weight ratio so that we can put the 38 | //fraction of that weight in the bag 39 | double r = (double)arr[i].value / (double)arr[i].weight; 40 | finalValue += W * r; 41 | break; 42 | } 43 | } 44 | return finalValue; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Greedy/huffmanencoding.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Huffman Encoding 3 | https://practice.geeksforgeeks.org/problems/huffman-encoding3345/1# 4 | */ 5 | 6 | struct Node{ 7 | char data; 8 | int freq; 9 | Node *left, *right; 10 | 11 | Node(char data, int freq){ 12 | left = right = NULL; 13 | this->data = data; 14 | this->freq = freq; 15 | } 16 | }; 17 | 18 | struct compare{ 19 | bool operator()(Node* l, Node* r){ 20 | return (l->freq > r->freq); 21 | } 22 | }; 23 | 24 | class Solution 25 | { 26 | void print(struct Node* root, string s, vector& v){ 27 | if(!root) return; 28 | if(root->data != '$') 29 | v.push_back(s); 30 | print(root->left, s+"0", v); 31 | print(root->right, s+"1", v); 32 | } 33 | public: 34 | vector huffmanCodes(string S,vector f,int N) 35 | { 36 | Node *left, *right, *top; 37 | 38 | priority_queue, compare> pq; 39 | 40 | for(int i=0; ifreq + right->freq); 52 | 53 | top->left = left; 54 | top->right = right; 55 | 56 | pq.push(top); 57 | } 58 | vector v; 59 | print(pq.top(), "", v); 60 | return v; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /Greedy/minimumplatforms.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Platforms 3 | https://practice.geeksforgeeks.org/problems/minimum-platforms-1587115620/1# 4 | */ 5 | 6 | class Solution{ 7 | public: 8 | //Function to find the minimum number of platforms required at the 9 | //railway station such that no train waits. 10 | //Time: O(nlogn), Space: O(1) 11 | int findPlatform(int arr[], int dep[], int n) 12 | { 13 | // Your code here 14 | sort(arr, arr+n); 15 | sort(dep, dep+n); 16 | 17 | int i=1, j=0, platformsNeeded = 1, result = 1; 18 | while(i < n && j < n){ 19 | if(arr[i] <= dep[j]){ 20 | platformsNeeded++; 21 | i++; 22 | } 23 | else if(arr[i] > dep[j]){ 24 | platformsNeeded--; 25 | j++; 26 | } 27 | 28 | result = max(result, platformsNeeded); 29 | } 30 | return result; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Greedy/nmeetingsinoneroom.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | N meetings in one room 3 | https://practice.geeksforgeeks.org/problems/n-meetings-in-one-room-1587115620/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Function to find the maximum number of meetings that can 10 | //be performed in a meeting room. 11 | int maxMeetings(int start[], int end[], int n) 12 | { 13 | // Your code here 14 | vector > activity; 15 | for (int i = 0; i < n; i++) 16 | { 17 | activity.push_back({start[i], end[i]}); 18 | } 19 | 20 | sort(activity.begin(), activity.end(), [&](vector &a, vector &b){ 21 | return a[1] < b[1]; 22 | }); 23 | 24 | int noOfActivities = 1; 25 | int done = activity[0][1]; 26 | for (int i = 1; i < n; i++) 27 | { 28 | if (activity[i][0] > done) 29 | { 30 | noOfActivities++; 31 | done = activity[i][1]; 32 | } 33 | } 34 | return noOfActivities; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Greedy/wigglesubsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 376. Wiggle Subsequence 3 | https://leetcode.com/problems/wiggle-subsequence/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(N), Space: O(N) 10 | int wiggleMaxLength(vector &nums) 11 | { 12 | if (nums.size() < 2) 13 | return nums.size(); 14 | 15 | int prev = nums[1] - nums[0]; 16 | int diff = prev; 17 | int count = prev != 0 ? 2 : 1; 18 | 19 | for (int i = 2; i < nums.size(); i++) 20 | { 21 | diff = nums[i] - nums[i - 1]; 22 | if ((prev >= 0 && diff < 0) || (prev <= 0 && diff > 0)) 23 | { 24 | count++; 25 | prev = diff; 26 | } 27 | } 28 | return count; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /HashMap/isomorphicstrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 205. Isomorphic Strings 3 | https://leetcode.com/problems/isomorphic-strings/ 4 | */ 5 | 6 | /* 7 | Insert chars of string s as key, and chars of t as value , into a map. For ex. if s = foo and t = baa 8 | contents of map should be'f'-'b' , 'o'-'a'. 9 | 10 | if present check for the values of the corresponding chars in t and map's value, i.e map[s[i]] != 11 | t[i] return false else continue to next index. 12 | 13 | The above steps work for the given eg. test cases, but for s= badc and t = baba the map results in 14 | the following content:'b'-'b' , 'a'-'a' , 'd'-'a', 'c'-'a' and return true as answer. 15 | 16 | So to avoid test cases having "many to one" key value pair, the function is called by interchanging s 17 | and t , for the above case now s= baba and t= badcwhen characterb of string s is processed for the 18 | second time map[s[i]] = b but t[i]= d which are not same, hence returns false. 19 | */ 20 | class Solution 21 | { 22 | public: 23 | //Time: O(N), Space: O(N) 24 | bool isIsomorphic(string s, string t) 25 | { 26 | return (helper(s, t) && helper(t, s)); 27 | } 28 | 29 | int helper(string s, string t) 30 | { 31 | unordered_map mp; 32 | 33 | int n = s.size(); 34 | for (int i = 0; i < s.size(); i++) 35 | { 36 | if (mp.find(s[i]) != mp.end()) 37 | { 38 | if (mp[s[i]] != t[i]) 39 | return false; 40 | } 41 | else 42 | mp[s[i]] = t[i]; 43 | } 44 | return true; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /HashMap/majorityelement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 169. Majority Element 3 | https://leetcode.com/problems/majority-element/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int majorityElement(vector &nums) 10 | { 11 | unordered_map mp; 12 | 13 | for (auto x : nums){ 14 | mp[x]++; 15 | } 16 | 17 | for (auto item : mp){ 18 | if (item.second > nums.size() / 2){ 19 | return item.first; 20 | } 21 | } 22 | return 0; 23 | } 24 | }; -------------------------------------------------------------------------------- /HashMap/majorityelementii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 229. Majority Element II 3 | https://leetcode.com/problems/majority-element-ii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | vector majorityElement(vector &nums) 10 | { 11 | unordered_map mp; 12 | 13 | vector result; 14 | 15 | for (auto x : nums){ 16 | mp[x]++; 17 | } 18 | 19 | for (auto item : mp){ 20 | if (item.second > nums.size() / 3){ 21 | result.push_back(item.first); 22 | } 23 | } 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /HashMap/reducearraysizetothehalf.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1338. Reduce Array Size to The Half 3 | https://leetcode.com/problems/reduce-array-size-to-the-half/ 4 | */ 5 | /* 6 | We need to choose the smallest set of numbers such that deleting all their occurrences will 7 | reduce the array size by atleast half. To accomplish this, we need to delete the numbers 8 | having higher frequencies so that the size is minimized. 9 | */ 10 | class Solution 11 | { 12 | public: 13 | //Time: O(N + N + NlogN), Space: O(N) 14 | int minSetSize(vector &arr) 15 | { 16 | 17 | //calculate the frequency of the numbers 18 | unordered_map mp; 19 | for (int i = 0; i < arr.size(); i++) 20 | mp[arr[i]]++; 21 | 22 | //store the frequencies in vector 23 | vector v; 24 | for (auto x : mp) 25 | v.push_back(x.second); 26 | 27 | //sort the frequencies in descending order 28 | sort(v.begin(), v.end(), greater()); 29 | 30 | //numbers having maximum frequency should be deleted so that we will get the set with 31 | //atleast size >= half of the array size 32 | int deleteNumbers = 0; 33 | int result = 0; 34 | for (auto y : v) 35 | { 36 | deleteNumbers += y; 37 | result++; 38 | if (deleteNumbers >= arr.size() / 2) 39 | return result; 40 | } 41 | return -1; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Heap/kclosestpointstoorigin.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 973. K Closest Points to Origin 3 | https://leetcode.com/problems/k-closest-points-to-origin/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(nlogk), Space: O(k) 10 | vector > kClosest(vector > &points, int K) 11 | { 12 | priority_queue > > maxHeap; 13 | 14 | for (int i = 0; i < points.size(); i++) 15 | { 16 | //calculating the distance 17 | int dist = points[i][0] * points[i][0] + points[i][1] * points[i][1]; 18 | maxHeap.push({dist, points[i]}); 19 | 20 | if (maxHeap.size() > K) 21 | maxHeap.pop(); 22 | } 23 | 24 | vector > result; 25 | while (maxHeap.size() > 0) 26 | { 27 | result.push_back(maxHeap.top().second); 28 | maxHeap.pop(); 29 | } 30 | return result; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Heap/klargestelements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | k largest elements 3 | https://practice.geeksforgeeks.org/problems/k-largest-elements4206/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(nlogk).Space: O(k) 10 | vector kLargest(int arr[], int n, int k) 11 | { 12 | priority_queue, greater > minHeap; 13 | vector result; 14 | for (int i = 0; i < n; i++) 15 | { 16 | minHeap.push(arr[i]); 17 | if (minHeap.size() > k) 18 | minHeap.pop(); 19 | } 20 | 21 | while (minHeap.size() > 0) 22 | { 23 | result.push_back(minHeap.top()); 24 | minHeap.pop(); 25 | } 26 | reverse(result.begin(), result.end()); 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /Heap/kthsmallestelement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth smallest element 3 | https://practice.geeksforgeeks.org/problems/kth-smallest-element5635/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // arr : given array 10 | // l : starting index of the array i.e 0 11 | // r : ending index of the array i.e size-1 12 | // k : find kth smallest element and return using this function 13 | //Time: O(nlogk), Space: O(k); 14 | int kthSmallest(int arr[], int l, int r, int k) 15 | { 16 | priority_queue maxHeap; 17 | for (int i = l; i <= r; i++) 18 | { 19 | maxHeap.push(arr[i]); 20 | 21 | if (maxHeap.size() > k) 22 | maxHeap.pop(); 23 | } 24 | return maxHeap.top(); 25 | } 26 | }; -------------------------------------------------------------------------------- /Heap/kthsmallestelementinsortedmatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 378. Kth Smallest Element in a Sorted Matrix 3 | https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 4 | */ 5 | 6 | /* 7 | We have to get the kth smallest element in a sorted matrix, that means we need to keep the k small 8 | elements, so that we can easily find kth smallest element. Hence we will be using max heap. 9 | */ 10 | class Solution 11 | { 12 | public: 13 | //Time: O(N^2*logk), Space: O(k) 14 | int kthSmallest(vector > &matrix, int k) 15 | { 16 | 17 | //creating the max heap 18 | priority_queue maxheap; 19 | 20 | for (int i = 0; i < matrix.size(); i++) 21 | { 22 | for (int j = 0; j < matrix.size(); j++) 23 | { 24 | maxheap.push(matrix[i][j]); 25 | 26 | //if the size of the maxheap is more than k just pop the element 27 | if (maxheap.size() > k) 28 | maxheap.pop(); 29 | } 30 | } 31 | //kth smallest element will be at top 32 | return maxheap.top(); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Heap/topkfrequentelements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 347. Top K Frequent Elements 3 | https://leetcode.com/problems/top-k-frequent-elements/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(nlogk), Space: O(n + k) 10 | vector topKFrequent(vector &nums, int k) 11 | { 12 | unordered_map mp; 13 | 14 | for (int i = 0; i < nums.size(); i++) 15 | mp[nums[i]]++; 16 | 17 | //using the min heap 18 | priority_queue, vector >, greater > > pq; 19 | 20 | for (auto i = mp.begin(); i != mp.end(); i++) 21 | { 22 | pq.push({i->second, i->first}); 23 | 24 | if (pq.size() > k) 25 | pq.pop(); 26 | } 27 | 28 | vector kFrequent; 29 | while (pq.size() > 0) 30 | { 31 | kFrequent.push_back(pq.top().second); 32 | pq.pop(); 33 | } 34 | return kFrequent; 35 | } 36 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Nitish Kumar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LinkedList/addtwonumbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 2. Add Two Numbers 3 | https://leetcode.com/problems/add-two-numbers/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | /*the basic idea is to apply simple math, take every 20 | node and add them and manage carries 21 | Time: O(max(m,n)), Space: O(max(m,n))*/ 22 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 23 | { 24 | ListNode *result = new ListNode(); 25 | ListNode *temp = result; 26 | int carry = 0; 27 | 28 | while (l1 || l2) 29 | { 30 | int x = l1 != NULL ? l1->val : 0; 31 | int y = l2 != NULL ? l2->val : 0; 32 | int sum = x + y + carry; 33 | carry = sum / 10; //getting the carry 34 | 35 | //putting the actual value in the node 36 | temp->next = new ListNode(sum % 10); 37 | temp = temp->next; 38 | 39 | /*move to the next node*/ 40 | if (l1) 41 | l1 = l1->next; 42 | if (l2) 43 | l2 = l2->next; 44 | } 45 | 46 | if (carry > 0) 47 | { 48 | temp->next = new ListNode(carry); 49 | } 50 | return result->next; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /LinkedList/deleteloopinlinkedlist.cpp: -------------------------------------------------------------------------------- 1 | /* This question is not on the Leetcode as of now, so I'm doing this one 2 | for learning purpose, I am assuming that we know how to create a Linked 3 | List, and and how to detect the loop in a Linked List. So, i will directly 4 | write the function for deleting the loop of Linked List. 5 | 6 | The basic idea is, we will be using Floyd's Tortoise and Hare Algorithm 7 | and when the hare and tortoise meet at same point then move anyone hare 8 | or tortoise to head and start traversing both hare and tortoise one by 9 | one and check if the next node is same, As you get the next node same, 10 | whichever you haven't move to the head earlier put NULL in their next. 11 | */ 12 | 13 | void deleteLoop(node* &head){ 14 | node* hare = head; 15 | node* tortoise = head; 16 | 17 | while(hare && hare->next){ 18 | hare = hare->next->next; 19 | tortoise = tortoise->next; 20 | 21 | if(hare == tortoise){ 22 | 23 | /*you can do the vice versa also*/ 24 | tortoise = head; 25 | 26 | while(tortoise->next != hare->next){ 27 | tortoise = tortoise->next; 28 | hare = hare->next; 29 | } 30 | hare->next = NULL; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LinkedList/linkedlistcycleii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 142. Linked List Cycle II 3 | https://leetcode.com/problems/linked-list-cycle-ii/ 4 | */ 5 | 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 Solution 15 | { 16 | public: 17 | /*the basic idea is follow the procedure of 18 | detecting the cycle in LL and then when the 19 | hare and tortoise meet reset the tortoise to 20 | head and then move forward tortoise and hare 21 | one by one, again they will meet then that 22 | will be the answer Time: O(N)*/ 23 | ListNode *detectCycle(ListNode *head) 24 | { 25 | ListNode *hare, *tortoise; 26 | hare = head; 27 | tortoise = head; 28 | 29 | while (hare && hare->next) 30 | { 31 | hare = hare->next->next; 32 | tortoise = tortoise->next; 33 | 34 | if (hare == tortoise) 35 | { 36 | tortoise = head; 37 | 38 | while (hare != tortoise) 39 | { 40 | hare = hare->next; 41 | tortoise = tortoise->next; 42 | } 43 | /*can return tortoise also*/ 44 | return hare; 45 | } 46 | } 47 | return NULL; 48 | } 49 | }; -------------------------------------------------------------------------------- /LinkedList/middleofthelinkedlist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 876. Middle of the Linked List 3 | https://leetcode.com/problems/middle-of-the-linked-list/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | //Time: O(N), Space: O(1) 20 | ListNode *middleNode(ListNode *head) 21 | { 22 | 23 | ListNode *fast = head, *slow = head; 24 | while (fast && fast->next) 25 | { 26 | slow = slow->next; 27 | fast = fast->next->next; 28 | } 29 | return slow; 30 | } 31 | }; -------------------------------------------------------------------------------- /LinkedList/nextgreaternodeinlinkedlist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1019. Next Greater Node In Linked List 3 | https://leetcode.com/problems/next-greater-node-in-linked-list/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | /*basic idea is to traverse through the list 20 | and compare one by one. Time: O(N^2), Space: O(1)*/ 21 | vector nextLargerNodes(ListNode *head) 22 | { 23 | 24 | if (head == NULL) 25 | return {}; 26 | 27 | vector result; 28 | while (head != NULL) 29 | { 30 | int x = head->val; 31 | ListNode *temp = head->next; 32 | 33 | while (temp != NULL) 34 | { 35 | if (x < temp->val) 36 | { 37 | result.push_back(temp->val); 38 | break; 39 | } 40 | temp = temp->next; 41 | } 42 | 43 | if (temp == NULL) 44 | { 45 | result.push_back(0); 46 | } 47 | head = head->next; 48 | } 49 | return result; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /LinkedList/removeduplicatesfromsortedlist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 83. Remove Duplicates from Sorted List 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | //Time: O(N) 20 | ListNode *deleteDuplicates(ListNode *head) 21 | { 22 | ListNode *temp = head; 23 | 24 | if (!head) 25 | return NULL; 26 | while (temp->next) 27 | { 28 | if (temp->val == temp->next->val) 29 | temp->next = temp->next->next; 30 | else 31 | temp = temp->next; 32 | } 33 | return head; 34 | } 35 | }; -------------------------------------------------------------------------------- /LinkedList/removeduplicatesfromsortedlistii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 82. Remove Duplicates from Sorted List II 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | ListNode *deleteDuplicates(ListNode *head) 20 | { 21 | 22 | if (head == NULL || head->next == NULL) 23 | return head; 24 | 25 | auto temp = new ListNode(-1); 26 | auto prev = temp; 27 | 28 | while (head != NULL) 29 | { 30 | if (head->next && head->val == head->next->val) 31 | { 32 | int duplicate = head->val; 33 | while (head && head->val == duplicate) 34 | { 35 | head = head->next; 36 | } 37 | } 38 | else 39 | { 40 | prev->next = head; 41 | prev = prev->next; 42 | head = head->next; 43 | } 44 | } 45 | prev->next = NULL; 46 | return temp->next; 47 | } 48 | }; -------------------------------------------------------------------------------- /LinkedList/removenthnodefromendoflinkedlist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 19. Remove Nth Node From End of List 3 | https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | //Time: O(length of LL), Space: O(1) 20 | ListNode *removeNthFromEnd(ListNode *head, int n) 21 | { 22 | 23 | if (head == NULL) 24 | return head; 25 | 26 | int count = 0; 27 | ListNode *r = head; 28 | //counting the length of the list 29 | while (r != NULL) 30 | { 31 | count++; 32 | r = r->next; 33 | } 34 | int accessLessthan_n = count - n; 35 | if (accessLessthan_n == 0) 36 | return head->next; 37 | 38 | //removing the element from the desired position 39 | r = head; 40 | while (--accessLessthan_n) 41 | { 42 | r = r->next; 43 | } 44 | ListNode *temp; 45 | temp = r->next; 46 | r->next = temp->next; 47 | return head; 48 | } 49 | }; -------------------------------------------------------------------------------- /LinkedList/reverselinkedlist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 206. Reverse Linked List 3 | https://leetcode.com/problems/reverse-linked-list/ 4 | */ 5 | 6 | //Iterative 7 | //Time O(N), Space O(1) 8 | class Solution 9 | { 10 | public: 11 | ListNode *reverseList(ListNode *head) 12 | { 13 | ListNode *prevptr, *nextptr, *curr; 14 | curr = head; 15 | prevptr = nextptr = NULL; 16 | while (curr) 17 | { 18 | nextptr = curr->next; 19 | curr->next = prevptr; 20 | prevptr = curr; 21 | curr = nextptr; 22 | } 23 | //curr = prevptr; 24 | return prevptr; 25 | } 26 | }; 27 | 28 | //Recursive 29 | //Time O(N), Space O(N) 30 | class Solution 31 | { 32 | public: 33 | ListNode* reverseList(ListNode* head) { 34 | if(head == NULL || head->next == NULL) return head; 35 | ListNode* newhead = reverseList(head->next); 36 | head->next->next = head; 37 | head->next = NULL; 38 | 39 | return newhead; 40 | } 41 | }; -------------------------------------------------------------------------------- /LinkedList/reverselinkedlistii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 92. Reverse Linked List II 3 | https://leetcode.com/problems/reverse-linked-list-ii/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | //Time: O(N), Space: O(1) 20 | ListNode *reverseBetween(ListNode *head, int m, int n) 21 | { 22 | if (head == NULL) 23 | return NULL; 24 | 25 | ListNode *curr = head, *prev = NULL; 26 | while (m > 1) 27 | { 28 | prev = curr; 29 | curr = curr->next; 30 | m--; 31 | n--; 32 | } 33 | 34 | ListNode *con = prev, *tail = curr; 35 | ListNode *third = NULL; 36 | while (n > 0) 37 | { 38 | third = curr->next; 39 | curr->next = prev; 40 | prev = curr; 41 | curr = third; 42 | n--; 43 | } 44 | 45 | if (con != NULL) 46 | { 47 | con->next = prev; 48 | } 49 | else 50 | { 51 | head = prev; 52 | } 53 | tail->next = curr; 54 | return head; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /LinkedList/rotatelist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 61. Rotate List 3 | https://leetcode.com/problems/rotate-list/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | // Time: O(N) 20 | ListNode *rotateRight(ListNode *head, int k) 21 | { 22 | 23 | if (head == NULL || head->next == NULL || k == 0) 24 | return head; 25 | 26 | ListNode *temp = head; 27 | int n = 1; 28 | while (temp->next) 29 | { 30 | n++; 31 | temp = temp->next; 32 | } 33 | 34 | k = k % n; 35 | // if k == 0 no rotation 36 | if (k == 0) 37 | return head; 38 | ListNode *newTail = head; 39 | 40 | // creating the new tail 41 | int stepsForNewTail = n - k - 1; 42 | while (stepsForNewTail--) 43 | { 44 | newTail = newTail->next; 45 | } 46 | 47 | // get the new head for the linked list 48 | ListNode *newHead = newTail->next; 49 | newTail->next = NULL; 50 | temp->next = head; 51 | 52 | return newHead; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /LinkedList/swapnodesinpairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 24. Swap Nodes in Pairs 3 | https://leetcode.com/problems/swap-nodes-in-pairs/ 4 | */ 5 | 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 Solution 17 | { 18 | public: 19 | //Time: O(N) 20 | ListNode *swapPairs(ListNode *head) 21 | { 22 | if (head == NULL) 23 | return head; 24 | ListNode *prev; 25 | ListNode *temp; 26 | prev = head; 27 | while (temp->next != NULL) 28 | { 29 | prev = temp; 30 | temp = temp->next; 31 | swap(prev->val, temp->val); 32 | temp = temp->next; 33 | if (temp == NULL) 34 | break; 35 | } 36 | return (head); 37 | } 38 | }; 39 | 40 | // Solution 2 41 | class Solution 42 | { 43 | public: 44 | //Time: O(N) 45 | ListNode *swapPairs(ListNode *head) 46 | { 47 | if (head == NULL || head->next == NULL) 48 | return head; 49 | 50 | ListNode *temp = head; 51 | head = head->next; 52 | temp->next = head->next; 53 | head->next = temp; 54 | 55 | temp->next = swapPairs(temp->next); 56 | return head; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /Maths/minimumoperationstomakearrayequal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1551. Minimum Operations to Make Array Equal 3 | https://leetcode.com/problems/minimum-operations-to-make-array-equal/ 4 | */ 5 | 6 | //Detailed explaination is given here 7 | // https://leetcode.com/problems/minimum-operations-to-make-array-equal/discuss/1148440/C%2B%2B-Math-Solution-Explained-Step-by-step-100-Time-~70-Space 8 | class Solution 9 | { 10 | public: 11 | int minOperations(int n) 12 | { 13 | return n * n / 4; 14 | } 15 | }; -------------------------------------------------------------------------------- /Maths/powerofthree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 326. Power of Three 3 | https://leetcode.com/problems/power-of-three/ 4 | */ 5 | 6 | class Solution { 7 | public: 8 | //Time: O(log3N), Space: O(1) 9 | bool isPowerOfThree(int n) { 10 | if(n < 1) return false; 11 | while(n%3 == 0){ 12 | n = n/3; 13 | } 14 | return n == 1; 15 | } 16 | }; -------------------------------------------------------------------------------- /Maths/poweroftwo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 231. Power of Two 3 | https://leetcode.com/problems/power-of-two/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | bool isPowerOfTwo(int n) 10 | { 11 | 12 | if (n <= 0) 13 | return 0; 14 | return (n & (n - 1)) ? false : true; 15 | //return (n && !(n & n-1)); //first n is for the corner case when n is 0 16 | } 17 | }; -------------------------------------------------------------------------------- /Matrix/determinewhetherthematrixcanbeobtainedbyrotation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1886. Determine Whether Matrix Can Be Obtained By Rotation 3 | https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/ 4 | */ 5 | 6 | /* 7 | The main idea is to rotate matrix, check everytime that if it equal to the target matrix. 8 | We only have to rotate till 270 deg because after that the matrix will be same 9 | */ 10 | class Solution 11 | { 12 | public: 13 | //Time: O(N^2), Space: O(1) 14 | bool findRotation(vector > &mat, vector > &target) 15 | { 16 | if (mat == target) 17 | return true; 18 | 19 | //90 deg 20 | rotate(mat); 21 | if (mat == target) 22 | return true; 23 | 24 | //180 deg 25 | rotate(mat); 26 | if (mat == target) 27 | return true; 28 | 29 | //270 deg 30 | rotate(mat); 31 | if (mat == target) 32 | return true; 33 | 34 | return false; 35 | } 36 | 37 | void rotate(vector > &mat) 38 | { 39 | 40 | //transpose of matrix 41 | for (int i = 0; i < mat.size(); i++) 42 | for (int j = i; j < mat.size(); j++) 43 | swap(mat[i][j], mat[j][i]); 44 | 45 | //reverse the rows 46 | for (int i = 0; i < mat.size(); i++) 47 | reverse(mat[i].begin(), mat[i].end()); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Matrix/kthsmallestelementinasortedmatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 378. Kth Smallest Element in a Sorted Matrix 3 | https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*using maxheap, basic idea is to put the elements in the 10 | pq and if pq size > k pop the elements and atlast return the 11 | top value. Time: O(N^2), Space: O(N)*/ 12 | int kthSmallest(vector > &matrix, int k) 13 | { 14 | priority_queue temp; 15 | 16 | for (int i = 0; i < matrix.size(); i++) 17 | { 18 | for (int j = 0; j < matrix.size(); j++) 19 | { 20 | temp.push(matrix[i][j]); 21 | if (temp.size() > k) 22 | { 23 | temp.pop(); 24 | } 25 | } 26 | } 27 | 28 | return temp.top(); 29 | } 30 | }; -------------------------------------------------------------------------------- /Matrix/maximumsumrectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum sum Rectangle 3 | https://practice.geeksforgeeks.org/problems/maximum-sum-rectangle2948/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N*3) 10 | int kadane(vector &kade, int R) 11 | { 12 | int max_sum = INT_MIN, sum = 0; 13 | for (int i = 0; i < R; i++) 14 | { 15 | sum += kade[i]; 16 | max_sum = max(max_sum, sum); 17 | 18 | if (sum < 0) 19 | sum = 0; 20 | } 21 | return max_sum; 22 | } 23 | 24 | int maximumSumRectangle(int R, int C, vector > M) 25 | { 26 | int result = INT_MIN; 27 | for (int i = 0; i < C; i++) 28 | { 29 | vector kade(R, 0); 30 | for (int x = i; x < C; x++) 31 | { 32 | for (int j = 0; j < R; j++) 33 | { 34 | kade[j] += M[j][x]; 35 | } 36 | int val = kadane(kade, R); 37 | result = max(result, val); 38 | } 39 | } 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /Matrix/rotateimage.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 48. Rotate Image 3 | https://leetcode.com/problems/rotate-image/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is to take transpose of 10 | a matrix and reverse the rows. Time: O(N^2), Space: O(1)*/ 11 | void rotate(vector > &matrix) 12 | { 13 | if (matrix.empty()) 14 | return; 15 | 16 | //take the transpose 17 | int size = 0; 18 | for (int i = 0; i < matrix.size(); i++) 19 | { 20 | for (int j = i; j < matrix.size(); j++) 21 | { 22 | int temp = matrix[i][j]; 23 | matrix[i][j] = matrix[j][i]; 24 | matrix[j][i] = temp; 25 | } 26 | } 27 | 28 | //reverse the rows 29 | for (int i = 0; i < matrix.size(); i++) 30 | { 31 | for (int j = 0; j < matrix.size() / 2; j++) 32 | { 33 | int temp = matrix[i][j]; 34 | matrix[i][j] = matrix[i][matrix.size() - j - 1]; 35 | matrix[i][matrix.size() - j - 1] = temp; 36 | } 37 | } 38 | } 39 | }; -------------------------------------------------------------------------------- /Matrix/setmatrixzeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 73. Set Matrix Zeroes 3 | https://leetcode.com/problems/set-matrix-zeroes/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(m*n), Space: O(m+n) 10 | void setZeroes(vector > &matrix) 11 | { 12 | int r = matrix.size(); 13 | int c = matrix[0].size(); 14 | 15 | vector rows; 16 | vector cols; 17 | 18 | for (int i = 0; i < r; i++) 19 | { 20 | for (int j = 0; j < c; j++) 21 | { 22 | if (matrix[i][j] == 0) 23 | { 24 | rows.push_back(i); 25 | cols.push_back(j); 26 | } 27 | } 28 | } 29 | 30 | for (int i = 0; i < r; i++) 31 | { 32 | for (int j = 0; j < c; j++) 33 | { 34 | if (find(rows.begin(), rows.end(), i) != rows.end() || 35 | find(cols.begin(), cols.end(), j) != cols.end()) 36 | matrix[i][j] = 0; 37 | } 38 | } 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Matrix/spiralmatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 54. Spiral Matrix 3 | https://leetcode.com/problems/spiral-matrix/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic is to simply traverse the matrix 10 | Time: O(N), Space: O(N)*/ 11 | vector spiralOrder(vector> &matrix) 12 | { 13 | vector resultantArray; 14 | 15 | if (matrix.empty()) 16 | return vector(); 17 | 18 | int r1, c1, r2, c2; 19 | r1 = 0; 20 | r2 = matrix.size() - 1; 21 | c1 = 0; 22 | c2 = matrix[0].size() - 1; 23 | 24 | while (r1 <= r2 && c1 <= c2) 25 | { 26 | for (int c = c1; c <= c2; c++) 27 | resultantArray.push_back(matrix[r1][c]); 28 | 29 | for (int r = r1 + 1; r <= r2; r++) 30 | resultantArray.push_back(matrix[r][c2]); 31 | 32 | if (c1 < c2 && r1 < r2) 33 | { 34 | for (int c = c2 - 1; c > c1; c--) 35 | resultantArray.push_back(matrix[r2][c]); 36 | for (int r = r2; r > r1; r--) 37 | resultantArray.push_back(matrix[r][c1]); 38 | } 39 | r1++; 40 | r2--; 41 | c1++; 42 | c2--; 43 | } 44 | 45 | return resultantArray; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Recursion/deletemiddleelementofastack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Delete middle element of a stack 3 | https://practice.geeksforgeeks.org/problems/delete-middle-element-of-a-stack/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Function to delete middle element of a stack. 10 | //Time: O(N), Space: O(N) 11 | void helper(stack &s, int k) 12 | { 13 | if (k == 1) 14 | { 15 | s.pop(); 16 | return; 17 | } 18 | 19 | int val = s.top(); 20 | s.pop(); 21 | 22 | helper(s, k - 1); 23 | s.push(val); 24 | } 25 | void deleteMid(stack &s, int sizeOfStack) 26 | { 27 | int k = (sizeOfStack / 2) + 1; 28 | helper(s, k); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Recursion/finduniquebinarystring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1980. Find Unique Binary String 3 | https://leetcode.com/problems/find-unique-binary-string/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(2^N) 10 | string res; 11 | bool ok = false; 12 | void findUniqueString(unordered_set s, string str, int idx, int n) 13 | { 14 | // base case 15 | if (n == idx) 16 | { 17 | if (!s.count(str)) 18 | { 19 | res = str; 20 | ok = true; 21 | } 22 | return; 23 | } 24 | 25 | if (!ok) 26 | findUniqueString(s, str + "0", idx + 1, n); 27 | if (!ok) 28 | findUniqueString(s, str + "1", idx + 1, n); 29 | } 30 | string findDifferentBinaryString(vector &nums) 31 | { 32 | unordered_set s(nums.begin(), nums.end()); 33 | findUniqueString(s, "", 0, nums.size()); 34 | return res; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Recursion/generateparantheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 22. Generate Parentheses 3 | https://leetcode.com/problems/generate-parentheses/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(2^2n), Space: O(n) 10 | vector parentheses; 11 | vector generateParenthesis(int n) 12 | { 13 | int openBrackets = n; 14 | int closeBrackets = n; 15 | string output = ""; 16 | helper(openBrackets, closeBrackets, output); 17 | return parentheses; 18 | } 19 | 20 | void helper(int openBrackets, int closeBrackets, string output) 21 | { 22 | //Base Condition 23 | if (openBrackets == 0 && closeBrackets == 0) 24 | { 25 | parentheses.push_back(output); 26 | return; 27 | } 28 | 29 | if (openBrackets != 0) 30 | { 31 | string output1 = output; 32 | output1.push_back('('); 33 | helper(openBrackets - 1, closeBrackets, output1); 34 | } 35 | if (closeBrackets > openBrackets) 36 | { 37 | string output2 = output; 38 | output2.push_back(')'); 39 | helper(openBrackets, closeBrackets - 1, output2); 40 | } 41 | } 42 | }; -------------------------------------------------------------------------------- /Recursion/lettercasepermutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 784. Letter Case Permutation 3 | https://leetcode.com/problems/letter-case-permutation/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(2^N), Space: O(2^N) 10 | vector allpermutations; 11 | void findPermutations(string s, string permutation) 12 | { 13 | // base case 14 | if (s.size() == 0) 15 | { 16 | allpermutations.push_back(permutation); 17 | return; 18 | } 19 | 20 | if (isalpha(s[0])) 21 | { 22 | string permutation1 = permutation; 23 | string permutation2 = permutation; 24 | 25 | /* 26 | as the question says,you can transform every letter individually to be 27 | lowercase or uppercase to create another string. So, we have 2 choices, 28 | if we encounter an alphabet. 29 | */ 30 | 31 | permutation1.push_back(toupper(s[0])); 32 | permutation2.push_back(tolower(s[0])); 33 | 34 | s.erase(s.begin() + 0); 35 | 36 | findPermutations(s, permutation1); 37 | findPermutations(s, permutation2); 38 | } 39 | else 40 | { 41 | string permutation1 = permutation; 42 | permutation1.push_back(s[0]); 43 | 44 | s.erase(s.begin() + 0); 45 | 46 | findPermutations(s, permutation1); 47 | } 48 | } 49 | 50 | vector letterCasePermutation(string s) 51 | { 52 | string permutation; 53 | findPermutations(s, permutation); 54 | return allpermutations; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Recursion/printnbitbinarynumbershavingmore1than0.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Print N-bit binary numbers having more 1s than 0s 3 | https://practice.geeksforgeeks.org/problems/print-n-bit-binary-numbers-having-more-1s-than-0s0252/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(2^n), Space: O(2^n) 10 | vector result; 11 | vector NBitBinary(int N) 12 | { 13 | string op = ""; 14 | int ones = 0, zeros = 0; 15 | helper(ones, zeros, N, op); 16 | return result; 17 | } 18 | 19 | void helper(int ones, int zeros, int N, string op) 20 | { 21 | if (N == 0) 22 | { 23 | result.push_back(op); 24 | return; 25 | } 26 | 27 | /* 28 | if(ones > zeros){ 29 | string op1 = op; 30 | string op2 = op; 31 | 32 | op1.push_back('1'); 33 | op2.push_back('0'); 34 | helper(ones+1, zeros, N-1, op1); 35 | helper(ones, zeros+1, N-1, op2); 36 | } 37 | else{ 38 | string op1 = op; 39 | op1.push_back('1'); 40 | helper(ones+1, zeros, N-1, op1); 41 | } 42 | */ 43 | //Refactoring the above code 44 | /* 45 | Since we are getting 1s at every branch but for 0s we are getting when 46 | we have 1s > 0s, in that way we have 2 choices, either to choose 1 or 47 | 0. 48 | */ 49 | string op1 = op; 50 | op1.push_back('1'); 51 | helper(ones + 1, zeros, N - 1, op1); 52 | 53 | if (ones > zeros) 54 | { 55 | string op2 = op; 56 | op2.push_back('0'); 57 | helper(ones, zeros + 1, N - 1, op2); 58 | } 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /Recursion/sortastack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort a stack 3 | https://practice.geeksforgeeks.org/problems/sort-a-stack/1 4 | */ 5 | 6 | /*The structure of the class is 7 | class SortedStack{ 8 | public: 9 | stack s; 10 | void sort(); 11 | }; 12 | */ 13 | 14 | /* The below method sorts the stack s 15 | you are required to complete the below method */ 16 | //We can sort the stack in ascending order as well with the 17 | //help of same code 18 | //Time: O(N*N), Space: O(N) 19 | void insert(stack &s, int temp) 20 | { 21 | if (s.size() == 0 || s.top() <= temp) 22 | { 23 | s.push(temp); 24 | return; 25 | } 26 | 27 | int val = s.top(); 28 | s.pop(); 29 | insert(s, temp); 30 | s.push(val); 31 | } 32 | 33 | void sortStack(stack &s) 34 | { 35 | if (s.size() == 1) 36 | return; 37 | int val = s.top(); 38 | s.pop(); 39 | sortStack(s); 40 | insert(s, val); 41 | } 42 | 43 | void SortedStack ::sort() 44 | { 45 | sortStack(s); 46 | } 47 | -------------------------------------------------------------------------------- /Recursion/uniquepathsiii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 980. Unique Paths III 3 | https://leetcode.com/problems/unique-paths-iii/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(3^(m*n)), Space: O(m*n) 10 | int emptyCells = 1; 11 | int uniquePathsIII(vector > &grid) 12 | { 13 | int m = grid.size(); 14 | int n = grid[0].size(); 15 | int startX, startY; 16 | for (int i = 0; i < m; i++) 17 | { 18 | for (int j = 0; j < n; j++) 19 | { 20 | if (grid[i][j] == 1) 21 | startX = i, startY = j; 22 | if (grid[i][j] == 0) 23 | emptyCells++; 24 | } 25 | } 26 | 27 | return helper(grid, startX, startY, m, n, 0); 28 | } 29 | 30 | int helper(vector > &grid, int x, int y, int m, int n, int cell) 31 | { 32 | if (x >= m || y >= n || x < 0 || y < 0 || grid[x][y] == -1) 33 | return 0; 34 | if (grid[x][y] == 3) 35 | return 0; 36 | 37 | // when you hit the ending square 38 | if (grid[x][y] == 2) 39 | { 40 | if (cell == emptyCells) 41 | return 1; 42 | else 43 | return 0; 44 | } 45 | grid[x][y] = 3; // mark it visited 46 | 47 | int count = helper(grid, x + 1, y, m, n, cell + 1) + 48 | helper(grid, x - 1, y, m, n, cell + 1) + 49 | helper(grid, x, y + 1, m, n, cell + 1) + 50 | helper(grid, x, y - 1, m, n, cell + 1); 51 | 52 | grid[x][y] = 0; // mark it univisted 53 | return count; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Searching&Sorting/mergesortedarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 88. Merge Sorted Array 3 | https://leetcode.com/problems/merge-sorted-array/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is to implement the merge part of the merge sort 10 | algorithm. Time: O(N)*/ 11 | void merge(vector &nums1, int m, vector &nums2, int n) 12 | { 13 | vector result; 14 | int i = 0, j = 0; 15 | while (i < m && j < n) 16 | { 17 | if (nums1[i] <= nums2[j]) 18 | { 19 | result.push_back(nums1[i]); 20 | i++; 21 | } 22 | else 23 | { 24 | result.push_back(nums2[j]); 25 | j++; 26 | } 27 | } 28 | 29 | while (i < m) 30 | { 31 | result.push_back(nums1[i]); 32 | i++; 33 | } 34 | while (j < n) 35 | { 36 | result.push_back(nums2[j]); 37 | j++; 38 | } 39 | nums1 = result; 40 | result.clear(); 41 | } 42 | }; -------------------------------------------------------------------------------- /Searching&Sorting/nonoverlappingintervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 435. Non-overlapping Intervals 3 | https://leetcode.com/problems/non-overlapping-intervals/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(NLogN), Space: O(N) 10 | int eraseOverlapIntervals(vector > &intervals) 11 | { 12 | int n = intervals.size(); 13 | if (n == 1) 14 | return 0; 15 | 16 | sort(intervals.begin(), intervals.end(), [](vector &a, vector &b) 17 | { return a[1] < b[1]; }); 18 | 19 | int endOfPrevious = intervals[0][1]; 20 | int removeIntervals = 0; 21 | for (int i = 1; i < n; i++) 22 | { 23 | if (endOfPrevious <= intervals[i][0]) 24 | endOfPrevious = intervals[i][1]; 25 | else 26 | removeIntervals++; 27 | } 28 | return removeIntervals; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /SlidingWindow/countoccurrencesofanagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Count Occurences of Anagrams 3 | https://practice.geeksforgeeks.org/problems/count-occurences-of-anagrams5839/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int search(string pat, string txt) 10 | { 11 | int i = 0, j = 0, k, count, ans = 0; 12 | unordered_map mp; 13 | //store the freq of every element from pat 14 | for (auto c : pat) 15 | { 16 | mp[c]++; 17 | } 18 | count = mp.size(); 19 | k = pat.size(); 20 | while (j < txt.size()) 21 | { 22 | if (mp.find(txt[j]) != mp.end()) 23 | { 24 | mp[txt[j]]--; 25 | if (mp[txt[j]] == 0) 26 | count--; 27 | } 28 | if (j - i + 1 < k) 29 | j++; 30 | else if (j - i + 1 == k) 31 | { 32 | if (count == 0) 33 | ans++; 34 | if (mp.find(txt[i]) != mp.end()) 35 | { 36 | mp[txt[i]]++; 37 | if (mp[txt[i]] == 1) 38 | count++; 39 | } 40 | i++; 41 | j++; 42 | } 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /SlidingWindow/findallanagramsinastring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 438. Find All Anagrams in a String 3 | https://leetcode.com/problems/find-all-anagrams-in-a-string/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N), Space: O(N) 10 | vector findAnagrams(string s, string p) 11 | { 12 | int k = p.size(); 13 | unordered_map mp; 14 | for (auto c : p) 15 | mp[c]++; 16 | 17 | vector result; 18 | 19 | //stores the number of distinct characters of anagram with their frequencies 20 | int count = mp.size(); 21 | 22 | int i = 0, j = 0; 23 | while (j < s.size()) 24 | { 25 | if (mp.find(s[j]) != mp.end()) 26 | { 27 | mp[s[j]]--; 28 | if (mp[s[j]] == 0) 29 | count--; 30 | } 31 | 32 | if (j - i + 1 < k) 33 | j++; 34 | else if (j - i + 1 == k) 35 | { 36 | //if we hit the window of k size just store the i value, ofc that is 37 | //starting index of the anagram 38 | if (count == 0) 39 | result.push_back(i); 40 | if (mp.find(s[i]) != mp.end()) 41 | { 42 | mp[s[i]]++; 43 | if (mp[s[i]] == 1) 44 | count++; 45 | } 46 | i++; 47 | j++; 48 | } 49 | } 50 | return result; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /SlidingWindow/firstnegativeineverywindowofsizek.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First negative integer in every window of size k 3 | https://practice.geeksforgeeks.org/problems/first-negative-integer-in-every-window-of-size-k3345/1# 4 | */ 5 | 6 | vector printFirstNegativeInteger(long long int A[], long long int N, long long int K) 7 | { 8 | 9 | vector result; 10 | queue q; 11 | int i = 0, j = 0; 12 | 13 | while (j < N) 14 | { 15 | if (A[j] < 0) 16 | q.push(A[j]); 17 | if (j - i + 1 < K) 18 | j++; 19 | else if (j - i + 1 == K) 20 | { 21 | if (q.size() == 0) 22 | result.push_back(0); 23 | else 24 | { 25 | result.push_back(q.front()); 26 | if (A[i] == q.front()) 27 | q.pop(); 28 | } 29 | i++; 30 | j++; 31 | } 32 | } 33 | return result; 34 | } -------------------------------------------------------------------------------- /SlidingWindow/longestkuniquecharacterssubstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest K unique characters substring 3 | https://practice.geeksforgeeks.org/problems/longest-k-unique-characters-substring0853/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N), Space: O(N) 10 | int longestKSubstr(string s, int k) 11 | { 12 | int i = 0, j = 0, result = -1; 13 | unordered_map mp; 14 | 15 | while (j < s.length()) 16 | { 17 | //calculation I 18 | mp[s[j]]++; 19 | 20 | if (mp.size() < k) 21 | j++; 22 | else if (mp.size() == k) 23 | { 24 | //calculation II 25 | result = max(result, j - i + 1); 26 | j++; 27 | } 28 | else if (mp.size() > k) 29 | { 30 | //calculation III 31 | while (mp.size() > k) 32 | { 33 | mp[s[i]]--; 34 | 35 | if (mp[s[i]] == 0) 36 | mp.erase(s[i]); 37 | i++; 38 | } 39 | j++; 40 | } 41 | } 42 | return result; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /SlidingWindow/longestsubarraywithsumk.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Sub-Array with Sum K 3 | https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int lenOfLongSubarr(int A[], int N, int K) 10 | { 11 | int i = 0, j = 0, sum = 0, ans = 0; 12 | 13 | while (j < N) 14 | { 15 | sum += A[j]; 16 | //here we have to all the 3 cases because it is a variable size S.W. 17 | if (sum < K) 18 | j++; 19 | else if (sum == K) 20 | { 21 | //if we found that sum == k then calulate the length of the 22 | //window and update it 23 | ans = max(ans, (j - i) + 1); 24 | j++; 25 | } 26 | else if (sum > K) 27 | { 28 | while (sum > K) 29 | { 30 | sum = sum - A[i]; 31 | i++; 32 | 33 | if (sum == K) 34 | { 35 | ans = max(ans, (j - i) + 1); 36 | } 37 | } 38 | j++; 39 | } 40 | } 41 | return ans; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /SlidingWindow/longestsubstringwithoutrepeatingcharacters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 3. Longest Substring Without Repeating Characters 3 | https://leetcode.com/problems/longest-substring-without-repeating-characters/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N), Space: O(N) 10 | int lengthOfLongestSubstring(string s) 11 | { 12 | if (s.size() == 0) 13 | return 0; 14 | 15 | int i = 0, j = 0, result = INT_MIN; 16 | unordered_map mp; 17 | while (j < s.size()) 18 | { 19 | 20 | //calculation I 21 | mp[s[j]]++; 22 | 23 | if (mp.size() < j - i + 1) 24 | { 25 | while (mp.size() < j - i + 1) 26 | { 27 | mp[s[i]]--; 28 | if (mp[s[i]] == 0) 29 | mp.erase(s[i]); 30 | i++; 31 | } 32 | j++; 33 | } 34 | else if (mp.size() == j - i + 1) 35 | { 36 | //calculation II 37 | result = max(result, j - i + 1); 38 | j++; 39 | } 40 | /*mp.size() will never be more than j-i+1 becaause mp stores unique chars and 41 | atmost it can store the entire window*/ 42 | } 43 | return result; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /SlidingWindow/maximumerasurevalue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1695. Maximum Erasure Value 3 | https://leetcode.com/problems/maximum-erasure-value/ 4 | */ 5 | 6 | /* 7 | This question says erase the subarray containing unique elements. And the score you get is 8 | sum of its elements. Basically this problem reduced to finding the subarray having all 9 | unique elements and also having maximum sum. 10 | */ 11 | class Solution 12 | { 13 | public: 14 | //Time: O(N), Space: O(N) 15 | int maximumUniqueSubarray(vector &nums) 16 | { 17 | int i = 0, j = 0; 18 | unordered_map mp; 19 | int result = INT_MIN, sum = 0; 20 | 21 | while (j < nums.size()) 22 | { 23 | //Calculation I 24 | sum += nums[j]; 25 | mp[nums[j]]++; 26 | if (mp.size() < j - i + 1) 27 | { 28 | while (mp.size() < j - i + 1) 29 | { 30 | sum = sum - nums[i]; 31 | mp[nums[i]]--; 32 | 33 | if (mp[nums[i]] == 0) 34 | mp.erase(nums[i]); 35 | i++; 36 | } 37 | j++; 38 | } 39 | else if (mp.size() == j - i + 1) 40 | { 41 | //Calculation II 42 | result = max(result, sum); 43 | j++; 44 | } 45 | } 46 | return result; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /SlidingWindow/maximumofallsubarraysofsizek.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum of all subarrays of size k 3 | https://practice.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Function to find maximum of each subarray of size k. 10 | vector max_of_subarrays(int *nums, int n, int k) 11 | { 12 | vector ans; 13 | deque q; 14 | int i = 0, j = 0; 15 | 16 | while (j < n) 17 | { 18 | //calculation 1 19 | while (q.size() > 0 && q.back() < nums[j]) 20 | q.pop_back(); 21 | q.push_back(nums[j]); 22 | 23 | if (j - i + 1 < k) 24 | j++; 25 | else if (j - i + 1 == k) 26 | { 27 | //store the maximum element of that window 28 | //maximum element will always be in front 29 | ans.push_back(q.front()); 30 | //before sliding the window if the nums[i] and q.front() 31 | //are equal then remove the element, if not don't remove it 32 | if (q.front() == nums[i]) 33 | q.pop_front(); 34 | 35 | i++; 36 | j++; 37 | } 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /SlidingWindow/maximumsumsubarrayofsizek.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Max Sum Subarray of size K 3 | https://practice.geeksforgeeks.org/problems/max-sum-subarray-of-size-k5313/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | int maximumSumSubarray(int K, vector &Arr, int N) 10 | { 11 | int i = 0, j = 0, sum = 0, mx = INT_MIN; 12 | 13 | while (j < N) 14 | { 15 | sum += Arr[j]; 16 | if (j - i + 1 < K) 17 | { 18 | j++; 19 | } 20 | else if (j - i + 1 == K) 21 | { 22 | mx = max(mx, sum); 23 | sum = sum - Arr[i]; 24 | i++; 25 | j++; 26 | } 27 | } 28 | return mx; 29 | } 30 | }; -------------------------------------------------------------------------------- /SlidingWindow/numberofsubarraysofsizekavggreaterthanorequaltothreshold.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold 3 | https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N), Space: O(N) 10 | int numOfSubarrays(vector &arr, int k, int threshold) 11 | { 12 | int i = 0, j = 0, sum = 0, count = 0; 13 | 14 | while (j < arr.size()) 15 | { 16 | //calculation I 17 | sum += arr[j]; 18 | if (j - i + 1 < k) 19 | j++; 20 | else if (j - i + 1 == k) 21 | { 22 | //calculation II 23 | //find the answer and slide the window 24 | if (sum / k >= threshold) 25 | { 26 | count++; 27 | } 28 | sum = sum - arr[i]; 29 | i++; 30 | j++; 31 | } 32 | } 33 | return count; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /SlidingWindow/slidingwindowmaximum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 239. Sliding Window Maximum 3 | https://leetcode.com/problems/sliding-window-maximum/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(N), Space: O(M) 10 | vector maxSlidingWindow(vector &nums, int k) 11 | { 12 | //Base case 13 | if (k >= nums.size()) 14 | { 15 | return {*max_element(nums.begin(), nums.end())}; 16 | } 17 | 18 | int i = 0, j = 0; 19 | vector result; 20 | deque dq; 21 | 22 | while (j < nums.size()) 23 | { 24 | //Calculation I 25 | /* 26 | we are removing those elements from the deque which are smaller than the 27 | upcoming element 28 | */ 29 | while (dq.size() > 0 && dq.back() < nums[j]) 30 | { 31 | dq.pop_back(); 32 | } 33 | dq.push_back(nums[j]); 34 | 35 | if (j - i + 1 < k) 36 | j++; 37 | else if (j - i + 1 == k) 38 | { 39 | //Calculation II 40 | /* 41 | our maximum element for any window of size k will be in front of the deque 42 | */ 43 | result.push_back(dq.front()); 44 | if (dq.front() == nums[i]) 45 | { 46 | dq.pop_front(); 47 | } 48 | i++; 49 | j++; 50 | } 51 | } 52 | return result; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /SlidingWindow/subarraywithkdifferentintegers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 992. Subarrays with K Different Integers 3 | https://leetcode.com/problems/subarrays-with-k-different-integers/ 4 | */ 5 | 6 | /* 7 | Since the question says that we need exactly k elements so we need to remove less than k 8 | elements. 9 | */ 10 | class Solution 11 | { 12 | public: 13 | //Time: O(N), Space: O(N) 14 | int helper(vector &nums, int k) 15 | { 16 | int i = 0, j = 0; 17 | unordered_map mp; 18 | int count = 0; 19 | while (j < nums.size()) 20 | { 21 | mp[nums[j]]++; 22 | 23 | if (mp.size() <= k) 24 | { 25 | count += j - i + 1; 26 | j++; 27 | } 28 | else if (mp.size() > k) 29 | { 30 | while (mp.size() > k) 31 | { 32 | mp[nums[i]]--; 33 | if (mp[nums[i]] == 0) 34 | mp.erase(nums[i]); 35 | i++; 36 | } 37 | count += j - i + 1; 38 | j++; 39 | } 40 | } 41 | return count; 42 | } 43 | int subarraysWithKDistinct(vector &nums, int k) 44 | { 45 | return helper(nums, k) - helper(nums, k - 1); 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Stack&Queues/asteroidcollision.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 735. Asteroid Collision 3 | https://leetcode.com/problems/asteroid-collision/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is put the first value into the stack and after that 10 | for the next values check the top values for all the three possibilities. 11 | Time: O(N)*/ 12 | vector asteroidCollision(vector &asteroids) 13 | { 14 | stack s; 15 | int i = 0; 16 | while (i < asteroids.size()) 17 | { 18 | if (s.empty()) 19 | { 20 | s.push(asteroids[i++]); 21 | } 22 | else 23 | { 24 | if (s.top() > 0 && asteroids[i] < 0) 25 | { 26 | if (s.top() > abs(asteroids[i])) 27 | i++; 28 | else if (s.top() < abs(asteroids[i])) 29 | s.pop(); 30 | else 31 | { 32 | i++; 33 | s.pop(); 34 | } 35 | } 36 | else 37 | { 38 | s.push(asteroids[i++]); 39 | } 40 | } 41 | } 42 | 43 | vector result(s.size(), 0); 44 | for (int i = s.size() - 1; i >= 0; i--) 45 | { 46 | result[i] = s.top(); 47 | s.pop(); 48 | } 49 | return result; 50 | } 51 | }; -------------------------------------------------------------------------------- /Stack&Queues/evaluationofpostfixexpression.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Evaluation of Postfix Expression 3 | https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1# 4 | * 5 | 6 | 7 | class Solution 8 | { 9 | public: 10 | // The main function that returns value of a given postfix expression 11 | /*this is the standard problem, so better you learn by yourself. 12 | Time: O(N)*/ 13 | int evaluatePostfix(string S) 14 | { 15 | stack Stack; 16 | 17 | for (int i = 0; i < S.size(); i++) 18 | { 19 | //if it encounters the digit then push it to the stack 20 | if (isdigit(S[i])) 21 | { 22 | Stack.push(S[i] - '0'); 23 | } 24 | else 25 | { 26 | //if it encounters the operand then pop above two values 27 | //and apply operations on them and again push it to the stack 28 | int v1 = Stack.top(); 29 | Stack.pop(); 30 | int v2 = Stack.top(); 31 | Stack.pop(); 32 | 33 | switch (S[i]) 34 | { 35 | case '+': 36 | Stack.push(v2 + v1); 37 | break; 38 | case '-': 39 | Stack.push(v2 - v1); 40 | break; 41 | case '*': 42 | Stack.push(v2 * v1); 43 | break; 44 | case '/': 45 | Stack.push(v2 / v1); 46 | break; 47 | } 48 | } 49 | } 50 | return Stack.top(); 51 | } 52 | }; -------------------------------------------------------------------------------- /Stack&Queues/firstnegativeintegerineverywindowofsizek.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First negative integer in every window of size k 3 | https://practice.geeksforgeeks.org/problems/first-negative-integer-in-every-window-of-size-k/0# 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | //code 13 | /*the basic idea is to use queue, take the first negative number from 14 | the first k values from the subarrays and then start loop from k to n 15 | and delete all the previous values from the queue and find rest of the 16 | values Time: O(N)*/ 17 | int t; 18 | cin >> t; 19 | while (t--) 20 | { 21 | int n; 22 | cin >> n; 23 | 24 | int a[n]; 25 | for (int i = 0; i < n; i++) 26 | { 27 | cin >> a[i]; 28 | } 29 | int k; 30 | cin >> k; 31 | 32 | queue q; 33 | for (int i = 0; i < k; i++) 34 | { 35 | if (a[i] < 0) 36 | { 37 | q.push(i); 38 | } 39 | } 40 | 41 | if (!q.empty()) 42 | cout << a[q.front()] << " "; 43 | else 44 | cout << "0" 45 | << " "; 46 | 47 | for (int i = k; i < n; i++) 48 | { 49 | 50 | while (!q.empty() && q.front() <= (i - k)) 51 | q.pop(); 52 | 53 | if (a[i] < 0) 54 | q.push(i); 55 | 56 | if (q.empty()) 57 | cout << "0" 58 | << " "; 59 | else 60 | cout << a[q.front()] << " "; 61 | } 62 | cout << endl; 63 | } 64 | return 0; 65 | } -------------------------------------------------------------------------------- /Stack&Queues/gamewithstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Game with String 3 | https://practice.geeksforgeeks.org/problems/game-with-string4100/1# 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is to have count of each characters 10 | use pq(max-heap) to store the count, then pop the values 11 | k times after that at last pop every values and add the square 12 | of it. Time: O(N), Space: O(N)*/ 13 | int minValue(string s, int k) 14 | { 15 | // code here 16 | if (k >= s.size()) 17 | return 0; 18 | unordered_map mp; 19 | 20 | for (int i = 0; i < s.size(); i++) 21 | { 22 | mp[s[i]]++; 23 | } 24 | 25 | priority_queue pq; 26 | 27 | for (auto i : mp) 28 | { 29 | pq.push(i.second); 30 | } 31 | 32 | while (k--) 33 | { 34 | int x = pq.top(); 35 | pq.pop(); 36 | x--; 37 | pq.push(x); 38 | } 39 | 40 | int result = 0; 41 | while (!pq.empty()) 42 | { 43 | int x = pq.top(); 44 | pq.pop(); 45 | result += x * x; 46 | } 47 | 48 | return result; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Stack&Queues/implementqueueusingstack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 232. Implement Queue using Stacks 3 | https://leetcode.com/problems/implement-queue-using-stacks/ 4 | */ 5 | 6 | class MyQueue 7 | { 8 | public: 9 | /*here the question says to use 2 stacks, 10 | the dequeue operation is costly here. 11 | Time: Push O(1), Pop O(N), Space: O(N)*/ 12 | /** Initialize your data structure here. */ 13 | stack s1, s2; 14 | MyQueue() 15 | { 16 | } 17 | 18 | /** Push element x to the back of queue. */ 19 | void push(int x) 20 | { 21 | s1.push(x); 22 | } 23 | 24 | /** Removes the element from in front of queue and returns that element. */ 25 | int pop() 26 | { 27 | int top = peek(); 28 | s2.pop(); 29 | return top; 30 | } 31 | 32 | /** Get the front element. */ 33 | int peek() 34 | { 35 | if (s2.empty()) 36 | { 37 | while (!s1.empty()) 38 | { 39 | s2.push(s1.top()); 40 | s1.pop(); 41 | } 42 | } 43 | return s2.top(); 44 | } 45 | 46 | /** Returns whether the queue is empty. */ 47 | bool empty() 48 | { 49 | return s1.empty() && s2.empty(); 50 | } 51 | }; 52 | 53 | /** 54 | * Your MyQueue object will be instantiated and called as such: 55 | * MyQueue* obj = new MyQueue(); 56 | * obj->push(x); 57 | * int param_2 = obj->pop(); 58 | * int param_3 = obj->peek(); 59 | * bool param_4 = obj->empty(); 60 | */ -------------------------------------------------------------------------------- /Stack&Queues/implementstackusingqueues.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 225. Implement Stack using Queues 3 | https://leetcode.com/problems/implement-stack-using-queues/ 4 | */ 5 | 6 | class MyStack 7 | { 8 | public: 9 | /*Time: Push O(N), Pop O(1), Space: O(1)*/ 10 | /** Initialize your data structure here. */ 11 | queue q1, q2; 12 | MyStack() 13 | { 14 | } 15 | 16 | /** Push element x onto stack. */ 17 | void push(int x) 18 | { 19 | q2.push(x); 20 | while (!q1.empty()) 21 | { 22 | q2.push(q1.front()); 23 | q1.pop(); 24 | } 25 | swap(q1, q2); 26 | } 27 | 28 | /** Removes the element on top of the stack and returns that element. */ 29 | int pop() 30 | { 31 | int temp = top(); 32 | q1.pop(); 33 | return temp; 34 | } 35 | 36 | /** Get the top element. */ 37 | int top() 38 | { 39 | return q1.front(); 40 | } 41 | 42 | /** Returns whether the stack is empty. */ 43 | bool empty() 44 | { 45 | return q1.empty(); 46 | } 47 | }; 48 | 49 | /** 50 | * Your MyStack object will be instantiated and called as such: 51 | * MyStack* obj = new MyStack(); 52 | * obj->push(x); 53 | * int param_2 = obj->pop(); 54 | * int param_3 = obj->top(); 55 | * bool param_4 = obj->empty(); 56 | */ -------------------------------------------------------------------------------- /Stack&Queues/minstack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 155. Min Stack 3 | https://leetcode.com/problems/min-stack/ 4 | */ 5 | 6 | /* 7 | This question was pretty tricky to me. I missed one thing that, I need to keep track 8 | of the min till every number which is pushed in the stack. 9 | 10 | Whenever a number gets popped from stack the minimum changes. 11 | 12 | So, We designed the stack in such a way that we can track minimum till every number. 13 | */ 14 | 15 | class MinStack 16 | { 17 | public: 18 | // Time: O(N), Space: O(N) 19 | vector> v; 20 | MinStack() 21 | { 22 | } 23 | 24 | void push(int val) 25 | { 26 | if (v.size() == 0) 27 | v.push_back({val, val}); 28 | else 29 | v.push_back({val, min(v[v.size() - 1].second, val)}); 30 | } 31 | 32 | void pop() 33 | { 34 | v.pop_back(); 35 | } 36 | 37 | int top() 38 | { 39 | return v[v.size() - 1].first; 40 | } 41 | 42 | int getMin() 43 | { 44 | return v[v.size() - 1].second; 45 | } 46 | }; 47 | 48 | /** 49 | * Your MinStack object will be instantiated and called as such: 50 | * MinStack* obj = new MinStack(); 51 | * obj->push(val); 52 | * obj->pop(); 53 | * int param_3 = obj->top(); 54 | * int param_4 = obj->getMin(); 55 | */ 56 | -------------------------------------------------------------------------------- /Stack&Queues/queuereversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Queue Reversal 3 | https://practice.geeksforgeeks.org/problems/queue-reversal/1# 4 | */ 5 | 6 | /*the basic idea is to recurse the queue and at last 7 | start pushing the value. Time: O(N)*/ 8 | void helper(queue &q) 9 | { 10 | if (q.empty()) 11 | return; 12 | 13 | int temp = q.front(); 14 | q.pop(); 15 | 16 | helper(q); 17 | q.push(temp); 18 | } 19 | 20 | queue rev(queue q) 21 | { 22 | // add code here. 23 | helper(q); 24 | return q; 25 | } 26 | -------------------------------------------------------------------------------- /Stack&Queues/reversefirstkelementsofqueue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse First K elements of Queue 3 | https://practice.geeksforgeeks.org/problems/reverse-first-k-elements-of-queue/1# 4 | */ 5 | 6 | /*the basic idea is to pop the k values from q and 7 | push to the stack and pop again from the s push to the temp 8 | and at the end push rest of values from q to temp 9 | Time: O(N), Space: O(N)*/ 10 | queue modifyQueue(queue q, int k) 11 | { 12 | //add code here. 13 | stack s; 14 | queue temp; 15 | 16 | while (k--) 17 | { 18 | int x = q.front(); 19 | q.pop(); 20 | s.push(x); 21 | } 22 | 23 | while (!s.empty()) 24 | { 25 | int x = s.top(); 26 | s.pop(); 27 | temp.push(x); 28 | } 29 | 30 | while (!q.empty()) 31 | { 32 | int x = q.front(); 33 | q.pop(); 34 | temp.push(x); 35 | } 36 | return temp; 37 | } -------------------------------------------------------------------------------- /Stack&Queues/reversesubstringbetweeneachpairofparantheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 1190. Reverse Substrings Between Each Pair of Parentheses 3 | https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /*the basic idea is use stack and when you get '(' push the index of it 10 | and when you get ')' pop the corresponding top value from stack and reverse 11 | the string between those indexes and do this repeatedly. Time: O(N^2) Space: O(N)*/ 12 | string reverseParentheses(string s) 13 | { 14 | stack Stack; 15 | 16 | for (int i = 0; i < s.size(); i++) 17 | { 18 | if (s[i] == '(') 19 | Stack.push(i); 20 | else if (s[i] == ')') 21 | { 22 | reverse(s.begin() + Stack.top(), s.begin() + i); 23 | Stack.pop(); 24 | } 25 | } 26 | 27 | string result = ""; 28 | for (auto i : s) 29 | { 30 | if (i != '(' && i != ')') 31 | { 32 | result += i; 33 | } 34 | } 35 | return result; 36 | } 37 | }; -------------------------------------------------------------------------------- /Stack&Queues/simplifypath.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 71. Simplify Path 3 | https://leetcode.com/problems/simplify-path/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | // Time: O(N), Space: O(N) 10 | string simplifyPath(string path) 11 | { 12 | stack st; 13 | int n = path.size(); 14 | if (path[path.size() - 1] != '/') 15 | path.push_back('/'); 16 | 17 | string temp = ""; 18 | for (int i = 0; i < path.size(); i++) 19 | { 20 | if (path[i] == '/') 21 | { 22 | if (temp == "" || temp == ".") 23 | { 24 | } // do nothing 25 | else if (temp == "..") 26 | { 27 | if (st.size() > 0) 28 | st.pop(); 29 | } 30 | else 31 | st.push(temp); 32 | temp = ""; 33 | } 34 | else 35 | { 36 | temp.push_back(path[i]); 37 | } 38 | } 39 | 40 | string res = ""; 41 | while (!st.empty()) 42 | { 43 | res = "/" + st.top() + res; 44 | st.pop(); 45 | } 46 | if (res == "") 47 | return "/"; 48 | return res; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Stack&Queues/sortastack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort a stack 3 | https://practice.geeksforgeeks.org/problems/sort-a-stack/1# 4 | */ 5 | 6 | /*The structure of the class is 7 | class SortedStack{ 8 | public: 9 | stack s; 10 | void sort(); 11 | }; 12 | */ 13 | 14 | /* The below method sorts the stack s 15 | you are required to complete the below method */ 16 | 17 | /*the basic idea constantly pop the element from stack and 18 | then call insert function to insert it. For insertion check if the 19 | stack is empty or not of if the top element in smaller than the element 20 | which is going to insert. Time: O(N*N), Space: O(N) 21 | I've used recursion just to explore the concept of recursion, 22 | otherwise we can use any method*/ 23 | 24 | void stackInsert(stack &s, int ele) 25 | { 26 | if (s.empty() || ele > s.top()) 27 | { 28 | s.push(ele); 29 | } 30 | else 31 | { 32 | int temp = s.top(); 33 | s.pop(); 34 | stackInsert(s, ele); 35 | s.push(temp); 36 | } 37 | } 38 | 39 | void SortedStack ::sort() 40 | { 41 | //Your code here 42 | if (!s.empty()) 43 | { 44 | int temp = s.top(); 45 | s.pop(); 46 | SortedStack::sort(); 47 | stackInsert(s, temp); 48 | } 49 | } -------------------------------------------------------------------------------- /Stack&Queues/validparanthesis.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 20. Valid Parentheses 3 | https://leetcode.com/problems/valid-parentheses/ 4 | */ 5 | 6 | //The basic idea plzz read the infix to postfix conversion application from stack 7 | //then this question is a piece of cake for you 8 | 9 | // I was able to solve this in 15 mins, 26 sec. 10 | class Solution 11 | { 12 | public: 13 | // Time: O(N), Space: O(N) 14 | bool isValid(string s) 15 | { 16 | 17 | if (s.size() == 0) 18 | return true; 19 | if (s.size() == 1) 20 | return false; 21 | 22 | stack st; 23 | 24 | for (auto c : s) 25 | { 26 | if (c == ')' || c == ']' || c == '}') 27 | { 28 | if (st.empty()) 29 | return false; 30 | if (st.top() != '(' && c == ')') 31 | return false; 32 | if (st.top() != '{' && c == '}') 33 | return false; 34 | if (st.top() != '[' && c == ']') 35 | return false; 36 | st.pop(); 37 | } 38 | else 39 | { 40 | st.push(c); 41 | } 42 | } 43 | 44 | if (st.empty()) 45 | return true; 46 | return false; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /String/addstrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 415. Add Strings 3 | https://leetcode.com/problems/add-strings/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | string addStrings(string num1, string num2) 10 | { 11 | string result = ""; 12 | int len1 = num1.length() - 1; 13 | int len2 = num2.length() - 1; 14 | int carry = 0; 15 | 16 | while (len1 >= 0 || len2 >= 0) 17 | { 18 | //getting the actual value to add the string according to ascii table 19 | int x1 = len1 >= 0 ? num1[len1] - '0' : 0; 20 | int x2 = len2 >= 0 ? num2[len2] - '0' : 0; 21 | 22 | //first calculate the overall sum and then find the result and carry from it 23 | int sum = x1 + x2 + carry; 24 | carry = sum / 10; //to get the carry 25 | 26 | sum = sum % 10; //to get the actual last value 27 | string temp = to_string(sum); 28 | result += temp; 29 | len1--; 30 | len2--; 31 | } 32 | 33 | if (carry) 34 | { 35 | string temp = to_string(carry); 36 | result += temp; 37 | } 38 | reverse(result.begin(), result.end()); 39 | return result; 40 | } 41 | }; -------------------------------------------------------------------------------- /String/boardgameproblem.cpp: -------------------------------------------------------------------------------- 1 | //Cpp prgram for count the number of paths possible from start point to end point in gameboard 2 | 3 | #include 4 | using namespace std; 5 | 6 | int countPath(int start, int end){ 7 | if(start == end) return 1; 8 | 9 | if(start > end) return 0; 10 | 11 | int count = 0; 12 | for(int i=0; i<=6; i++){ 13 | count += countPath(start+i, end); 14 | } 15 | return count; 16 | } 17 | 18 | 19 | int main(){ 20 | 21 | cout< indices; 37 | 38 | for(int i=0; i &word1, vector &word2) 11 | { 12 | string Word1 = ""; 13 | string Word2 = ""; 14 | 15 | for (auto item : word1) 16 | { 17 | Word1 += item; 18 | } 19 | 20 | for (auto item : word2) 21 | { 22 | Word2 += item; 23 | } 24 | //cout< A*26^1 + B*26^2, Now if you will calculate this you will get the exact column 10 | number. Similary we can do for all the strings. 11 | */ 12 | class Solution 13 | { 14 | public: 15 | //Time: O(N), Space: O(1) 16 | int titleToNumber(string columnTitle) 17 | { 18 | int result = 0; 19 | for (auto c : columnTitle) 20 | { 21 | int n = c - 'A' + 1; 22 | result = result * 26 + n; 23 | } 24 | return result; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /String/groupanagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 49. Group Anagrams 3 | https://leetcode.com/problems/group-anagrams/ 4 | */ 5 | 6 | /* 7 | It was very simple implementation of hashing. Now, new concepts I learned in this 8 | question. 9 | I was able to do it in 7 mins. 59 sec. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | // Time: O(n * m.logm + n), Space: O(n) 16 | vector> groupAnagrams(vector &strs) 17 | { 18 | // base case 19 | if (strs.size() == 1) 20 | { 21 | if (strs[0] == "") 22 | return {{""}}; 23 | else 24 | return {{strs[0]}}; 25 | } 26 | 27 | unordered_map> mp; 28 | for (auto s : strs) 29 | { 30 | string t = s; 31 | sort(t.begin(), t.end()); 32 | mp[t].push_back(s); 33 | } 34 | 35 | vector> result; 36 | for (auto &[k, v] : mp) 37 | { 38 | result.push_back(v); 39 | } 40 | return result; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /String/longestcommonprefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode 14. Longest Common Prefix 3 | https://leetcode.com/problems/longest-common-prefix/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | string longestCommonPrefix(vector &strs) 10 | { 11 | if (strs.size() == 0) 12 | return ""; 13 | 14 | //string result=""; 15 | 16 | for (int i = 0; i < strs[0].size(); i++) 17 | { 18 | char c = strs[0].at(i); 19 | 20 | for (int j = 1; j < strs.size(); j++) 21 | { 22 | if (i == strs[j].length() || strs[j].at(i) != c) 23 | return strs[0].substr(0, i); 24 | } 25 | } 26 | return strs[0]; 27 | } 28 | }; -------------------------------------------------------------------------------- /String/longestpalindromicsubstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 5. Longest Palindromic Substring 3 | https://leetcode.com/problems/longest-palindromic-substring/ 4 | */ 5 | 6 | /* 7 | The first intuition is to solve this via Longest Common Substring, but unfortunately, 8 | this is not the right way of doing it. 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | //Time: O(N^2) 15 | string longestPalindrome(string s) 16 | { 17 | int start = 0; 18 | int end = 0; 19 | 20 | //The idea is take every character from the string get traverse 21 | //backward and forward to get and compare the character and the length simultaneously 22 | for (int i = 0; i < s.length(); i++) 23 | { 24 | int len1 = expandFromMiddle(s, i, i); //racecar i.e. when the string is of length odd 25 | int len2 = expandFromMiddle(s, i, i + 1); //aabbaa i.e.when the string is of length even 26 | 27 | int maxLength = max(len1, len2); 28 | 29 | if (maxLength > end - start) 30 | { 31 | start = i - ((maxLength - 1) / 2); 32 | end = i + (maxLength / 2); 33 | } 34 | } 35 | return (s.substr(start, end - start + 1)); 36 | } 37 | 38 | // utility function to check whether the string is palindrome or not 39 | // but it is expanding from the middle of the string 40 | int expandFromMiddle(string s, int left, int right) 41 | { 42 | while (left >= 0 && right < s.length() && s[left] == s[right]) 43 | { 44 | left--; 45 | right++; 46 | } 47 | return (right - left - 1); 48 | } 49 | }; -------------------------------------------------------------------------------- /String/minimumaddtomakeparanthesisvalid.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 921. Minimum Add to Make Parentheses Valid 3 | https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 4 | */ 5 | //The idea is plzz learn the infix to postfix conversion application of stack then this question is piece of cake for you 6 | 7 | class Solution 8 | { 9 | public: 10 | int minAddToMakeValid(string S) 11 | { 12 | //with stack 13 | //O(n) 14 | stack st; 15 | 16 | for (int i = 0; i < S.length(); i++) 17 | { 18 | if (S[i] == '(') 19 | { 20 | st.push(S[i]); 21 | } 22 | else if (st.size() > 0 && st.top() == '(') 23 | st.pop(); 24 | else 25 | st.push(S[i]); 26 | } 27 | 28 | return st.size(); 29 | 30 | //without stack 31 | //O(n) 32 | int result = 0, balance = 0; 33 | 34 | for(int i=0; i 18 | #include 19 | using namespace std; 20 | 21 | void permutation(string s, string ans){ 22 | 23 | if(s.length() == 0){ 24 | cout< &s) 11 | { 12 | int size = s.size(); 13 | for (int i = 0; i < size / 2; i++) 14 | { 15 | int temp = s[i]; 16 | s[i] = s[size - i - 1]; 17 | s[size - i - 1] = temp; 18 | } 19 | } 20 | }; -------------------------------------------------------------------------------- /String/rotatestring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 796. Rotate String 3 | https://leetcode.com/problems/rotate-string/ 4 | */ 5 | 6 | //Solution 1 7 | class Solution 8 | { 9 | public: 10 | //Time: O(n) 11 | bool rotateString(string A, string B) 12 | { 13 | int alength = A.length(); 14 | int blength = B.length(); 15 | 16 | if (alength != blength) 17 | return false; 18 | if (alength == 0) 19 | return true; 20 | 21 | //compare the A till it is equal to the B and add character 22 | //to the last and simultaneously delete from the front 23 | int i=alength; 24 | while(A != B){ 25 | A += A[0]; 26 | A.erase(A.begin()); 27 | i--; 28 | if(i == 0) return 0; 29 | } 30 | return 1; 31 | } 32 | }; 33 | 34 | //Solution 2 35 | class Solution 36 | { 37 | public: 38 | bool rotateString(string A, string B) 39 | { 40 | int alength = A.length(); 41 | int blength = B.length(); 42 | 43 | if (alength != blength) 44 | return false; 45 | if (alength == 0) 46 | return true; 47 | 48 | //basically add the string A with A then find B as a substring 49 | A = A + A; 50 | if (A.find(B) != string::npos) 51 | return 1; 52 | return 0; 53 | } 54 | }; -------------------------------------------------------------------------------- /Trie/distinctsubstrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | BinarySearch Question 939. Distinct Substrings 3 | https://binarysearch.com/problems/Distinct-Substrings 4 | */ 5 | 6 | // Trie Data Structure 7 | struct Node 8 | { 9 | Node *links[26]; 10 | 11 | bool containsKey(char ch) 12 | { 13 | return links[ch - 'a']; 14 | } 15 | 16 | void put(char ch, Node *node) 17 | { 18 | links[ch - 'a'] = node; 19 | } 20 | 21 | Node *get(char ch) 22 | { 23 | return links[ch - 'a']; 24 | } 25 | }; 26 | 27 | int solve(string s) 28 | { 29 | int count = 0; 30 | Node *root = new Node(); 31 | 32 | for (int i = 0; i < s.size(); i++) 33 | { 34 | Node *node = root; 35 | 36 | for (int j = i; j < s.size(); j++) 37 | { 38 | if (!node->containsKey(s[j])) 39 | { 40 | count++; 41 | node->put(s[j], new Node()); 42 | } 43 | node = node->get(s[j]); 44 | } 45 | } 46 | return count; 47 | } 48 | -------------------------------------------------------------------------------- /Two Pointers/3sumclosest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 16. 3Sum Closest 3 | https://leetcode.com/problems/3sum-closest/ 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | //Time: O(nlogn + n^2), Space: O(1) 10 | int threeSumClosest(vector &nums, int target) 11 | { 12 | int mindiff = INT_MAX; 13 | int result = 0; 14 | sort(nums.begin(), nums.end()); 15 | 16 | for (int i = 0; i < nums.size(); i++) 17 | { 18 | int left = i + 1; 19 | int right = nums.size() - 1; 20 | int x = nums[i]; 21 | 22 | while (left < right) 23 | { 24 | int sum = x + nums[left] + nums[right]; 25 | 26 | if (abs(target - sum) < abs(mindiff)) 27 | { 28 | mindiff = abs(target - sum); 29 | result = sum; 30 | } 31 | else if (sum < target) 32 | left++; 33 | else 34 | right--; 35 | if (target == sum) 36 | return result; 37 | } 38 | } 39 | return result; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Two Pointers/containerwithmostwater.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 11. Container With Most Water 3 | https://leetcode.com/problems/container-with-most-water/ 4 | */ 5 | 6 | // I was able to solve in 27 mins. 7 | // Brute Force 8 | class Solution 9 | { 10 | public: 11 | // Time: O(N^2), Space: O(1) 12 | int maxArea(vector &height) 13 | { 14 | int max_area = 0; 15 | for (int i = 0; i < height.size(); i++) 16 | { 17 | for (int j = i + 1; j < height.size(); j++) 18 | { 19 | int area = min(height[i], height[j]) * abs(j - i); 20 | max_area = max(max_area, area); 21 | } 22 | } 23 | return max_area; 24 | } 25 | }; 26 | 27 | // Two Pointers 28 | /* 29 | Since, we want the maximum area. So, we will start from maximum width. In case of 30 | shifting pointers (height), we will shift only from the smaller side by 1 (Side 31 | which have smaller height) 32 | */ 33 | class Solution 34 | { 35 | public: 36 | // Time: O(N), Space: O(1) 37 | int maxArea(vector &height) 38 | { 39 | int left = 0, right = height.size() - 1; 40 | int max_area = 0; 41 | while (left < right) 42 | { 43 | int area = min(height[left], height[right]) * abs(right - left); 44 | max_area = max(max_area, area); 45 | 46 | if (height[left] < height[right]) 47 | left++; 48 | else 49 | right--; 50 | } 51 | return max_area; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Two Pointers/sortColors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 75. Sort Colors 3 | https://leetcode.com/problems/sort-colors/ 4 | */ 5 | 6 | //Soultion 1 7 | class Solution 8 | { 9 | public: 10 | void sortColors(vector &nums) 11 | { 12 | 13 | int count_zero = 0; 14 | int count_one = 0; 15 | int count_two = 0; 16 | 17 | for(int i=0; i &nums) 45 | { 46 | int low = 0, high = nums.size() - 1, mid = 0; 47 | 48 | while (mid <= high){ 49 | if (nums[mid] == 0){ 50 | swap(nums[mid], nums[low]); 51 | mid++; 52 | low++; 53 | } 54 | else if (nums[mid] == 1){ 55 | mid++; 56 | } 57 | else if (nums[mid] == 2){ 58 | swap(nums[mid], nums[high]); 59 | high--; 60 | } 61 | } 62 | } 63 | }; -------------------------------------------------------------------------------- /Two Pointers/twosumii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode Question 167. Two Sum II - Input Array Is Sorted 3 | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 4 | */ 5 | 6 | /* 7 | This question is very similar to the 2 sum problem but here the array is sorted and 8 | it asks to give the indexes of both the elements such that: 9 | 1 <= index1 < index2 <= numbers.length 10 | 11 | Now, we want something like this, then we can't use BruteForce because it will give TLE. 12 | Also, we cannot use hashmap because, in this way, we are not sure whether we will 13 | get the indexes in the way we want or not. 14 | 15 | So, using Two Pointers would be a better idea becuase it will preserver the array and 16 | it's indexes and gives the output in constant extra space. 17 | 18 | I was able to solve in 10 mins. 49 sec. 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | // Time: O(N), Space: O(1) 25 | vector twoSum(vector &numbers, int target) 26 | { 27 | int left = 0, right = numbers.size() - 1; 28 | 29 | while (left < right) 30 | { 31 | if (numbers[left] + numbers[right] == target) 32 | return {left + 1, right + 1}; 33 | else if (numbers[left] + numbers[right] > target) 34 | right--; 35 | else 36 | left++; 37 | } 38 | return {}; 39 | } 40 | }; 41 | --------------------------------------------------------------------------------