├── 0 └── 1 Knapsack.cpp ├── Check If the number is power of 2.cpp ├── Count Digits.cpp ├── Find the difference.cpp ├── Single Number.cpp ├── kth smallest element.cpp ├── Climbing Stairs.cpp ├── Rotate Array.cpp ├── Min number of coins.cpp ├── Find the highest Altitude.cpp ├── Check if the array represents heap or not.cpp ├── Jump Game 1.cpp ├── Missing Number.cpp ├── Count Number of set bits from 1 to n.cpp ├── Minimum bit flips to convert from A to B.cpp ├── Maximum Subarray Sum.cpp ├── Best Time to buy and sell stocks(Easy Version).cpp ├── Find Sqrt in log n.cpp ├── Maximum Nesting Depth of parenthesis.cpp ├── Rotate Strings.cpp ├── Remove Outer Parenthesis.cpp ├── Remove duplicates from sorted array.cpp ├── Set the rightmost bit.cpp ├── kth largest element in array.cpp ├── Assign Cookies.cpp ├── Valid Anagrams.cpp ├── Isomorphic strings.cpp ├── Minimum Number Of Moves To make elements equal.cpp ├── Sort an array.cpp ├── Remove Duplicates from sorted array.cpp ├── Prefix to Infix.cpp ├── 2 Sum.cpp ├── Leaders In An Array.cpp ├── Next Smaller Element.cpp ├── Sieve of Eratosthenes.cpp ├── Best Time to Buy and Sell Stock II.cpp ├── Find k closest element.cpp ├── Find Pivot Index.cpp ├── Maximum Median Sum of subsequences of size 3.cpp ├── Minimum Number of Railway Station required.cpp ├── kth missing Positive number.cpp ├── Coin Change 1.cpp ├── Max Consecutive Ones.cpp ├── Check If The array is sorted and rotated.cpp ├── Longest Common Prefix in strings.cpp ├── Jump Game 2.cpp ├── Contains Duplicate II.cpp ├── Longest Substring without repeating Characters.cpp ├── Subarrays with xor k.cpp ├── Max Consecutive Ones III.cpp ├── Search in a 2D matrix II.cpp ├── Maximum Product Subarray.cpp ├── Find Power sets.cpp ├── Maximum Average Subarray.cpp ├── Number of substrings containing all three characters.cpp ├── Product Of Subarray except self.cpp ├── Arithmetic Slices.cpp ├── Minimum Window Subsequence.cpp ├── Rank Transform an array.cpp ├── Repeated DNA Sequences.cpp ├── Modular Exponentiation.cpp ├── Rearrange Elements by size(optimal approach).cpp ├── Minimum size subarray sum.cpp ├── Unique Paths.cpp ├── Largest Number atleast twice.cpp ├── Next Greater Element 2.cpp ├── Sliding Window Maximum.cpp ├── Find Occurrences of an element in array.cpp ├── Move zeroes to the end.cpp ├── Reverse Words in a string.cpp ├── Frog Jump.cpp ├── Sort Characters by frequency.cpp ├── Subarray Product Less than k.cpp ├── Continuous Subarray Sum.cpp ├── Count Good Numbers.cpp ├── Largest Odd Number In a string.cpp ├── Subset Generation.cpp ├── Count Subsets with sum k.cpp ├── Maximum Points You can obtain from cards.cpp ├── Reverse a stack using recursion.cpp ├── Prefix To Postfix.cpp ├── Minimum in a rotated sorted array.cpp ├── Top k most frequent elements.cpp ├── Valid Palindrome(Leetcode).cpp ├── Detect a cycle in linked list.cpp ├── Longest Repeating Character Replacement.cpp ├── Matrix Chain Multiplication.cpp ├── Next Permutation.cpp ├── Non Overlapping Intervals.cpp ├── Subarrays with k different integers.cpp ├── Longest Common Substring.cpp ├── Can Place Flowers.cpp ├── Plus One.cpp ├── Majority Element greater than n by 2.cpp ├── Minimum Cost of ropes.cpp ├── Range Sum query.cpp ├── Merge Intervals.cpp ├── Search Insert Position.cpp ├── Triangle.cpp ├── Valid Parenthesis.cpp ├── Hash Function.cpp ├── Subset Sum equals K.cpp ├── DFS of Graph.cpp ├── Find two numbers appearing odd number of times.cpp ├── Count Number of Subarrays.cpp ├── Find peak element.cpp ├── SubArraySum equalsK.cpp ├── Merge sorted arrays without using extra space.cpp ├── Postfix To Infix.cpp ├── Sum Of Beauty of Substrings.cpp ├── Task Scheduler.cpp ├── Binary Subarray With Sum.cpp ├── Longest Consecutive Sequence.cpp ├── Next Greater Element.cpp ├── kth largest element in the stream.cpp ├── Coin Change 2.cpp ├── Maximum Depth of Binary Tree.cpp ├── Sort a k sorted array.cpp ├── Largest Number.cpp ├── Trapping Rain Water.cpp ├── Are Two trees Same.cpp ├── Middle Of Linked List.cpp ├── Reverse Linked List(Recursive).cpp ├── Online Stock Span.cpp ├── Lowest Common Ancestor in binary search tree.cpp ├── Lowest Common Ancestor.cpp ├── Pascal Triangle.cpp ├── Convert Min heap to max heap.cpp ├── Find Min Max in BST.cpp ├── Fractional Knapsack problem.cpp ├── Reverse Linked List.cpp ├── Roman Number to integer.cpp ├── Single Element in a rotated sorted array.cpp ├── BFS.cpp ├── Find Smallest Number with given threshold.cpp ├── Intersection of two linked lists.cpp ├── Minimum falling Path Sum.cpp ├── Print LCS.cpp ├── Swap Node in pairs.cpp ├── Asteroid Collision.cpp ├── Koko Eating bananas.cpp ├── Rearrange Elements(brute force).cpp ├── Search In a rotated sorted array part 1.cpp ├── Largest Subarray with zero Sum.cpp ├── Minimum insertions or deletions to change a string.cpp ├── Best Time to buy and sell stocks 2.cpp ├── Combination Sum.cpp ├── Ninjas Training.cpp ├── Unique Paths 2.cpp ├── Search In a binary Search tree.cpp ├── Sort an array of 0 1 2.cpp ├── Best time to buy and sell stock IV.cpp ├── Job Sequencing Problem.cpp ├── QuickSort.cpp ├── 3 Sum Closest.cpp ├── N meetings in a room.cpp ├── Aggressive Cows Problem.cpp ├── Best Time to buy and sell stock 3.cpp ├── Check if graph is bipartite.cpp ├── Candy.cpp ├── Delete Middle of linked List.cpp ├── House Robber2.cpp ├── Longest Palindromic Subsequence.cpp ├── House Robber1.cpp ├── Sort a stack using recursion.cpp ├── Minimum Window Substring.cpp ├── Lemonade Change.cpp ├── Minimum Path Sum.cpp ├── BST Inorder Traversal.cpp ├── Invert Binary Tree.cpp ├── Largest Rectangle in Histogram.cpp ├── Matrix Median.cpp ├── Find the starting of cycle in Linked List.cpp ├── Binary Tree Preorder Traversal.cpp ├── Number of longest increasing subsequences.cpp ├── BST Post Order Traversal.cpp ├── Minimize Max Distance to Gas Station.cpp ├── Divide two integers without using multiplication and division sign.cpp ├── Check Diameter of Binary Tree.cpp ├── Hands Of Straights.cpp ├── Insert Intervals.cpp ├── Remove k digits.cpp ├── Validate Binary search tree.cpp ├── Flatten a binary Tree to linked list.cpp ├── Implement atoi.cpp ├── Binary Tree Maximum Path Sum.cpp ├── Rod Cutting Problem.cpp ├── kth smallest element in BST.cpp ├── 3 SUM.cpp ├── Search In a rotated Sorted Array part 2.cpp ├── Remove Nth Node from the end in linked list.cpp ├── Longest Bitnoic subsequence.cpp ├── Segregate odd and even nodes in linked list.cpp ├── Word Ladder.cpp ├── Book Allocation problem.cpp ├── Minimum Insertion steps to make a string palindrome.cpp ├── Partition equals subset Sum.cpp ├── Binary Tree Preorder traversal (Iterative).cpp ├── Search a 2D matrix.cpp ├── Floor in BST.cpp ├── Split Array Largest Sum.cpp ├── Binary Tree Paths.cpp ├── IPO.cpp ├── Spiral a Matrix.cpp ├── Undirected Graph detection in graph using dfs.cpp ├── Distinct Subsequences.cpp ├── Count Number of rotations in rotated sorted array.cpp ├── Flood Fill(using DFS).cpp ├── Infix To Postfix.cpp ├── Minimum Depth of Binary Tree.cpp ├── Capacity to Ship packaging within D days.cpp ├── Count Partitions with difference d.cpp ├── Find First and last position of element in sorted array.cpp ├── Find Peak Element II.cpp ├── Longest divisible subset.cpp ├── Sum Root to Leaf Numbers.cpp ├── Find highest lowest frequency element.cpp ├── Flattening a linked list.cpp ├── Merge m sorted lists.cpp ├── Painter's Partition.cpp ├── Longest Common Subsequence.cpp ├── Top View of Binary Tree.cpp ├── Binary Tree Inorder Traversal Iterative.cpp ├── Number Of Island.cpp ├── Battleships In a Board.cpp ├── Majority element.cpp ├── Merge two sorted linked lists.cpp ├── Number of Provinces.cpp ├── Partition Array into two arrays with minimum absolute difference.cpp ├── Topological sort.cpp ├── Add 1 to the number in the linked list.cpp ├── Best Time to buy and sell stock with cooldown.cpp ├── Best time to buy and sell stock with transaction fee.cpp ├── Set Matrix Zeroes.cpp ├── Binary Tree PostOrder Traversal using 2 stacks.cpp ├── Level Order Traversal.cpp ├── Minimum Number of Days to make m bouquets.cpp ├── LICENSE ├── Dijkstra Algorithm.cpp ├── Chocolate Pickup.cpp ├── Course Schedule 2.cpp ├── Insert Node in BST.cpp ├── Union of two sorted arrays.cpp ├── Rotate linked list by k places.cpp ├── Sum of left leaves.cpp ├── Add 2 numbers in linked list.cpp ├── 4 sum.cpp ├── Prim's Algorithm.cpp ├── Path Sum.cpp ├── Ceil in a BST.cpp ├── Shortest common supersequence.cpp ├── Remove duplicates from sorted doubly linked list.cpp ├── Median of two sorted arrays.cpp ├── Count Number of Island.cpp ├── 01 Matrix.cpp ├── Delete all occurences of a key in doubly linked list.cpp ├── Binary Tree Zigzag Order traversal.cpp ├── Sum Of Subarray minimums.cpp ├── Undirected Graph cycle bfs.cpp ├── 0 1 knapsack.cpp └── Cycle detection in undirected graph using bfs.cpp /Check If the number is power of 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if(n>0 &&(n&(n-1))==0) return true; 5 | return false; 6 | 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Count Digits.cpp: -------------------------------------------------------------------------------- 1 | int countDigits(int n){ 2 | long long int t=n; 3 | int ans=0; 4 | 5 | while(n>0){ 6 | int rem=n%10; 7 | if(rem!=0 && t%rem==0) ans+=1; 8 | n/=10; 9 | } 10 | return ans; 11 | } 12 | -------------------------------------------------------------------------------- /Find the difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findTheDifference(string s, string t) { 4 | char xori=0; 5 | 6 | for(char c:s) xori^=c; 7 | for(char c:t) xori^=c; 8 | 9 | return xori; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Single Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int xori=nums[0]; 5 | int n=nums.size(); 6 | 7 | for(int i=1;i 2 | int kthSmallest(vector& v, int n, int k) { 3 | priority_queue,greater>pq; 4 | for(auto it:v) pq.push(it); 5 | int ans=0; 6 | 7 | for(int i=0;i& nums, int k) { 4 | k=k%nums.size(); 5 | reverse(nums.begin(),nums.end()); 6 | reverse(nums.begin(),nums.begin()+k); 7 | reverse(nums.begin()+k,nums.end()); 8 | 9 | 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Min number of coins.cpp: -------------------------------------------------------------------------------- 1 | vector MinimumCoins(int n) 2 | { 3 | vectorans; 4 | int arr[9]={1,2,5,10,20,50,100,500,1000}; 5 | 6 | for(int i=8;i>=0;i--){ 7 | while(n>=arr[i]){ 8 | n-=arr[i]; 9 | ans.push_back(arr[i]); 10 | } 11 | } 12 | return ans; 13 | } 14 | -------------------------------------------------------------------------------- /Find the highest Altitude.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestAltitude(vector& gain) { 4 | int n=gain.size(); 5 | int ans=0,sum=0; 6 | 7 | for(int i=0;iarr[ind-1] || arr[ind*2]> arr[ind-1]) 8 | return 0; 9 | } 10 | return 1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Jump Game 1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int n=nums.size(); 5 | int maxind=0; 6 | 7 | for(int i=0;imaxind) return false; 9 | if((i+nums[i])>maxind) maxind=i+nums[i]; 10 | } 11 | return true; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | long int n=nums.size(); 5 | long int arrsum=(n*(n+1))/2; 6 | long int sum=0; 7 | 8 | for(int i=0;i 2 | int countSetBits(int n) { 3 | if(n==0) return 0; 4 | int x=log2(n); 5 | 6 | int bitsup2x=x*((1<<(x-1))); 7 | 8 | int msbbits=(n-(1<0){ 8 | int rem=ans%2; 9 | if(rem==1) cnt+=1; 10 | ans/=2; 11 | } 12 | return cnt; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Maximum Subarray Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | int sum=0,ans=INT_MIN; 5 | 6 | for(int i=0;i& prices) { 4 | int profit=0,mini=prices[0]; 5 | 6 | for(int i=1;i& nums) { 4 | int j=1; 5 | 6 | for(int i=1;i0){ 7 | int rem=t%2; 8 | cnt+=1; 9 | if(rem==0) { 10 | ans=cnt; 11 | break; 12 | } 13 | t=t/2; 14 | } 15 | if(ans==-1) return n; 16 | n=n^(1<<(ans-1)); 17 | return n; 18 | } 19 | -------------------------------------------------------------------------------- /kth largest element in array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { 4 | priority_queuepq; 5 | 6 | for(auto it:nums) pq.push(it); 7 | long long int ans=0; 8 | 9 | for(int i=0;i& g, vector& s) { 4 | sort(g.begin(),g.end()); 5 | sort(s.begin(),s.end()); 6 | int r=0,l=0; 7 | while(r hash1(27,0),hash2(27,0); 5 | 6 | for(int i=0;i& nums) { 4 | sort(nums.begin(),nums.end()); 5 | int n=nums.size(); 6 | int median=nums[n/2]; 7 | 8 | long long ans=0; 9 | 10 | for(int i=0;i sortArray(vector& nums) { 4 | priority_queue,greater>pq; 5 | 6 | for(auto it:nums) pq.push(it); 7 | 8 | vectorans; 9 | 10 | while(!pq.empty()){ 11 | ans.push_back(pq.top()); 12 | pq.pop(); 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Remove Duplicates from sorted array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int k=2; 5 | if(nums.size()<=2) return nums.size(); 6 | 7 | for(int i=2;ist; 5 | 6 | while(i>=0){ 7 | if(s[i]>='a' && s[i]<='z') st.push(string(1,s[i])); 8 | else{ 9 | string t1=st.top(); 10 | st.pop(); 11 | string t2=st.top(); 12 | st.pop(); 13 | string temp='('+t1+s[i]+t2+')'; 14 | st.push(temp); 15 | } 16 | i--; 17 | } 18 | return st.top(); 19 | } 20 | -------------------------------------------------------------------------------- /2 Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int n=nums.size(); 5 | mapmpp; 6 | 7 | for(int i=0;i 2 | vector findLeaders(vector &arr, int n) { 3 | // Write your code here. 4 | long long int maxi=INT_MIN; 5 | vectorans; 6 | 7 | for(int i=n-1;i>=0;i--){ 8 | if(arr[i]>maxi){ 9 | maxi=arr[i]; 10 | ans.push_back(arr[i]); 11 | } 12 | } 13 | 14 | reverse(ans.begin(),ans.end()); 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Next Smaller Element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | vector nextSmallerElement(vector &arr, int n) 3 | { 4 | vectorans(n); 5 | stackst; 6 | 7 | for(int i=n-1;i>=0;i--){ 8 | while(!st.empty() && st.top()>=arr[i]){ 9 | st.pop(); 10 | } 11 | if(st.empty()) ans[i]=-1; 12 | else ans[i]=st.top(); 13 | st.push(arr[i]); 14 | } 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Sieve of Eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrimes(int n) { 4 | 5 | int count=0; 6 | vectorvec(n+1,true); 7 | 8 | vec[0]=vec[1]=false; 9 | for(int i=2;i& prices) { 4 | int profit=0; 5 | int mini=prices.at(0); 6 | int sum=0; 7 | 8 | for(int i=1;iprices[i-1]){ 11 | sum+=prices[i]-prices[i-1]; 12 | } 13 | } 14 | return sum; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Find k closest element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findClosestElements(vector& arr, int k, int x) { 4 | int low=0,high=arr.size()-k; 5 | 6 | while(lowarr[mid+k]-x) low=mid+1; 10 | else high=mid; 11 | } 12 | 13 | return vector(arr.begin()+low, arr.begin()+low+k); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Find Pivot Index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int pivotIndex(vector& nums) { 4 | int n=nums.size(); 5 | vectorpsum(n,0); 6 | int total=0; 7 | 8 | for(int i=n-1;i>=0;i--) total+=nums[i]; 9 | 10 | int sum=0; 11 | 12 | for(int i=0;i& nums) { 4 | int n=nums.size(); 5 | long long int ans=0; 6 | sort(nums.begin(),nums.end()); 7 | int k=n/3; 8 | int i=n-2; 9 | 10 | while(k>0){ 11 | ans+=nums[i]; 12 | i-=2; 13 | k--; 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Minimum Number of Railway Station required.cpp: -------------------------------------------------------------------------------- 1 | int calculateMinPatforms(int at[], int dt[], int n) { 2 | sort(at,at+n); 3 | sort(dt,dt+n); 4 | 5 | int i=0,j=0,cnt=0,maxi=0; 6 | 7 | while(i& arr, int k) { 4 | int n=arr.size(); 5 | int low=0,high=n-1; 6 | 7 | while(low<=high){ 8 | int mid=low+(high-low)/2; 9 | 10 | int missing=arr[mid]-(mid+1); 11 | 12 | if(missing& coins, int amount) { 4 | int n=coins.size(); 5 | 6 | vectorans(amount+1,1e9); 7 | ans[0]=0; 8 | 9 | for(auto coin:coins){ 10 | for(int j=coin;j& nums) { 4 | int ans=INT_MIN; 5 | int count=0; 6 | 7 | for(int i=0;i& nums) { 4 | int count=0; 5 | int n=nums.size(); 6 | 7 | for(int i=1;inums[i]) 10 | { 11 | count++; 12 | } 13 | } 14 | 15 | if(nums[n-1]>nums[0]) 16 | count+=1; 17 | 18 | return count<=1; 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Longest Common Prefix in strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | int n=strs.size(); 5 | string ans=""; 6 | sort(strs.begin(),strs.end()); 7 | string st=strs[0]; 8 | string end=strs[n-1]; 9 | 10 | for(int i=0;i& nums) { 4 | int jumps=0; 5 | int n=nums.size(); 6 | int r=0,l=0; 7 | 8 | while(r& nums, int k) { 4 | int n=nums.size(); 5 | unordered_mapmpp; 6 | int mini=INT_MAX; 7 | 8 | for(int i=0;ihash(256,-1); 6 | 7 | while(r=l){ 9 | l=hash[s[r]]+1; 10 | } 11 | ans=max(ans,r-l+1); 12 | hash[s[r]]=r; 13 | r++; 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Subarrays with xor k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int subarraysWithSumK(vector < int > a, int b) { 3 | // Write your code here 4 | unordered_mapmpp; 5 | mpp[0]++; 6 | int xori=0; 7 | int n=a.size(); 8 | int ans=0; 9 | 10 | for(int i=0;i0){ 14 | ans+=mpp[need]; 15 | } 16 | mpp[xori]++; 17 | } 18 | return ans; 19 | } 20 | -------------------------------------------------------------------------------- /Max Consecutive Ones III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestOnes(vector& nums, int k) { 4 | int n=nums.size(); 5 | int l=0,r=0,temp=0,ans=0; 6 | 7 | while(rk){ 10 | temp-=(nums[l]==0); 11 | l++; 12 | 13 | } 14 | if(temp<=k) ans=max(ans,r-l+1); 15 | r++; 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Search in a 2D matrix II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | int n=matrix[0].size(),m=matrix.size(); 5 | 6 | int row=0,col=n-1; 7 | 8 | while(row=0){ 9 | if(matrix[row][col]==target) 10 | return true; 11 | else if(matrix[row][col]& nums) { 4 | int n=nums.size(); 5 | long long int prefix=1,suffix=1,ans=INT_MIN; 6 | 7 | for(int i=0;i> subsets(vector& nums) { 4 | int n=nums.size(); 5 | int subsets=(1<>ans; 8 | 9 | for(long long int i=0;itemp; 11 | for(int j=0;j& nums, int k) { 4 | int n=nums.size(); 5 | int ind=0; 6 | long long int maxi=INT_MIN; 7 | long long int sum=0; 8 | 9 | for(int i=0;i productExceptSelf(vector& nums) { 4 | int n=nums.size(); 5 | int start=1; 6 | vectorans(n,0); 7 | 8 | for(int i=0;i=0;i--){ 15 | ans[i]*=start; 16 | start*=nums[i]; 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Arithmetic Slices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector& nums) { 4 | int n=nums.size(); 5 | int count=0,ans=0; 6 | 7 | if(n<3) return 0; 8 | 9 | for(int i=2;i=0 && r2>=0){ 14 | if(s[l]==t[r2]) r2--; 15 | l--; 16 | } 17 | l++; 18 | if(r-l+1 arrayRankTransform(vector& arr) { 4 | vectorans; 5 | setst; 6 | mapmpp; 7 | 8 | for(auto it:arr){ 9 | st.insert(it); 10 | } 11 | int i=1; 12 | for(auto it:st){ 13 | mpp[it]=i; 14 | i++; 15 | } 16 | 17 | for(auto it:arr){ 18 | ans.push_back(mpp[it]); 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Repeated DNA Sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRepeatedDnaSequences(string s) { 4 | int n=s.size(); 5 | unordered_mapmpp; 6 | vectorans; 7 | if(n<10) return ans; 8 | 9 | for(int i=0;i<=n-10;i++){ 10 | string a=s.substr(i,10); 11 | mpp[a]++; 12 | } 13 | 14 | for(auto it:mpp){ 15 | if(it.second>=2) ans.push_back(it.first); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Modular Exponentiation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, long long int n) { 4 | if(x==0) return 0; 5 | double ans=1; 6 | long long int m=n; 7 | n=abs(n); 8 | 9 | while(n>0){ 10 | if(n&1){ 11 | ans=ans*x; 12 | n-=1; 13 | } 14 | else{ 15 | n/=2; 16 | x*=x; 17 | } 18 | } 19 | if(m<0) ans=1.0/ans; 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Rearrange Elements by size(optimal approach).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int n=nums.size(); 5 | vectorans(n); 6 | 7 | int pos=0,neg=1; 8 | 9 | for(auto it:nums){ 10 | if(it>0){ 11 | ans[pos]=it; 12 | pos+=2; 13 | } 14 | else{ 15 | ans[neg]=it; 16 | neg+=2; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Minimum size subarray sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int target, vector& nums) { 4 | int n=nums.size(); 5 | int l=0,r=0; 6 | int ans=INT_MAX,sum=0; 7 | 8 | while(r=target){ 11 | ans=min(ans,r-l+1); 12 | sum-=nums[l]; 13 | l++; 14 | } 15 | r++; 16 | } 17 | if(ans==INT_MAX) return 0; 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | long long int f(int m,int n,vector>&dp){ 5 | if(m==0 && n==0) return 1; 6 | if(m<0 || n<0) return 0; 7 | 8 | if(dp[m][n]!=-1) return dp[m][n]; 9 | long long int up=f(m-1,n,dp); 10 | long long int left=f(m,n-1,dp); 11 | return dp[m][n]=up+left; 12 | } 13 | 14 | 15 | long long int uniquePaths(int m, int n) { 16 | vector>dp(m,vector(n,-1)); 17 | return f(m-1,n-1,dp); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Largest Number atleast twice.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dominantIndex(vector& nums) { 4 | int n=nums.size(); 5 | int secondmaxi=-1,maxi=-1,ind=-1; 6 | 7 | for(int i=0;imaxi){ 9 | secondmaxi=maxi; 10 | maxi=nums[i]; 11 | ind=i; 12 | } 13 | else if(nums[i]>secondmaxi) secondmaxi=nums[i]; 14 | } 15 | 16 | if(maxi>=2*secondmaxi) return ind; 17 | return -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Next Greater Element 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElements(vector& nums) { 4 | int n=nums.size(); 5 | vectorans(n); 6 | stackst; 7 | 8 | for(int i=2*n-1;i>=0;i--){ 9 | while(!st.empty() && st.top() <= nums[i%n]){ 10 | st.pop(); 11 | } 12 | if(i maxSlidingWindow(vector& nums, int k) { 4 | int n=nums.size(); 5 | vectorans; 6 | dequedq; 7 | 8 | for(int i=0;i=k-1) ans.push_back(nums[dq.front()]); 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Find Occurrences of an element in array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector occurrencesOfElement(vector& nums, vector& queries, int x) { 4 | int n=nums.size(); 5 | vectortemp,ans; 6 | for(int i=0;itemp.size()) ans.push_back(-1); 12 | else ans.push_back(temp[queries[i]-1]); 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Move zeroes to the end.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int j=-1; 5 | int n=nums.size(); 6 | 7 | for(int i=0;i0) ans+=" "+word; 16 | } 17 | return ans.substr(1); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Frog Jump.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int f(int ind,vector&heights,vector&dp){ 4 | if(ind==0) return 0; 5 | if(dp[ind]!=-1) return dp[ind]; 6 | 7 | int left=f(ind-1,heights,dp)+abs(heights[ind-1]-heights[ind]); 8 | int right=INT_MAX; 9 | 10 | if(ind>1) right=f(ind-2,heights,dp)+abs(heights[ind-2]-heights[ind]); 11 | return dp[ind]= min(left,right); 12 | } 13 | int frogJump(int n, vector &heights) 14 | { 15 | vectordp(n+1,-1); 16 | return f(n-1,heights,dp); 17 | // Write your code here. 18 | } 19 | -------------------------------------------------------------------------------- /Sort Characters by frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | priority_queue>pq; 5 | unordered_mapmpp; 6 | 7 | for(auto it:s){ 8 | mpp[it]++; 9 | } 10 | 11 | for(auto it:mpp) pq.push({it.second,it.first}); 12 | string ans=""; 13 | while(!pq.empty()){ 14 | auto[cnt,ch]=pq.top(); 15 | pq.pop(); 16 | for(int i=0;i& nums, int k) { 4 | if(k==0) return 0; 5 | int n=nums.size(); 6 | int l=0,r=0; 7 | long long int multi=1,ans=0; 8 | 9 | while(r=k){ 13 | multi/=nums[l]; 14 | l++; 15 | } 16 | if(multi& nums, int k) { 4 | int n=nums.size(); 5 | unordered_mapmpp; 6 | long long int sum=0; 7 | mpp[0]=-1; 8 | 9 | for(int i=0;i=2) return 1; 14 | } 15 | else mpp[need]=i; 16 | } 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Count Good Numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long int power(long long n,long long int r){ 4 | if(r==0) return 1; 5 | 6 | if(r==1) return (n%1000000007); 7 | 8 | long long int ans=1; 9 | long long int know=power(n,r/2)%1000000007; 10 | if(r%2) ans=(ans*n)%1000000007; 11 | 12 | return (ans*((know*know)%1000000007))%1000000007; 13 | } 14 | int countGoodNumbers(long long n) { 15 | long long int combo=power(20,n/2)%1000000007; 16 | if(n%2) combo=(combo*5)%1000000007; 17 | return combo; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Largest Odd Number In a string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestOddNumber(string num) { 4 | int n=num.size(); 5 | string ans=""; 6 | bool flag=0; 7 | 8 | for(int i=n-1;i>=0;i--){ 9 | int digit=num[i]-'0'; 10 | if( digit%2){ 11 | flag=1; 12 | ans+=num[i]; 13 | } 14 | else if(flag==1){ 15 | ans+=num[i]; 16 | } 17 | } 18 | reverse(ans.begin(),ans.end()); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Subset Generation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsetsWithDup(vector& nums) { 4 | int n=nums.size(); 5 | set>st; 6 | sort(nums.begin(),nums.end()); 7 | 8 | for(int mask=0;mask<(1<temp; 10 | for(int i=0;i>ans(st.begin(),st.end()); 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Count Subsets with sum k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int f(int ind,int s,vector&arr, vector>&dp){ 4 | if(s==0) return 1; 5 | if(ind==0) return arr[0]==s; 6 | 7 | if(dp[ind][s]!=-1) return dp[ind][s]; 8 | int notpick=f(ind-1,s,arr,dp); 9 | int pick=0; 10 | if(arr[ind]<=s) pick=f(ind-1,s-arr[ind],arr,dp); 11 | 12 | return dp[ind][s]=pick+notpick; 13 | } 14 | 15 | 16 | 17 | 18 | 19 | int findWays(vector& arr, int k) 20 | { 21 | int n=arr.size(); 22 | vector>dp(n,vector(k+1,-1)); 23 | return f(n-1,k,arr,dp); 24 | } 25 | -------------------------------------------------------------------------------- /Maximum Points You can obtain from cards.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxScore(vector& cardPoints, int k) { 4 | int n=cardPoints.size(); 5 | long long int lsum=0,rsum=0,maxsum=0; 6 | for(int i=0;i=0;i--){ 11 | lsum-=cardPoints[i]; 12 | rsum+=cardPoints[rindex]; 13 | rindex-=1; 14 | maxsum=max(maxsum,lsum+rsum); 15 | } 16 | return maxsum; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Reverse a stack using recursion.cpp: -------------------------------------------------------------------------------- 1 | // User function Template for C++ 2 | 3 | class Solution { 4 | public: 5 | void insert(stack&st,int ele){ 6 | if(st.empty()){ 7 | st.push(ele); 8 | return; 9 | } 10 | 11 | int toper=st.top(); 12 | st.pop(); 13 | insert(st,ele); 14 | st.push(toper); 15 | } 16 | void Reverse(stack &st) { 17 | if(st.empty()) return; 18 | 19 | int ele=st.top(); 20 | st.pop(); 21 | Reverse(st); 22 | insert(st,ele); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Prefix To Postfix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | string preToPost(string s) { 3 | int n=s.size(); 4 | int i=0; 5 | stackst; 6 | 7 | for(int i=n-1;i>=0;i--){ 8 | if((s[i]>='A' && s[i]<='Z') || (s[i]>='a' && s[i]<='z') || (s[i]>='0' && s[i]<='9')) 9 | st.push(string(1,s[i])); 10 | else{ 11 | string t1=st.top(); 12 | st.pop(); 13 | string t2=st.top(); 14 | st.pop(); 15 | string temp=t1+t2+s[i]; 16 | st.push(temp); 17 | } 18 | } 19 | return st.top(); 20 | } 21 | -------------------------------------------------------------------------------- /Minimum in a rotated sorted array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n=nums.size(); 5 | int start=0,end=n-1; 6 | int ans=INT_MAX; 7 | 8 | while(start<=end){ 9 | int mid=start+(end-start)/2; 10 | if(nums[start]<=nums[mid]){ 11 | ans=min(ans,nums[start]); 12 | start=mid+1; 13 | } 14 | else{ 15 | ans=min(ans,nums[mid]); 16 | end=mid-1; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Top k most frequent elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | int n=nums.size(); 5 | 6 | mapmpp; 7 | vectorvec; 8 | 9 | for(auto it:nums) mpp[it]++; 10 | 11 | priority_queue>pq; 12 | 13 | for(auto it:mpp){ 14 | pq.push({it.second,it.first}); 15 | } 16 | while(k--){ 17 | auto [f,num]=pq.top(); 18 | vec.push_back(num); 19 | pq.pop(); 20 | } 21 | return vec; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Valid Palindrome(Leetcode).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(string s) { 4 | int l=0,r=s.size()-1; 5 | 6 | while(lnext!=NULL){ 16 | slow=slow->next; 17 | fast=fast->next->next; 18 | 19 | if(slow==fast) return true; 20 | } 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Longest Repeating Character Replacement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int characterReplacement(string s, int k) { 4 | int n=s.size(); 5 | int l=0,r=0,maxf=0,maxi=0; 6 | int hash[26]={0}; 7 | 8 | while(rk){ 13 | hash[s[l]-'A']--; 14 | l++; 15 | } 16 | if((r-l+1)-maxf<=k) maxi=max(maxi,r-l+1); 17 | r++; 18 | } 19 | return maxi; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Matrix Chain Multiplication.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int helper(int i,int j,vector&arr,vector>&dp){ 3 | if(i==j) return 0; 4 | 5 | if(dp[i][j]!=-1) return dp[i][j]; 6 | long long int mini=1e9; 7 | 8 | for(int k=i;k &arr, int N) 16 | { 17 | vector>dp(N+1,vector(N+1,-1)); 18 | return helper(1,N-1,arr,dp); 19 | } 20 | -------------------------------------------------------------------------------- /Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& a) { 4 | int n=a.size(); 5 | int ind=-1; 6 | for(int i=n-2;i>=0;i--){ 7 | if(a[i]ind;i--){ 17 | if(a[i]>a[ind]){ 18 | swap(a[i],a[ind]); 19 | break; 20 | } 21 | } 22 | reverse(a.begin()+ind+1,a.end()); 23 | return; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Non Overlapping Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | static bool comp(vector&v1,vector&v2){ 5 | return v1[1]>& intervals) { 8 | int n=intervals.size(); 9 | sort(intervals.begin(),intervals.end(),comp); 10 | 11 | int lastend=intervals[0][1],cnt=1; 12 | 13 | for(int i=1;i=lastend){ 15 | lastend=intervals[i][1]; 16 | cnt+=1; 17 | } 18 | } 19 | return n-cnt; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Subarrays with k different integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int f(vector& nums, int k){ 4 | int l=0,r=0,n=nums.size(); 5 | int cnt=0; 6 | unordered_mapmpp; 7 | 8 | while(rk){ 12 | mpp[nums[l]]--; 13 | if(mpp[nums[l]]==0) mpp.erase(nums[l]); 14 | l++; 15 | } 16 | cnt+=r-l+1; 17 | r++; 18 | } 19 | return cnt; 20 | } 21 | int subarraysWithKDistinct(vector& nums, int k) { 22 | return f(nums,k)-f(nums,k-1); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Longest Common Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLength(vector& nums1, vector& nums2) { 4 | int n=nums1.size(),m=nums2.size(); 5 | vectorprev(m+1,0),curr(m+1,0); 6 | int ans=0; 7 | 8 | for(int i=1;i<=n;i++){ 9 | for(int j=1;j<=m;j++){ 10 | if(nums1[i-1]==nums2[j-1]){ 11 | curr[j]=1+prev[j-1]; 12 | ans=max(ans,curr[j]); 13 | } 14 | else curr[j]=0; 15 | } 16 | prev=curr; 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Can Place Flowers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPlaceFlowers(vector& flowerbed, int n) { 4 | int s=flowerbed.size(); 5 | int cnt=0; 6 | 7 | for(int i=0;i=n) return 1; 16 | } 17 | } 18 | } 19 | return cnt>=n; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Plus One.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int n=digits.size(); 5 | int carry=0; 6 | vectorans; 7 | 8 | for(int i=n-1;i>=0;i--){ 9 | int temp=0; 10 | if(i==n-1) temp=digits[i]+1+carry; 11 | else temp=digits[i]+carry; 12 | digits[i]=temp%10; 13 | if(temp>=10) carry=temp/10; 14 | else carry=0; 15 | } 16 | 17 | if(carry>0) ans.push_back(carry); 18 | 19 | for(int i=0;i& nums) { 4 | int cnt=0,el; 5 | int n=nums.size(); 6 | 7 | for(int i=0;in/2) return el; 22 | return -1; 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Minimum Cost of ropes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost(vector& arr) { 4 | // code here 5 | int n=arr.size(),cost=0; 6 | priority_queue,greater>pq; 7 | 8 | for(int i=0;i1){ 13 | int len1=pq.top(); 14 | pq.pop(); 15 | int len2=pq.top(); 16 | pq.pop(); 17 | cost+=len1+len2; 18 | 19 | pq.push(len1+len2); 20 | } 21 | return cost; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Range Sum query.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | public: 3 | vectorprefix; 4 | 5 | NumArray(vector& nums) { 6 | int n=nums.size(); 7 | prefix.resize(n+1); 8 | 9 | prefix[0]=0; 10 | for(int i=0;isumRange(left,right); 24 | */ 25 | -------------------------------------------------------------------------------- /Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | int n=intervals.size(); 5 | sort(intervals.begin(),intervals.end()); 6 | 7 | vectortemp=intervals[0]; 8 | vector>ans; 9 | 10 | for(auto it:intervals){ 11 | if(it[0]<=temp[1]){ 12 | temp[1]=max(temp[1],it[1]); 13 | } 14 | else{ 15 | ans.push_back(temp); 16 | temp=it; 17 | } 18 | } 19 | ans.push_back(temp); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int start=0; 5 | int end=nums.size(); 6 | 7 | int mid=start+(end-start)/2; 8 | if(target>nums[end-1]) 9 | return end; 10 | 11 | while(start <= end) 12 | { 13 | mid=start+(end-start)/2; 14 | if(nums.at(mid)==target) 15 | return mid; 16 | else if(nums.at(mid)>& triangle) { 4 | int n=triangle.size(); 5 | vectordp(n); 6 | 7 | for(int j=0;j=0;i--){ 12 | vectortemp(n,0); 13 | for(int j=i;j>=0;j--){ 14 | int down=triangle[i][j]+dp[j]; 15 | int diag=triangle[i][j]+dp[j+1]; 16 | temp[j]=min(diag,down); 17 | } 18 | dp=temp; 19 | } 20 | 21 | return dp[0]; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Valid Parenthesis.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack < char > st; 5 | 6 | for(int i=0;imap; 4 | MyHashMap() { 5 | } 6 | 7 | void put(int key, int value) { 8 | map[key]=value; 9 | } 10 | 11 | int get(int key) { 12 | if(map.find(key)!=map.end()) return map[key]; 13 | return -1; 14 | } 15 | 16 | void remove(int key) { 17 | map.erase(key); 18 | } 19 | }; 20 | 21 | /** 22 | * Your MyHashMap object will be instantiated and called as such: 23 | * MyHashMap* obj = new MyHashMap(); 24 | * obj->put(key,value); 25 | * int param_2 = obj->get(key); 26 | * obj->remove(key); 27 | */ 28 | -------------------------------------------------------------------------------- /Subset Sum equals K.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool f(int n, int k, vector&arr, vector>&dp){ 4 | if(k==0) return true; 5 | 6 | if(n==0) return (arr[0]==k); 7 | 8 | if(dp[n][k] != -1) return dp[n][k]; 9 | 10 | bool nottake = f(n-1,k,arr,dp); 11 | 12 | bool take=0; 13 | if(k>=arr[n]){ 14 | take = f(n-1, k-arr[n], arr, dp); 15 | } 16 | 17 | return dp[n][k]=(take || nottake); 18 | } 19 | bool subsetSumToK(int n, int k, vector &arr) { 20 | // Write your code here. 21 | vector>dp(n+1,vector(k+1,-1)); 22 | 23 | return f(n-1, k, arr, dp); 24 | } 25 | -------------------------------------------------------------------------------- /DFS of Graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | 4 | 5 | void dfs(int node, vector>& adj, bool vis[], vector 6 | &ls){ 7 | vis[node]=1; 8 | ls.push_back(node); 9 | 10 | for(auto it:adj[node]){ 11 | if(!vis[it]){ 12 | dfs(it,adj,vis,ls); 13 | } 14 | } 15 | } 16 | 17 | 18 | public: 19 | vector dfs(vector>& adj) { 20 | // Code here 21 | int n=adj.size(); 22 | bool vis[n]={0}; 23 | vectorls; 24 | dfs(0,adj,vis,ls); 25 | return ls; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Find two numbers appearing odd number of times.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | vectorans; 5 | long long int xori=0; 6 | 7 | for(auto it:nums) xori=xori^it; 8 | 9 | long long int temp=xori & ~(xori-1); // find rightmost set bit 10 | long long int num1=0,num2=0; // bucket 1 and bucket 2 11 | 12 | for(auto it:nums){ 13 | if((temp& it)!=0) num1^=it; 14 | else num2^=it; 15 | } 16 | ans.push_back(num1); 17 | ans.push_back(num2); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Count Number of Subarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int f(vector&nums,int k){ 5 | if(k<0) return 0; 6 | 7 | int n=nums.size(); 8 | int l=0,r=0,ans=0,cnt=0; 9 | 10 | while(rk){ 14 | if(nums[l]&1) cnt--; 15 | l++; 16 | } 17 | ans+=r-l+1; 18 | r++; 19 | } 20 | return ans; 21 | } 22 | int numberOfSubarrays(vector& nums, int k) { 23 | int t1=f(nums,k); 24 | int t2=f(nums,k-1); 25 | return t1-t2; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Find peak element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | int n=nums.size(); 5 | if(n==1) return 0; 6 | if(nums[0]>nums[1]) return 0; 7 | if(nums[n-1]>nums[n-2]) return n-1; 8 | 9 | int low=1,high=n-2; 10 | while(low<=high){ 11 | int mid=low+(high-low)/2; 12 | if(nums[mid]>nums[mid+1] && nums[mid]>nums[mid-1]) return mid; 13 | else if(nums[mid]>nums[mid-1]) low=mid+1; 14 | else if(nums[mid]>nums[mid+1]) high=mid-1; 15 | else high=mid-1; 16 | } 17 | return -1; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /SubArraySum equalsK.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | int n=nums.size(),j=1,cnt=0; 5 | vectorprefix(n+1,0); 6 | 7 | for(auto it:nums){ 8 | prefix[j]=prefix[j-1]+it; 9 | j++; 10 | } 11 | unordered_mapmpp; 12 | 13 | for(int i=1;i& nums1, int m, vector& nums2, int n) { 4 | long long int i=m-1,j=0; 5 | 6 | while(i>=0 && jnums2[j]){ 8 | swap(nums1[i],nums2[j]); 9 | i--,j++; 10 | } 11 | else break; 12 | } 13 | sort(nums1.begin(),nums1.begin()+m); 14 | sort(nums2.begin(),nums2.end()); 15 | j=0; 16 | 17 | for(int i=m;i 2 | string postToInfix(string postfix) { 3 | stackst; 4 | int i=0; 5 | int n=postfix.size(); 6 | 7 | while(i='A' && postfix[i]<='Z') || (postfix[i]>='a' && postfix[i]<='z') 9 | || (postfix[i]>='0' && postfix[i]<='9')) st.push(string(1,postfix[i])); 10 | else{ 11 | string t1=st.top(); 12 | st.pop(); 13 | string t2=st.top(); 14 | st.pop(); 15 | string temp='('+t2+postfix[i] + t1+')'; 16 | st.push(temp); 17 | } 18 | i++; 19 | } 20 | return st.top(); 21 | } 22 | -------------------------------------------------------------------------------- /Sum Of Beauty of Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int beautySum(string s) { 4 | int n=s.size(); 5 | int ans=0; 6 | 7 | for(int i=0;ia(26,0); 9 | for(int j=i;j0) mini=min(mini,a[k]); 17 | } 18 | ans+=maxi-mini; 19 | } 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Task Scheduler.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Space Complexity-> O(26) ~= O(1); 4 | // Time Complexity-> O(n+26log26) almost equal to O(n) 5 | int leastInterval(vector& tasks, int n) { 6 | vectorhash(26,0); 7 | 8 | for(auto it:tasks){ 9 | hash[it-'A']++; 10 | } 11 | 12 | sort(hash.begin(),hash.end(),greater()); 13 | 14 | int ideal=(hash[0]-1)*n; // number of slots between all max freq. letters 15 | 16 | for(int i=1;i& nums, int goal){ 4 | if(goal<0) return 0; 5 | int n=nums.size(); 6 | int l=0,r=0,sum=0,count=0; 7 | 8 | while(rgoal){ 11 | sum=sum-nums[l]; 12 | l++; 13 | } 14 | count+=r-l+1; 15 | r++; 16 | } 17 | return count; 18 | } 19 | int numSubarraysWithSum(vector& nums, int goal) { 20 | int t1=func(nums,goal); 21 | int t2=func(nums,goal-1); 22 | return t1-t2; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | unordered_setst(nums.begin(),nums.end()); 5 | int n=nums.size(); 6 | long long int ans=1; 7 | long long int y=0,c=0; 8 | if(nums.size()==0) return 0; 9 | 10 | for(auto it:st){ 11 | if(!st.count(it-1)){ 12 | y=1; 13 | c=it; 14 | while(st.count(c+1)){ 15 | y+=1; 16 | c++; 17 | } 18 | ans=max(ans,y); 19 | } 20 | } 21 | return ans; 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Next Greater Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& nums1, vector& nums2) { 4 | int n=nums1.size(); 5 | vectorans; 6 | unordered_mapmpp; 7 | 8 | stackst; 9 | for(int i=nums2.size()-1;i>=0;i--){ 10 | while(!st.empty() && st.top()<=nums2[i]) st.pop(); 11 | if(st.empty()) mpp[nums2[i]]=-1; 12 | else mpp[nums2[i]]=st.top(); 13 | st.push(nums2[i]); 14 | } 15 | for(auto it:nums1){ 16 | ans.push_back(mpp[it]); 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /kth largest element in the stream.cpp: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | public: 3 | int num; 4 | priority_queue,greater>pq; 5 | KthLargest(int k, vector& nums) { 6 | num=k; 7 | for(auto it:nums){ 8 | pq.push(it); 9 | if(pq.size()>num) pq.pop(); 10 | } 11 | } 12 | 13 | int add(int val) { 14 | pq.push(val); 15 | if(pq.size()>num) pq.pop(); 16 | return pq.top(); 17 | } 18 | }; 19 | 20 | /** 21 | * Your KthLargest object will be instantiated and called as such: 22 | * KthLargest* obj = new KthLargest(k, nums); 23 | * int param_1 = obj->add(val); 24 | */ 25 | -------------------------------------------------------------------------------- /Coin Change 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int change(int amount, vector& coins) { 4 | using u128=unsigned __int128; 5 | int n=coins.size(); 6 | vectorprev(amount+1,0),curr(amount+1,0); 7 | 8 | for(int i=0;i<=amount;i++) prev[i]=(i%coins[0]==0); 9 | 10 | for(int i=1;ileft); 18 | int rh=maxDepth(root->right); 19 | 20 | return 1+max(lf,rh); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Sort a k sorted array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nearlySorted(vector& arr, int k) { 4 | // code 5 | priority_queue,greater>pq; 6 | 7 | int j=0; 8 | for(int i=0;ik){ 11 | int ele=pq.top(); 12 | pq.pop(); 13 | arr[j]=ele; 14 | j++; 15 | } 16 | } 17 | 18 | while(js2+s1; 8 | } 9 | 10 | string largestNumber(vector& nums) { 11 | int n=nums.size(); 12 | string ans=""; 13 | 14 | sort(nums.begin(),nums.end(),comp); 15 | 16 | for(auto it:nums){ 17 | ans+=to_string(it); 18 | } 19 | 20 | bool f=0; 21 | 22 | for(auto it:ans){ 23 | if(it!='0'){ 24 | f=1; 25 | break; 26 | } 27 | } 28 | return (f==0)?to_string(0):ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int n=height.size(); 5 | int l=0,r=n-1; 6 | int leftmax=0,rightmax=0; 7 | long int total=0; 8 | 9 | while(lval==q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Middle Of Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* fast=head; 15 | ListNode* slow=head; 16 | 17 | while(fast!=NULL && fast->next!=NULL){ 18 | fast=fast->next->next; 19 | slow=slow->next; 20 | } 21 | return slow; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Reverse Linked List(Recursive).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | if(head==NULL || head->next==NULL) return head; 15 | 16 | ListNode* newhead=reverseList(head->next); 17 | ListNode* front=head->next; 18 | front->next=head; 19 | head->next=NULL; 20 | 21 | return newhead; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Online Stock Span.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | int ind; 4 | stack>st; 5 | StockSpanner() { 6 | ind=-1; 7 | while(!st.empty()) st.pop(); 8 | } 9 | 10 | int next(int price) { 11 | ind+=1; 12 | while(!st.empty() && st.top().first<=price) st.pop(); 13 | 14 | int ans=ind; 15 | if(st.empty()) ans+=1; 16 | else ans-=st.top().second; 17 | st.push({price,ind}); 18 | return ans; 19 | } 20 | }; 21 | 22 | /** 23 | * Your StockSpanner object will be instantiated and called as such: 24 | * StockSpanner* obj = new StockSpanner(); 25 | * int param_1 = obj->next(price); 26 | */ 27 | -------------------------------------------------------------------------------- /Lowest Common Ancestor in binary search tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | class Solution { 12 | public: 13 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 14 | if(root==NULL) return root; 15 | 16 | int value=root->val; 17 | if(p->val>value && q->val>value) return lowestCommonAncestor(root->right,p,q); 18 | if(p->valvalleft,p,q); 19 | return root; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Lowest Common Ancestor.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | if(root==NULL || root==p || root==q) return root; 14 | 15 | TreeNode* lefti=lowestCommonAncestor(root->left,p,q); 16 | TreeNode* right=lowestCommonAncestor(root->right,p,q); 17 | 18 | if(lefti==NULL) return right; 19 | if(right==NULL) return lefti; 20 | return root; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Pascal Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vectorgeneraterow(int row){ 4 | long long int ans=1; 5 | vectoransrow; 6 | ansrow.push_back(ans); 7 | 8 | for(int col = 1; col < row; col++){ 9 | ans*=(row-col); 10 | ans/=col; 11 | ansrow.push_back(ans); 12 | } 13 | return ansrow; 14 | } 15 | 16 | public: 17 | vector> generate(int numRows) { 18 | vector>ans; 19 | 20 | for(int i = 1;i <= numRows; i++){ 21 | ans.push_back(generaterow(i)); 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Convert Min heap to max heap.cpp: -------------------------------------------------------------------------------- 1 | // User function Template for C++ 2 | 3 | class Solution { 4 | public: 5 | void convertMinToMaxHeap(vector &arr, int N) { 6 | for(int i=(N-2)/2;i>=0;i--){ 7 | maxheapify(arr,i,N); 8 | } 9 | } 10 | 11 | void maxheapify(vector&arr,int i,int N){ 12 | int l=2*i+1; 13 | int r=2*i+2; 14 | int largest=i; 15 | 16 | if(larr[largest]) largest=l; 17 | 18 | if(rarr[largest]) largest=r; 19 | 20 | if(largest!=i){ 21 | swap(arr[i],arr[largest]); 22 | maxheapify(arr,largest,N); 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Find Min Max in BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * class Node 3 | * { 4 | * public: 5 | * int data; 6 | * Node *left; 7 | * Node *right; 8 | * Node() : data(0), left(nullptr), right(nullptr){}; 9 | * Node(int x) : data(x), left(nullptr), right(nullptr) {} 10 | * Node(int x, Node *left, Node *right) : data(x), left(left), right(right) {} 11 | * }; 12 | */ 13 | int minVal(Node* root){ 14 | // Write your code here. 15 | if(root==NULL) return -1; 16 | if(root->left) return minVal(root->left); 17 | else return root->data; 18 | } 19 | 20 | /* int maxVal(Node* root){ 21 | if(root==NULL) return -1; 22 | if(root->right) return maxVal(root->right); 23 | else return root->data; 24 | } 25 | */ 26 | -------------------------------------------------------------------------------- /Fractional Knapsack problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | bool comp(pairp1,pairp2){ 3 | if((double)p1.second/p1.first>=(double)p2.second/p2.first) return 1; 4 | return 0; 5 | } 6 | double maximumValue (vector>& items, int n, int w) 7 | { 8 | sort(items.begin(),items.end(),comp); 9 | double totalvalue=0; 10 | 11 | for(auto it:items){ 12 | if(it.first<=w){ 13 | totalvalue+=it.second; 14 | w-=it.first; 15 | } 16 | else{ 17 | double perweight=((double)it.second/it.first)*w; 18 | totalvalue+=perweight; 19 | break; 20 | } 21 | } 22 | return totalvalue; 23 | } 24 | -------------------------------------------------------------------------------- /Reverse Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* temp=head; 15 | ListNode* prev=NULL; 16 | 17 | while(temp!=NULL){ 18 | ListNode* front=temp->next; 19 | temp->next=prev; 20 | prev=temp; 21 | temp=front; 22 | } 23 | return prev; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Roman Number to integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int cal(char a){ 4 | if(a=='I') return 1; 5 | if(a=='V') return 5; 6 | if(a=='X') return 10; 7 | if(a=='L') return 50; 8 | if(a=='C') return 100; 9 | if(a=='D') return 500; 10 | return 1000; 11 | } 12 | int romanToInt(string s) { 13 | int ans=0; 14 | for(int i=0;i& nums) { 4 | int n=nums.size(); 5 | if(n==1) return nums[0]; 6 | if(nums[0]!=nums[1]) return nums[0]; 7 | if(nums[n-1]!=nums[n-2]) return nums[n-1]; 8 | 9 | int start=0,end=n-1; 10 | 11 | while(start<=end){ 12 | int mid=start+(end-start)/2; 13 | if(nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1]) return nums[mid]; 14 | 15 | if((mid%2 && nums[mid-1]==nums[mid]) || (mid%2==0 && nums[mid]==nums[mid+1])) 16 | start=mid+1; 17 | else end=mid-1; 18 | } 19 | return -1; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /BFS.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to return Breadth First Traversal of given graph. 4 | vector bfs(vector> &adj) { 5 | int n=adj.size(); 6 | queueq; 7 | q.push(0); 8 | bool vis[n]={0}; 9 | vis[0]=1; 10 | vectorbfs; 11 | 12 | while(!q.empty()){ 13 | int node=q.front(); 14 | q.pop(); 15 | bfs.push_back(node); 16 | 17 | for(auto it:adj[node]){ 18 | if(!vis[it]){ 19 | vis[it]=1; 20 | q.push(it); 21 | } 22 | } 23 | } 24 | return bfs; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Find Smallest Number with given threshold.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | long long int f(vector&nums,long long int mid){ 5 | long long int sum=0; 6 | for(auto it:nums){ 7 | sum+=((it+mid-1)/mid); 8 | } 9 | return sum; 10 | } 11 | int smallestDivisor(vector& nums, int threshold) { 12 | long long int maxi=*max_element(nums.begin(),nums.end()); 13 | long long int s=1,e=maxi,ans=-1; 14 | 15 | while(s<=e){ 16 | long long int mid=s+(e-s)/2; 17 | if(f(nums,mid)<=threshold){ 18 | ans=mid; 19 | e=mid-1; 20 | } 21 | else s=mid+1; 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Intersection of two linked lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 | if(headA==NULL || headB==NULL) return NULL; 13 | 14 | ListNode* t1=headA; 15 | ListNode* t2=headB; 16 | 17 | while(t1!=t2){ 18 | t1=t1->next; 19 | t2=t2->next; 20 | 21 | if(t1==t2) return t1; 22 | if(t1==NULL) t1=headB; 23 | if(t2==NULL) t2=headA; 24 | } 25 | return t1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Minimum falling Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFallingPathSum(vector>& matrix) { 4 | int n=matrix[0].size(); 5 | vectordp(n,0); 6 | 7 | for(int i=0;itemp(n,0); 11 | for(int j=0;j0)?dp[j-1]+matrix[i][j]:1e9; 15 | temp[j]=min({up,leftdiag,rightdiag}); 16 | } 17 | dp=temp; 18 | } 19 | return *min_element(dp.begin(),dp.end()); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Print LCS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | string helper(int ind1,int ind2,string &s1, string &s2,vector>&dp){ 3 | if(ind1<0 || ind2<0) return ""; 4 | 5 | if(dp[ind1][ind2]!="A") return dp[ind1][ind2]; 6 | 7 | if(s1[ind1]==s2[ind2]){ 8 | return dp[ind1][ind2]=helper(ind1-1,ind2-1,s1,s2,dp)+string(1,s1[ind1]); 9 | } 10 | 11 | string temp1=helper(ind1-1,ind2,s1,s2,dp); 12 | string temp2=helper(ind1,ind2-1,s1,s2,dp); 13 | 14 | if(temp1.size()>temp2.size()) dp[ind1][ind2]=temp1; 15 | else dp[ind1][ind2]=temp2; 16 | return dp[ind1][ind2]; 17 | } 18 | 19 | string findLCS(int n, int m,string &s1, string &s2){ 20 | vector>dp(n,vector(m,"A")); 21 | return helper(n-1,m-1,s1,s2,dp); 22 | } 23 | -------------------------------------------------------------------------------- /Swap Node in pairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* fun(ListNode* head){ 14 | if(head==NULL || head->next==NULL) return head; 15 | 16 | ListNode* first=head; 17 | ListNode* second=head->next; 18 | 19 | first->next=fun(second->next); 20 | second->next=first; 21 | return second; 22 | } 23 | 24 | ListNode* swapPairs(ListNode* head) { 25 | return fun(head); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Asteroid Collision.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector asteroidCollision(vector& asteroids) { 4 | int n=asteroids.size(); 5 | vectorst; 6 | 7 | for(int i=0;i0) st.push_back(asteroids[i]); 9 | else{ 10 | while(!st.empty() && st.back()>0 && st.back()&piles,int mid){ 5 | long long int totsum=0; 6 | for(auto it:piles){ 7 | totsum+=((it+mid-1)/mid); 8 | } 9 | return totsum; 10 | } 11 | int minEatingSpeed(vector& piles, int h) { 12 | long long int maxi=*max_element(piles.begin(),piles.end()); 13 | long long int s=1,e=maxi,ans=0; 14 | 15 | while(s<=e){ 16 | long long int mid=s+(e-s)/2; 17 | long long int t=f(piles,mid); 18 | if(t<=h){ 19 | ans=mid; 20 | e=mid-1; 21 | } 22 | else if(t>h) s=mid+1; 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Rearrange Elements(brute force).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int n=nums.size(); 5 | vectorpos,neg,ans; 6 | 7 | for(auto it:nums){ 8 | if(it>0) pos.push_back(it); 9 | else neg.push_back(it); 10 | } 11 | bool fg=0; 12 | int j=0,k=0; 13 | for(int i=0;i& arr, int target) { 4 | int n=arr.size(); 5 | int start=0,end=n-1; 6 | 7 | while(start<=end){ 8 | int mid=start+(end-start)/2; 9 | if(arr[mid]==target) return mid; 10 | if(arr[mid]<=arr[end]){ 11 | if(arr[mid]<=target && target<=arr[end]) 12 | start=mid+1; 13 | else end=mid-1; 14 | } 15 | else{ 16 | if(arr[mid]>=target && arr[start]<=target) 17 | end=mid-1; 18 | else start=mid+1; 19 | } 20 | } 21 | return -1; 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Largest Subarray with zero Sum.cpp: -------------------------------------------------------------------------------- 1 | /*You are required to complete this function*/ 2 | 3 | class Solution { 4 | public: 5 | int maxLen(vector& arr) { 6 | int n=arr.size(); 7 | vectorpsum(n+1,0); 8 | 9 | for(int i=0;impp; 14 | int maxi=0; 15 | 16 | for(int i=1;i<=n;i++){ 17 | if(psum[i]==0){ 18 | maxi=max(maxi,i); 19 | } 20 | else if(mpp.count(psum[i])){ 21 | maxi=max(maxi,i-mpp[psum[i]]); 22 | } 23 | else mpp[psum[i]]=i; 24 | } 25 | return maxi; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Minimum insertions or deletions to change a string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int lcs(string str1,string str2){ 4 | int n=str1.size(); 5 | int m=str2.size(); 6 | 7 | vectorcurr(m+1,0),prev(m+1,0); 8 | 9 | for(int i=1;i<=n;i++){ 10 | for(int j=1;j<=m;j++){ 11 | if(str1[i-1]==str2[j-1]) curr[j]=1+prev[j-1]; 12 | else curr[j]=max(prev[j],curr[j-1]); 13 | } 14 | prev=curr; 15 | } 16 | 17 | return prev[m]; 18 | } 19 | 20 | public: 21 | int minDistance(string word1, string word2) { 22 | int n=word1.size(); 23 | int m=word2.size(); 24 | 25 | return n+m-2*lcs(word1,word2); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Best Time to buy and sell stocks 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int f(int ind, int c, vector&values, int n, vector>&dp){ 5 | if(ind==n) return 0; 6 | 7 | if(dp[ind][c]!=-1) return dp[ind][c]; 8 | 9 | int profit=0; 10 | if(c){ 11 | profit=max(-values[ind]+f(ind+1,0,values,n,dp),0+f(ind+1,1,values,n,dp)); 12 | } 13 | else{ 14 | profit=max(values[ind]+f(ind+1,1,values,n,dp),0+f(ind+1,0,values,n,dp)); 15 | } 16 | return dp[ind][c]=profit; 17 | } 18 | 19 | int maxProfit(vector& prices) { 20 | int n=prices.size(); 21 | vector>dp(n,vector(2,-1)); 22 | return f(0,1,prices,n,dp); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Combination Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void printS(int ind,vector>&ans,vector&ds,int s,int sum, vector&arr,int n){ 5 | if(ind==n){ 6 | if(sum==s){ 7 | ans.push_back(ds); 8 | } 9 | return; 10 | } 11 | 12 | printS(ind+1,ans,ds,s,sum,arr,n); 13 | if(s+arr[ind]<=sum){ 14 | s+=arr[ind]; 15 | ds.push_back(arr[ind]); 16 | printS(ind,ans,ds,s,sum,arr,n); 17 | ds.pop_back(); 18 | } 19 | } 20 | vector> combinationSum(vector& candidates, int target) { 21 | vector>ans; 22 | vectords; 23 | printS(0,ans,ds,0,target,candidates,candidates.size()); 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Ninjas Training.cpp: -------------------------------------------------------------------------------- 1 | int f(int day,int last, vector>&points,vector>&dp){ 2 | if(day==0){ 3 | int maxi=0; 4 | for(int i=0;i<3;i++){ 5 | if(i!=last) 6 | maxi=max(maxi,points[0][i]); 7 | } 8 | return maxi; 9 | } 10 | 11 | if(dp[day][last]!=-1) return dp[day][last]; 12 | 13 | int maxi=0; 14 | 15 | for(int i=0;i<3;i++){ 16 | if(i!=last){ 17 | int point=points[day][i]+f(day-1,i,points,dp); 18 | maxi=max(maxi,point); 19 | } 20 | } 21 | return dp[day][last]=maxi; 22 | } 23 | 24 | int ninjaTraining(int n, vector> &points) 25 | { 26 | vector>dp(n,vector(4,-1)); 27 | return f(n-1,3,points,dp); 28 | } 29 | -------------------------------------------------------------------------------- /Unique Paths 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsWithObstacles(vector>& obs) { 4 | int n=obs[0].size(); 5 | int m=obs.size(); 6 | vectordp(n,0); 7 | dp[0]=1; 8 | 9 | for(int i=0;itemp(n,0); 11 | for(int j=0;j0) up=dp[j]; 19 | if(j>0) left=temp[j-1]; 20 | temp[j]=up+left; 21 | } 22 | } 23 | dp=temp; 24 | } 25 | return dp[n-1]; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Search In a binary Search tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* searchBST(TreeNode* root, int val) { 15 | if(root==NULL) return NULL; 16 | if(root->val==val) return root; 17 | 18 | if(root->val>val){ 19 | return searchBST(root->left,val); 20 | } 21 | else return searchBST(root->right,val); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Sort an array of 0 1 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int zero=0,one=0,two=0; 5 | 6 | for(int i=0;i&a,int n, int k,vector>&dp){ 4 | if(ind==n || tran==2*k) return 0; 5 | 6 | if(dp[ind][tran]!=-1) return dp[ind][tran]; 7 | 8 | if(tran%2==0){ // buy 9 | return dp[ind][tran]=max(-a[ind]+helper(ind+1,tran+1,a,n,k,dp),helper(ind+1,tran,a,n,k,dp)); 10 | } 11 | else{ 12 | return dp[ind][tran]=max(a[ind]+helper(ind+1,tran+1,a,n,k,dp),helper(ind+1,tran,a,n,k,dp)); 13 | } 14 | } 15 | 16 | int maxProfit(int k, vector& prices) { 17 | int n=prices.size(); 18 | vector>dp(n,vector(2*k,-1)); 19 | return helper(0,0,prices,n,k,dp); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Job Sequencing Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | static bool comp(vector&v1,vector&v2){ 3 | return v1[2]>v2[2]; 4 | } 5 | 6 | vector jobScheduling(vector> &jobs) 7 | { 8 | sort(jobs.begin(),jobs.end(),comp); 9 | int totprofit=0,cnt=0,maxdeadline=-1; 10 | int n=jobs.size(); 11 | 12 | for(int i=0;ihash(maxdeadline+1,-1); 15 | 16 | for(int i=0;i=1;j--){ 18 | if(hash[j]==-1){ 19 | cnt++; 20 | hash[j]=jobs[i][0]; 21 | totprofit+=jobs[i][2]; 22 | break; 23 | } 24 | } 25 | } 26 | 27 | return {cnt,totprofit}; 28 | } 29 | -------------------------------------------------------------------------------- /QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int f(vector&arr, int low, int high){ 5 | int pivot=arr[low]; 6 | int i=low; 7 | int j=high; 8 | 9 | while(ipivot && j>low){ 15 | j--; 16 | } 17 | if(i&arr, int low, int high){ 24 | if(low quickSort(vector arr) 31 | { 32 | qs(arr, 0, arr.size()-1); 33 | return arr; 34 | } 35 | -------------------------------------------------------------------------------- /3 Sum Closest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | int n=nums.size(); 5 | int diff=INT_MAX; 6 | int ans=0; 7 | sort(nums.begin(),nums.end()); 8 | 9 | for(int i=0;i0 && nums[i]==nums[i-1]) continue; 11 | int j=i+1,k=n-1; 12 | 13 | while(j&p1,pair&p2){ 5 | return p1.second& start, vector& end) { 9 | int n=start.size(); 10 | vector>vec; 11 | 12 | for(int i=0;ilastfree){ 22 | ans+=1; 23 | lastfree=vec[i].second; 24 | } 25 | } 26 | 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Aggressive Cows Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool f(vector&temp,int mid,int k){ 4 | int cnt=1,last=temp[0]; 5 | 6 | for(int i=1;i=mid){ 9 | last=it; 10 | cnt++; 11 | } 12 | } 13 | 14 | return cnt>=k; 15 | } 16 | 17 | 18 | 19 | int aggressiveCows(vector &temp, int k) 20 | { 21 | int n=temp.size(); 22 | 23 | sort(temp.begin(),temp.end()); 24 | 25 | int low=1,high=temp[n-1]-temp[0]; 26 | int ans=0; 27 | 28 | while(low<=high){ 29 | int mid=low+(high-low)/2; 30 | 31 | if(f(temp,mid,k)){ 32 | ans=mid; 33 | low=mid+1; 34 | } 35 | else high=mid-1; 36 | } 37 | return ans; 38 | } 39 | -------------------------------------------------------------------------------- /Best Time to buy and sell stock 3.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int n=prices.size(); 5 | vector>after(2,vector(3,0)),curr(2,vector(3,0)); 6 | 7 | for(int ind=n-1;ind>=0;ind--){ 8 | for(int buy=0;buy<=1;buy++){ 9 | for(int cap=1;cap<=2;cap++){ 10 | if(buy){ 11 | curr[buy][cap]=max(-prices[ind]+after[0][cap],0+after[1][cap]); 12 | } 13 | else{ 14 | curr[buy][cap]=max(prices[ind]+after[1][cap-1],0+after[0][cap]); 15 | } 16 | } 17 | } 18 | after=curr; 19 | } 20 | return after[1][2]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Check if graph is bipartite.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool dfs(int node,int col,vector>& graph,vector&colour){ 4 | colour[node]=col; 5 | 6 | for(auto it:graph[node]){ 7 | if(colour[it]==-1){ 8 | if(!dfs(it,1-col,graph,colour)) return 0; 9 | } 10 | else if(colour[it]==col) return 0; 11 | } 12 | return 1; 13 | } 14 | public: 15 | bool isBipartite(vector>& graph) { 16 | int n=graph.size(); 17 | 18 | vectorcolour(n,-1); 19 | 20 | for(int i=0;i& ratings) { 4 | int n=ratings.size(); 5 | int sum=1; 6 | int i=1; 7 | 8 | while(iratings[i-1]){ 16 | peak++; 17 | sum+=peak; 18 | i++; 19 | } 20 | int down=1; 21 | while(ipeak)sum+=down-peak; 27 | } 28 | 29 | return sum; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Delete Middle of linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteMiddle(ListNode* head) { 14 | if(head==NULL || head->next==NULL) return NULL; 15 | ListNode* slow=head; 16 | ListNode* fast=head; 17 | fast=fast->next->next; 18 | 19 | while(fast!=NULL && fast->next!=NULL){ 20 | slow=slow->next; 21 | fast=fast->next->next; 22 | } 23 | slow->next=slow->next->next; 24 | return head; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /House Robber2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob1(vector& nums) { 4 | int n=nums.size(); 5 | int prev2=0; 6 | int prev1=nums[0]; 7 | 8 | for(int i=1;i1) pick+=prev2; 11 | int notpick=prev1; 12 | 13 | int curi=max(pick,notpick); 14 | prev2=prev1; 15 | prev1=curi; 16 | } 17 | return prev1; 18 | } 19 | 20 | int rob(vector& nums) { 21 | if(nums.size()==1) return nums[0]; 22 | vectort1,t2; 23 | int n=nums.size(); 24 | 25 | for(int i=0;i>dp(n+1,vector(m+1,0)); 7 | 8 | for(int ind1=1;ind1<=n;ind1++){ 9 | for(int ind2=1;ind2<=m;ind2++){ 10 | if(text1[ind1-1]==text2[ind2-1]) dp[ind1][ind2]=1+dp[ind1-1][ind2-1]; 11 | else 12 | dp[ind1][ind2]=max(dp[ind1-1][ind2],dp[ind1][ind2-1]); 13 | } 14 | } 15 | return dp[n][m]; 16 | } 17 | 18 | int longestPalindromeSubseq(string s) { 19 | string t=s; 20 | reverse(t.begin(),t.end()); 21 | return longestCommonSubsequence(s,t); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /House Robber1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // int f(int ind,vector&nums,vector&dp){ 4 | // if(ind==0) return nums[ind]; 5 | 6 | // if(ind<0) return 0; 7 | // if(dp[ind]!=-1) return dp[ind]; 8 | 9 | // int pick=nums[ind]+f(ind-2,nums,dp); 10 | // int notpick=0+f(ind-1,nums,dp); 11 | 12 | // return dp[ind]=max(pick,notpick); 13 | // } 14 | int rob(vector& nums) { 15 | int n=nums.size(); 16 | int prev2=0; 17 | int prev1=nums[0]; 18 | 19 | for(int i=1;i1) pick+=prev2; 22 | int notpick=prev1; 23 | 24 | int curi=max(pick,notpick); 25 | prev2=prev1; 26 | prev1=curi; 27 | } 28 | return prev1; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Sort a stack using recursion.cpp: -------------------------------------------------------------------------------- 1 | /*The structure of the class is 2 | class SortedStack{ 3 | public: 4 | stack s; 5 | void sort(); 6 | }; 7 | */ 8 | 9 | /* The below method sorts the stack s 10 | you are required to complete the below method */ 11 | 12 | void sorted(stack&st,int n){ 13 | if(n<=1) return; 14 | 15 | int ele=st.top(); 16 | st.pop(); 17 | sorted(st,n-1); 18 | stackdummy; 19 | 20 | while(!st.empty() && st.top()>ele){ 21 | dummy.push(st.top()); 22 | st.pop(); 23 | } 24 | st.push(ele); 25 | 26 | while(!dummy.empty()){ 27 | st.push(dummy.top()); 28 | dummy.pop(); 29 | } 30 | return; 31 | 32 | } 33 | void SortedStack ::sort() { 34 | // Your code here 35 | sorted(s,s.size()); 36 | } 37 | -------------------------------------------------------------------------------- /Minimum Window Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minWindow(string s, string t) { 4 | int n=s.size(),m=t.size(); 5 | int l=0,r=0,cnt=0,sindex=-1; 6 | long long int minlen=INT_MAX; 7 | int hash[256]={0}; 8 | 9 | for(int i=0;i0) cnt+=1; 13 | hash[s[r]]--; 14 | 15 | while(cnt==m){ 16 | if((r-l+1)0) cnt-=1; 22 | l+=1; 23 | } 24 | r++; 25 | } 26 | return ((sindex==-1)? "":s.substr(sindex,minlen)); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Lemonade Change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool lemonadeChange(vector& bills) { 4 | int five=0,ten=0,twenty=0; 5 | int n=bills.size(); 6 | 7 | for(int i=0;i=3) 22 | five-=3; 23 | else 24 | return false; 25 | } 26 | } 27 | return true; 28 | 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Minimum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPathSum(vector>& grid) { 4 | int m=grid.size(); 5 | int n=grid[0].size(); 6 | vectordp(n); 7 | dp[0]=grid[0][0]; 8 | 9 | for(int i=0;itemp(n,0); 11 | for(int j=0;j0) up+=dp[j]; 16 | else up+=1e9; 17 | if(j>0) left+=temp[j-1]; 18 | else left=1e9; 19 | temp[j]=min(up,left); 20 | } 21 | } 22 | dp=temp; 23 | } 24 | return dp[n-1]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /BST Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector inorderTraversal(TreeNode* root) { 15 | vectorvec; 16 | 17 | inorder(root,vec); 18 | return vec; 19 | } 20 | 21 | void inorder(TreeNode* root, vector&vec){ 22 | if(root==NULL) return; 23 | 24 | inorder(root->left,vec); 25 | vec.push_back(root->val); 26 | inorder(root->right,vec); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* invertTree(TreeNode* root) { 15 | if(root==NULL) return root; 16 | 17 | if(root->right==NULL && root->left==NULL) return root; 18 | 19 | TreeNode* left=invertTree(root->left); 20 | TreeNode* right=invertTree(root->right); 21 | 22 | root->right=left; 23 | root->left=right; 24 | 25 | return root; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Largest Rectangle in Histogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& heights) { 4 | int maxi=0; 5 | int n=heights.size(); 6 | stackst; 7 | 8 | for(int i=0;iheights[i]){ 10 | int element=st.top(); 11 | st.pop(); 12 | int nse=i,pse=(st.empty()?-1:st.top()); 13 | maxi=max(maxi,heights[element]*(nse-pse-1)); 14 | } 15 | st.push(i); 16 | } 17 | 18 | while(!st.empty()){ 19 | int element=st.top(); 20 | st.pop(); 21 | int nse=n,pse=(st.empty()?-1:st.top()); 22 | maxi=max(maxi,heights[element]*(nse-pse-1)); 23 | } 24 | return maxi; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Matrix Median.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int blackbox(vector> &matrix, int mid, int n, int m){ 4 | int cnt=0; 5 | 6 | for(int i=0;i> &matrix) 14 | { 15 | int n=matrix.size(); 16 | int m=matrix[0].size(); 17 | 18 | int low=1e9,high=0; 19 | 20 | for(int i=0;inext!=NULL){ 16 | slow=slow->next; 17 | fast=fast->next->next; 18 | 19 | if(slow==fast){ 20 | slow=head; 21 | while(slow!=fast){ 22 | slow=slow->next; 23 | fast=fast->next; 24 | } 25 | return slow; 26 | } 27 | } 28 | return NULL; 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Binary Tree Preorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector preorderTraversal(TreeNode* root) { 15 | vectorvec; 16 | preorder(root,vec); 17 | return vec; 18 | } 19 | 20 | void preorder(TreeNode* root, vector&arr){ 21 | if(root==NULL) return; 22 | 23 | arr.push_back(root->val); 24 | preorder(root->left,arr); 25 | preorder(root->right, arr); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Number of longest increasing subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNumberOfLIS(vector& nums) { 4 | int n=nums.size(); 5 | vectordp(n,1),cnt(n,1); 6 | int maxi=1; 7 | 8 | for(int i=1;inums[prev] && 1+dp[prev]>dp[i]){ 11 | dp[i]=1+dp[prev]; 12 | cnt[i]=cnt[prev]; 13 | } 14 | else if(nums[i]>nums[prev] && 1+dp[prev]==dp[i]){ 15 | cnt[i]+=cnt[prev]; 16 | } 17 | } 18 | maxi=max(maxi,dp[i]); 19 | } 20 | 21 | int num=0; 22 | 23 | for(int i=0;i postorderTraversal(TreeNode* root) { 15 | vectorvec; 16 | 17 | postorder(root,vec); 18 | return vec; 19 | } 20 | 21 | void postorder(TreeNode* root, vector&vec){ 22 | if(root==NULL) return; 23 | 24 | postorder(root->left,vec); 25 | postorder(root->right,vec); 26 | vec.push_back(root->val); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Minimize Max Distance to Gas Station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool f(vector&arr,int k, double mid){ 5 | int ans=0; 6 | 7 | for(int i=1;i &stations, int k) { 16 | // Code here 17 | int n=stations.size(); 18 | double low=0,high=stations[n-1]-stations[0], ans=0; 19 | 20 | while(high-low>1e-6){ 21 | double mid=(high+low)/2.0; 22 | 23 | if(f(stations,k, mid)){ 24 | ans=mid; 25 | high=mid; 26 | } 27 | else low=mid; 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Divide two integers without using multiplication and division sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int divide(int dividend, int divisor) { 4 | if(dividend==divisor) return 1; 5 | bool sign=true; 6 | if(dividend>=0 && divisor<0) sign=false; 7 | else if(dividend<=0 && divisor>0) sign=false; 8 | long n=abs((long)dividend); 9 | long d=abs((long)divisor); 10 | divisor=abs((long)divisor); 11 | long ans=0; 12 | 13 | while(n>=d){ 14 | long long int cnt=0; 15 | while(n>=(d<<(cnt+1))){ 16 | cnt++; 17 | } 18 | ans+=1<left,diam); 19 | int r=height(root->right,diam); 20 | diam=max(diam,l+r); 21 | return 1+max(l,r); 22 | } 23 | int diameterOfBinaryTree(TreeNode* root) { 24 | int diam=0; 25 | height(root,diam); 26 | return diam; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Hands Of Straights.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNStraightHand(vector& hand, int g) { 4 | int n=hand.size(); 5 | if(n%g) return 0; 6 | mapmpp; 7 | for(auto it:hand) mpp[it]+=1; 8 | 9 | priority_queue,greater>pq; 10 | for(auto it:mpp) pq.push(it.first); 11 | 12 | while(!pq.empty()){ 13 | long long int first=pq.top(); 14 | 15 | for(long long int i=first;i> insert(vector>& intervals, vector& newIntervals) { 4 | int n=intervals.size(); 5 | int i=0; 6 | 7 | vector>ans; 8 | while(ist; 6 | 7 | for(int i=0;i0 && st.top()>num[i]){ 9 | st.pop(); 10 | k-=1; 11 | } 12 | st.push(num[i]); 13 | } 14 | 15 | while(k>0){ 16 | st.pop(); 17 | k--; 18 | } 19 | if(st.empty()) return "0"; 20 | 21 | string ans=""; 22 | while(!st.empty()){ 23 | ans+=st.top(); 24 | st.pop(); 25 | } 26 | while(!ans.empty() && ans.back()=='0'){ 27 | ans.pop_back(); 28 | } 29 | if(ans.empty()) return "0"; 30 | reverse(ans.begin(),ans.end()); 31 | return ans; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Validate Binary search tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | bool helper(TreeNode* root, long long int mini, long long int maxi){ 15 | if(root==NULL) return 1; 16 | if(root->val>=maxi || root->val<=mini) return 0; 17 | 18 | return helper(root->left,mini,root->val) && helper(root->right,root->val,maxi); 19 | } 20 | public: 21 | bool isValidBST(TreeNode* root) { 22 | return helper(root, LLONG_MIN, LLONG_MAX); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Flatten a binary Tree to linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | void helper(TreeNode* root, TreeNode* &prev){ 15 | if(!root) return; 16 | 17 | helper(root->right,prev); 18 | helper(root->left,prev); 19 | 20 | root->right=prev; 21 | root->left=NULL; 22 | prev=root; 23 | } 24 | 25 | public: 26 | void flatten(TreeNode* root) { 27 | TreeNode* prev=nullptr; 28 | helper(root,prev); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Implement atoi.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int myAtoi(char *s) { 4 | if(s == nullptr || s[0] == '\0') return -1; 5 | 6 | int i = 0, sign = 1; 7 | long long ans = 0; 8 | 9 | if(s[i] == '-') { 10 | sign = -1; 11 | i++; 12 | } else if(s[i] == '+') { 13 | i++; 14 | } 15 | 16 | if(s[i] == '\0') return 0; 17 | 18 | for(; s[i] != '\0'; i++) { 19 | if(s[i] >= '0' && s[i] <= '9') { 20 | ans = ans * 10 + (s[i] - '0'); 21 | 22 | if(sign == 1 && ans > INT_MAX) return INT_MAX; 23 | if(sign == -1 && -ans < INT_MIN) return INT_MIN; 24 | }else{ 25 | if(sign==-1) return -ans; 26 | return ans; 27 | } 28 | } 29 | 30 | return sign * ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Binary Tree Maximum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int height(TreeNode* root, int &ans){ 15 | if(root==NULL) return 0; 16 | 17 | int l=max(0,height(root->left,ans)); 18 | int r=max(0,height(root->right,ans)); 19 | 20 | ans=max(ans,l+r+root->val); 21 | return root->val+max(l,r); 22 | } 23 | int maxPathSum(TreeNode* root) { 24 | int ans=INT_MIN; 25 | height(root,ans); 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Rod Cutting Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // int helper(int ind, int n, vector> &dp, vector&price){ 3 | // if(ind==0){ 4 | // return n*price[0]; 5 | // } 6 | 7 | // if(dp[ind][n]!=-1) return dp[ind][n]; 8 | // int nottake=0+helper(ind-1,n,dp,price); 9 | // int take=INT_MIN; 10 | 11 | // if(ind+1<=n) take=price[ind] + helper(ind,n-ind-1,dp,price); 12 | 13 | // return dp[ind][n]=max(take,nottake); 14 | // } 15 | 16 | int cutRod(vector &price, int n) 17 | { 18 | // vector>dp(n,vector(n+1,-1)); 19 | vectorprev(n+1,0),curr(n+1,0); 20 | 21 | for(int i=0;i<=n;i++) prev[i]=i*price[0]; 22 | 23 | for(int i=1;ileft,k); 23 | count++; 24 | 25 | if(count==k){ 26 | result=root->val; 27 | return; 28 | } 29 | helper(root->right,k); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /3 SUM.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | vector>ans; 6 | int n=nums.size(); 7 | 8 | for(int i=0;i0 && nums[i]==nums[i-1]) continue; 10 | int j=i+1,k=n-1; 11 | 12 | while(j0) k--; 16 | else{ 17 | vectortemp={nums[i],nums[j],nums[k]}; 18 | ans.push_back(temp); 19 | j++; 20 | k--; 21 | while(j& arr, int target) { 4 | int n=arr.size(); 5 | int start=0,end=n-1; 6 | 7 | while(start<=end){ 8 | int mid=start+(end-start)/2; 9 | if(arr[mid]==target) return 1; 10 | if(arr[start]==arr[mid] && arr[mid]==arr[end]) { 11 | start++; 12 | end--; 13 | continue; 14 | } 15 | if(arr[mid]<=arr[end]){ 16 | if(arr[mid]<=target && target<=arr[end]) 17 | start=mid+1; 18 | else end=mid-1; 19 | } 20 | else{ 21 | if(arr[mid]>=target && arr[start]<=target) 22 | end=mid-1; 23 | else start=mid+1; 24 | } 25 | } 26 | return 0; 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Remove Nth Node from the end in linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* removeNthFromEnd(ListNode* head, int n) { 14 | ListNode* slow=head; 15 | ListNode* fast=head; 16 | 17 | for(int i=0;inext; 18 | 19 | while(fast!=NULL && fast->next!=NULL){ 20 | slow=slow->next; 21 | fast=fast->next; 22 | } 23 | if(fast==NULL) return head->next; 24 | 25 | ListNode* delnode=slow->next; 26 | slow->next=slow->next->next; 27 | delete(delnode); 28 | return head; 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Longest Bitnoic subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestBitonicSequence(int n, vector &nums) { 4 | // code here 5 | vectordp1(n,1),dp2(n,1); 6 | 7 | for(int i=0;inums[prev] && 1+dp1[prev]>dp1[i]){ 10 | dp1[i]=1+dp1[prev]; 11 | } 12 | } 13 | } 14 | 15 | for(int i=n-1;i>=1;i--){ 16 | for(int prev=n-1;prev>i;prev--){ 17 | if(nums[i]>nums[prev] && 1+dp2[prev]>dp2[i]){ 18 | dp2[i]=1+dp2[prev]; 19 | } 20 | } 21 | } 22 | 23 | int maxi=0; 24 | for(int i=0;i1 && dp2[i]>1) 26 | maxi=max(maxi,dp1[i]+dp2[i]-1); 27 | } 28 | return maxi; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Segregate odd and even nodes in linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* oddEvenList(ListNode* head) { 14 | 15 | if(head==NULL || head->next==NULL) 16 | return head; 17 | ListNode* odd=head; 18 | ListNode* even=head->next; 19 | ListNode* evenhead=head->next; 20 | 21 | while(even!=NULL && even->next!=NULL){ 22 | odd->next=odd->next->next; 23 | even->next=even->next->next; 24 | 25 | odd=odd->next; 26 | even=even->next; 27 | } 28 | odd->next=evenhead; 29 | return head; 30 | 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Word Ladder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ladderLength(string beginWord, string endWord, vector& wordList) { 4 | setst(wordList.begin(),wordList.end()); 5 | queue>q; 6 | q.push({beginWord,1}); 7 | 8 | while(!q.empty()){ 9 | string word=q.front().first; 10 | int steps=q.front().second; 11 | q.pop(); 12 | if(word==endWord) return steps; 13 | 14 | for(int i=0;i 2 | 3 | bool f(vector&arr,int m,int mid){ 4 | long long int sum=0; 5 | int ans=1; 6 | 7 | for(auto it:arr){ 8 | if(it>mid) return 0; 9 | if(sum+it>mid){ 10 | sum=it; 11 | ans+=1; 12 | } 13 | else sum+=it; 14 | } 15 | return ans<=m; 16 | } 17 | 18 | 19 | int findPages(vector& arr, int n, int m) { 20 | // Write your code here. 21 | 22 | if(m>n) return -1; 23 | 24 | long long int maxi=*max_element(arr.begin(),arr.end()); 25 | long long int sum=0; 26 | 27 | for(int i=0;i>dp(n+1,vector(m+1,0)); 7 | 8 | for(int ind1=1;ind1<=n;ind1++){ 9 | for(int ind2=1;ind2<=m;ind2++){ 10 | if(text1[ind1-1]==text2[ind2-1]) dp[ind1][ind2]=1+dp[ind1-1][ind2-1]; 11 | else 12 | dp[ind1][ind2]=max(dp[ind1-1][ind2],dp[ind1][ind2-1]); 13 | } 14 | } 15 | return dp[n][m]; 16 | } 17 | 18 | int longestPalindromeSubseq(string &s) { 19 | string t=s; 20 | reverse(t.begin(),t.end()); 21 | return longestCommonSubsequence(s,t); 22 | } 23 | int minInsertions(string s) { 24 | int temp=longestPalindromeSubseq(s); 25 | return s.size()-temp; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Partition equals subset Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool f(int n,int k, vector&arr){ 5 | vectorprev(k+1,0), curr(k+1,0); 6 | 7 | prev[0] = curr[0] = 1; 8 | 9 | if(arr[0]<=k) 10 | prev[arr[0]] = true; 11 | 12 | for(int ind=1;ind=arr[ind]){ 18 | take = prev[j-arr[ind]]; 19 | } 20 | 21 | curr[j]=(take | nottake); 22 | } 23 | prev=curr; 24 | } 25 | 26 | return prev[k]; 27 | } 28 | 29 | bool canPartition(vector& arr) { 30 | int n=arr.size(); 31 | long long int totSum=0; 32 | 33 | for(auto it:arr){ 34 | totSum+=it; 35 | } 36 | 37 | if(totSum%2) return false; 38 | int target=totSum/2; 39 | 40 | return f(n,target,arr); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Binary Tree Preorder traversal (Iterative).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector preorderTraversal(TreeNode* root) { 15 | vectorans; 16 | if(root==NULL) return ans; 17 | 18 | stackst; 19 | st.push(root); 20 | while(!st.empty()){ 21 | TreeNode* root=st.top(); 22 | st.pop(); 23 | ans.push_back(root->val); 24 | if(root->right) st.push(root->right); 25 | if(root->left) st.push(root->left); 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Search a 2D matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool f(vector&arr,int k){ 5 | int low=0,high=arr.size()-1; 6 | 7 | while(low<=high){ 8 | int mid=low+(high-low)/2; 9 | if(arr[mid]==k) return 1; 10 | else if(arr[mid]>k) high=mid-1; 11 | else low=mid+1; 12 | } 13 | return 0; 14 | } 15 | bool searchMatrix(vector>& matrix, int target) { 16 | int n=matrix.size(),m=matrix[0].size(); 17 | int low=0,high=n-1; 18 | 19 | while(low<=high){ 20 | int mid=low+(high-low)/2; 21 | 22 | if(target>=matrix[mid][0] && target<=matrix[mid][m-1]){ 23 | return f(matrix[mid],target); 24 | } 25 | else if(target>matrix[mid][0] && target>matrix[mid][m-1]){ 26 | low=mid+1; 27 | } 28 | else high=mid-1; 29 | } 30 | return 0; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Floor in BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /************************************************************ 3 | 4 | Following is the TreeNode class structure 5 | 6 | template 7 | class TreeNode { 8 | public: 9 | T val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | 13 | TreeNode(T val) { 14 | this->val = val; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | ************************************************************/ 21 | 22 | int floorInBST(TreeNode * root, int X) 23 | { 24 | int floor=-1; 25 | while(root){ 26 | if(root->val==X){ 27 | floor=root->val; 28 | return floor; 29 | } 30 | if(X>root->val){ 31 | floor=root->val; 32 | root=root->right; 33 | } 34 | else{ 35 | root=root->left; 36 | } 37 | } 38 | return floor; 39 | } 40 | -------------------------------------------------------------------------------- /Split Array Largest Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool f(vector&arr,int k, int mid){ 5 | long int sum=0,ans=0; 6 | 7 | for(auto it:arr){ 8 | if(sum+it<=mid){ 9 | sum+=it; 10 | } 11 | else{ 12 | ans+=1; 13 | sum=it; 14 | } 15 | } 16 | return ans+1<=k; 17 | } 18 | 19 | int splitArray(vector& nums, int k) { 20 | int sum=0,maxi=nums[0],n=nums.size(); 21 | 22 | for(int i=0;i&ans,string temp){ 15 | temp+=to_string(root->val); 16 | 17 | if(root->right==NULL && root->left==NULL) ans.push_back(temp); 18 | temp+="->"; 19 | 20 | if(root->left) dfs(root->left,ans,temp); 21 | if(root->right) dfs(root->right,ans,temp); 22 | } 23 | 24 | public: 25 | vector binaryTreePaths(TreeNode* root) { 26 | vectorans; 27 | string temp=""; 28 | dfs(root,ans,temp); 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /IPO.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { 4 | int n=profits.size(); 5 | vector>vec(n); 6 | 7 | for(int i=0;ip1,pairp2){ 13 | if(p1.firstp2.second; 15 | 16 | return false; 17 | }); 18 | 19 | priority_queuepq; 20 | int j=0; 21 | 22 | for(int i=0;i spiralOrder(vector>& matrix) { 4 | int n = matrix[0].size(); 5 | int m = matrix.size(); 6 | vectorans; 7 | 8 | int left = 0, right = n-1; 9 | int top = 0, bottom = m-1; 10 | 11 | while(top <= bottom && left <= right){ 12 | for(int i = left; i <= right; i++){ 13 | ans.push_back(matrix[top][i]); 14 | } 15 | top++; 16 | 17 | for(int i = top; i <= bottom; i++) ans.push_back(matrix[i][right]); 18 | right--; 19 | 20 | if(top <= bottom){ 21 | for(int i = right; i >= left; i--) ans.push_back(matrix[bottom][i]); 22 | bottom--; 23 | } 24 | if(left <= right){ 25 | for(int i = bottom; i >= top;i--) ans.push_back(matrix[i][left]); 26 | left++; 27 | } 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Undirected Graph detection in graph using dfs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool detect(int node, int parent, vector&vis, vector>&adj){ 4 | vis[node]=1; 5 | 6 | for(int adjacentnode:adj[node]){ 7 | if(!vis[adjacentnode]){ 8 | if(detect(adjacentnode,node,vis,adj)) return 1; 9 | } 10 | else if(adjacentnode!=parent) return 1; 11 | } 12 | return 0; 13 | } 14 | 15 | public: 16 | bool isCycle(int V, vector>& edges) { 17 | // Code here 18 | vectorvis(V,0); 19 | vector>adj(V); 20 | 21 | for(auto it:edges){ 22 | adj[it[0]].push_back(it[1]); 23 | adj[it[1]].push_back(it[0]); 24 | } 25 | 26 | for(int i=0;i>&dp){ 4 | // if(j<0) return 1; 5 | // if(i<0) return 0; 6 | 7 | // if(dp[i][j]!=-1) return dp[i][j]; 8 | // if(s[i]==t[j]){ 9 | // return dp[i][j]=f(i-1,j-1,s,t,dp)+f(i-1,j,s,t,dp); 10 | // } 11 | // return dp[i][j]=f(i-1,j,s,t,dp); 12 | // } 13 | 14 | public: 15 | long long int numDistinct(string s, string t) { 16 | int n=s.size(); 17 | int m=t.size(); 18 | vector>dp(n+1,vector(m+1,0)); 19 | for(int i=0;i<=n;i++) dp[i][0]=1; 20 | 21 | for(int i=1;i<=n;i++){ 22 | for(int j=1;j<=m;j++){ 23 | if(s[i-1]==t[j-1]){ 24 | dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; 25 | } 26 | else dp[i][j]=dp[i-1][j]; 27 | } 28 | } 29 | 30 | return (int)dp[n][m]; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Count Number of rotations in rotated sorted array.cpp: -------------------------------------------------------------------------------- 1 | int findKRotation(vector &nums){ 2 | // Write your code here. 3 | int n=nums.size(); 4 | int start=0,end=n-1; 5 | int ans=1e9,ind=-1; 6 | 7 | while(start<=end){ 8 | int mid=start+(end-start)/2; 9 | if(nums[start]<=nums[end]){ 10 | if(nums[start]>& ans, vector>& image, int ini,int delrow[],int delcol[],int color){ 5 | ans[sr][sc]=color; 6 | 7 | int n=image.size(); 8 | int m=image[0].size(); 9 | 10 | for(int i=0;i<4;i++){ 11 | int nrow=sr+delrow[i]; 12 | int ncol=sc+delcol[i]; 13 | if(nrow>=0 && nrow=0 && ncol> floodFill(vector>& image, int sr, int sc, int color) { 19 | int ini=image[sr][sc]; 20 | if(ini==color) return image; 21 | vector>ans=image; 22 | int delrow[]={-1,0,1,0}; 23 | int delcol[]={0,1,0,-1}; 24 | dfs(sr,sc,ans,image,ini,delrow,delcol,color); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Infix To Postfix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int priority(char c){ 3 | if(c == '^') return 3; 4 | if(c == '*' || c == '/') return 2; 5 | if(c == '+' || c == '-') return 1; 6 | return -1; 7 | } 8 | 9 | 10 | 11 | 12 | 13 | string infixToPostfix(string exp){ 14 | int n = exp.size(), i = 0; 15 | stackst; 16 | string ans = ""; 17 | 18 | while(i= 'A' && exp[i] <= 'Z') || (exp[i] >= 'a' && exp[i] <= 'z') || (exp[i] >= '0' && exp[i] <= '9')) 20 | ans += exp[i]; 21 | else if(exp[i] == '(') st.push(exp[i]); 22 | else if(exp[i] == ')'){ 23 | 24 | while(!st.empty() && st.top() != '('){ 25 | ans += st.top(); 26 | st.pop(); 27 | } 28 | st.pop(); 29 | } 30 | else{ 31 | int temp=priority(exp[i]); 32 | while(!st.empty() && temp <= priority(st.top())){ 33 | ans += st.top(); 34 | st.pop(); 35 | } 36 | st.push(exp[i]); 37 | } 38 | i++; 39 | } 40 | 41 | while(!st.empty()){ 42 | ans += st.top(); 43 | st.pop(); 44 | } 45 | return ans; 46 | } 47 | -------------------------------------------------------------------------------- /Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | void helper(TreeNode* root, int &ans, int sum){ 15 | sum+=1; 16 | if(root->left==NULL && root->right==NULL){ 17 | ans=min(ans,sum); 18 | return; 19 | } 20 | 21 | if(root->left) helper(root->left,ans,sum); 22 | if(root->right) helper(root->right,ans,sum); 23 | } 24 | public: 25 | int minDepth(TreeNode* root) { 26 | if(root==NULL) return 0; 27 | int ans=INT_MAX; 28 | int sum=0; 29 | 30 | helper(root,ans,sum); 31 | return ans; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Capacity to Ship packaging within D days.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool f(vector&arr,int mid,int days){ 5 | int sum=0,ans=0; 6 | 7 | for(auto it:arr){ 8 | if((sum+it)<=mid){ 9 | sum+=it; 10 | } 11 | else{ 12 | ans+=1; 13 | sum=it; 14 | } 15 | } 16 | ans+=1; 17 | 18 | return ans<=days; 19 | } 20 | int shipWithinDays(vector& weights, int days) { 21 | int sum=0,maxi=0; 22 | 23 | for(auto it:weights){ 24 | sum+=it; 25 | maxi=max(maxi,it); 26 | } 27 | 28 | int low=maxi,high=sum; 29 | int ans=0; 30 | 31 | while(low<=high){ 32 | int mid=low+(high-low)/2; 33 | 34 | if(f(weights,mid,days)){ 35 | ans=mid; 36 | high=mid-1; 37 | } 38 | else low=mid+1; 39 | } 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Count Partitions with difference d.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int mod=(int)(1e9+7); 3 | 4 | 5 | int helper(int sum,vector&arr, vector>&dp,int ind){ 6 | if(ind==0){ 7 | if(arr[0]==0 && sum==0) return 2; 8 | if(sum==0 || arr[0]==sum) return 1; 9 | return 0; 10 | } 11 | 12 | if(dp[ind][sum]!=-1) return dp[ind][sum]; 13 | 14 | int nottake=helper(sum,arr,dp,ind-1); 15 | int take=0; 16 | 17 | if(arr[ind]<=sum) take=helper(sum-arr[ind],arr,dp,ind-1); 18 | 19 | return dp[ind][sum]=(nottake+take)%mod; 20 | } 21 | 22 | 23 | int findways(vector&arr, int target){ 24 | int n=arr.size(); 25 | 26 | vector>dp(n,vector(target+1,-1)); 27 | return (helper(target,arr,dp,n-1)%mod); 28 | } 29 | 30 | 31 | int countPartitions(int n, int d, vector &arr) { 32 | int totsum=0; 33 | 34 | for(auto it:arr) totsum+=it; 35 | 36 | if(totsum-d <0 || (totsum-d)%2) return 0; 37 | return findways(arr,(totsum-d)/2); 38 | } 39 | 40 | 41 | -------------------------------------------------------------------------------- /Find First and last position of element in sorted array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int n=nums.size(); 5 | vectorans(2,-1); 6 | if(n==0) return ans; 7 | 8 | int start=0,end=n-1,answ=-1; 9 | 10 | while(start<=end){ 11 | int mid=start+(end-start)/2; 12 | if(nums[mid]==target){ 13 | answ=mid; 14 | end=mid-1; 15 | } 16 | else if(nums[mid]>target) end=mid-1; 17 | else start=mid+1; 18 | } 19 | ans[0]=answ; 20 | 21 | start=0,end=n-1; answ=-1; 22 | while(start<=end){ 23 | int mid=start+(end-start)/2; 24 | if(nums[mid]==target){ 25 | answ=mid; 26 | start=mid+1; 27 | } 28 | else if(nums[mid]>target) end=mid-1; 29 | else start=mid+1; 30 | } 31 | ans[1]=answ; 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Find Peak Element II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int maxi(vector>& mat, int m, int n, int col){ 5 | int maxi=-1; 6 | int ind=-1; 7 | 8 | for(int i=0;imaxi){ 10 | maxi=mat[i][col]; 11 | ind=i; 12 | } 13 | } 14 | return ind; 15 | } 16 | 17 | vector findPeakGrid(vector>& mat) { 18 | int m=mat.size(),n=mat[0].size(); 19 | int low=0,high=n-1; 20 | 21 | while(low<=high){ 22 | int mid=low+(high-low)/2; 23 | int row=maxi(mat,m,n,mid); 24 | 25 | int left=mid-1>=0?mat[row][mid-1]:-1; 26 | int right=mid+1left && mat[row][mid]>right){ 28 | return {row,mid}; 29 | } 30 | else if(mat[row][mid] largestDivisibleSubset(vector& nums) { 4 | int n=nums.size(); 5 | vectordp(n,1),hash(n,0); 6 | int maxi=1,lastindex=0; 7 | sort(nums.begin(),nums.end()); 8 | 9 | for(int i=1;idp[i]){ 13 | dp[i]=1+dp[prev]; 14 | hash[i]=prev; 15 | } 16 | } 17 | if(dp[i]>maxi){ 18 | maxi=dp[i]; 19 | lastindex=i; 20 | } 21 | } 22 | 23 | vectortemp; 24 | temp.push_back(nums[lastindex]); 25 | 26 | while(hash[lastindex]!=lastindex){ 27 | lastindex=hash[lastindex]; 28 | temp.push_back(nums[lastindex]); 29 | } 30 | reverse(temp.begin(),temp.end()); 31 | return temp; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Sum Root to Leaf Numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | void dfs(TreeNode* root, long long int &sum, int number){ 15 | if(root==NULL) return; 16 | 17 | number=number*10+root->val; 18 | if(root->left==NULL && root->right==NULL){ 19 | sum+=number; 20 | return; 21 | } 22 | 23 | if(root->left) dfs(root->left,sum,number); 24 | if(root->right) dfs(root->right,sum,number); 25 | } 26 | 27 | public: 28 | int sumNumbers(TreeNode* root) { 29 | long long int sum=0,number=0; 30 | 31 | dfs(root,sum,number); 32 | return sum; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Find highest lowest frequency element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool possible(vector&nums,int mid,int k){ 5 | long long int windowsum=0,totalsum=0; 6 | for(int i=0;i& nums, int k) { 22 | int l=1,h=nums.size(),ans=0; 23 | sort(nums.begin(),nums.end()); 24 | 25 | while(l<=h){ 26 | int mid=l+(h-l)/2; 27 | if(possible(nums,mid,k)){ 28 | ans=mid; 29 | l=mid+1; 30 | } 31 | else h=mid-1; 32 | } 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Flattening a linked list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Definition for linked list. 3 | * class Node { 4 | * public: 5 | * int data; 6 | * Node *next; 7 | * Node *child; 8 | * Node() : data(0), next(nullptr), child(nullptr){}; 9 | * Node(int x) : data(x), next(nullptr), child(nullptr) {} 10 | * Node(int x, Node *next, Node *child) : data(x), next(next), child(child) {} 11 | * }; 12 | */ 13 | 14 | Node* merge(Node* list1, Node* list2){ 15 | Node* dnode=new Node(-1); 16 | Node* temp=dnode; 17 | 18 | while(list1!=NULL && list2!=NULL){ 19 | if(list1->data < list2->data){ 20 | temp->child=list1; 21 | temp=list1; 22 | list1=list1->child; 23 | } 24 | else{ 25 | temp->child=list2; 26 | temp=list2; 27 | list2=list2->child; 28 | } 29 | } 30 | if(list1) temp->child=list1; 31 | else temp->child=list2; 32 | 33 | return dnode->child; 34 | } 35 | Node* flattenLinkedList(Node* head) 36 | { 37 | if(head==NULL || head->next==NULL) return head; 38 | 39 | Node* merged=flattenLinkedList(head->next); 40 | return merge(head,merged); 41 | } 42 | -------------------------------------------------------------------------------- /Merge m sorted lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeKLists(vector& lists) { 14 | priority_queue,vector>,greater<>>pq; 15 | 16 | for(int i=0;ival, lists[i]}); 19 | } 20 | ListNode* dnode=new ListNode(-1); 21 | ListNode* temp=dnode; 22 | 23 | while(!pq.empty()){ 24 | auto it=pq.top(); 25 | temp->next=it.second; 26 | pq.pop(); 27 | if(it.second->next) pq.push({it.second->next->val,it.second->next}); 28 | temp=temp->next; 29 | } 30 | return dnode->next; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Painter's Partition.cpp: -------------------------------------------------------------------------------- 1 | // User function template for C++ 2 | 3 | class Solution { 4 | public: 5 | 6 | bool f(vector&arr,int k, int mid){ 7 | long int sum=0,ans=1; 8 | 9 | for(auto it:arr){ 10 | if(sum+it<=mid){ 11 | sum+=it; 12 | } 13 | else{ 14 | ans+=1; 15 | sum=it; 16 | } 17 | } 18 | 19 | return ans<=k; 20 | } 21 | 22 | 23 | int minTime(vector& arr, int k) { 24 | int sum=0,maxi=0; 25 | 26 | for(auto it:arr){ 27 | sum+=it; 28 | maxi=max(maxi,it); 29 | } 30 | 31 | int low=maxi,high=sum,ans=0; 32 | 33 | while(low<=high){ 34 | int mid=low+(high-low)/2; 35 | 36 | if(f(arr,k,mid)){ 37 | ans=mid; 38 | high=mid-1; 39 | } 40 | else low=mid+1; 41 | } 42 | return ans; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int helper(int ind1,int ind2,string &text1, string &text2, vector>&dp){ 4 | if(ind1<0 || ind2<0) return 0; 5 | 6 | if(dp[ind1][ind2]!=-1) return dp[ind1][ind2]; 7 | 8 | if(text1[ind1]==text2[ind2]) return dp[ind1][ind2]=1+helper(ind1-1,ind2-1,text1,text2,dp); 9 | 10 | return dp[ind1][ind2]=max(helper(ind1-1,ind2,text1,text2,dp),helper(ind1,ind2-1,text1,text2,dp)); 11 | } 12 | 13 | int longestCommonSubsequence(string text1, string text2) { 14 | int n=text1.length(); 15 | int m=text2.length(); 16 | vector>dp(n+1,vector(m+1,0)); 17 | 18 | for(int ind1=1;ind1<=n;ind1++){ 19 | for(int ind2=1;ind2<=m;ind2++){ 20 | if(text1[ind1-1]==text2[ind2-1]) dp[ind1][ind2]=1+dp[ind1-1][ind2-1]; 21 | else 22 | dp[ind1][ind2]=max(dp[ind1-1][ind2],dp[ind1][ind2-1]); 23 | } 24 | } 25 | return dp[n][m]; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Top View of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | public: 4 | int data; 5 | Node* left; 6 | Node* right; 7 | 8 | Node(int val) { 9 | data = val; 10 | left = nullptr; 11 | right = nullptr; 12 | } 13 | }; 14 | */ 15 | 16 | class Solution { 17 | public: 18 | vector topView(Node *root) { 19 | // code here 20 | vectorans; 21 | if(root==NULL) return ans; 22 | mapmpp; 23 | queue>q; 24 | q.push({root,0}); 25 | 26 | while(!q.empty()){ 27 | auto it=q.front(); 28 | q.pop(); 29 | Node* node=it.first; 30 | int x=it.second; 31 | 32 | if(mpp.find(x)==mpp.end()) mpp[x]=node->data; 33 | 34 | if(node->left) q.push({node->left,x-1}); 35 | if(node->right) q.push({node->right,x+1}); 36 | } 37 | 38 | 39 | for(auto it:mpp) ans.push_back(it.second); 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Binary Tree Inorder Traversal Iterative.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector inorderTraversal(TreeNode* root) { 15 | vectorans; 16 | stackst; 17 | TreeNode* node=root; 18 | 19 | while(1){ 20 | if(node!=NULL){ 21 | st.push(node); 22 | node=node->left; 23 | } 24 | else{ 25 | if(st.empty()) break; 26 | node=st.top(); 27 | st.pop(); 28 | ans.push_back(node->val); 29 | node=node->right; 30 | } 31 | } 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Number Of Island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void dfs(int i,int j, vector>&grid, vector>&vis, int m, int n){ 4 | vis[i][j]=1; 5 | 6 | if(i-1>=0 && vis[i-1][j]!=1 && grid[i-1][j]=='1') dfs(i-1,j,grid,vis,m,n); 7 | if(i+1=0 && vis[i][j-1]!=1 && grid[i][j-1]=='1') dfs(i,j-1,grid,vis,m,n); 9 | if(j+1>& grid) { 14 | int m=grid.size(); 15 | int n=grid[0].size(); 16 | int count=0; 17 | vector>vis(m,vector(n,0)); 18 | 19 | for(int i=0;i>& board,int m,int n, int start, int end){ 4 | board[i][j]='.'; 5 | 6 | if(i-1>=0 && (start==i-1 || end==j) && board[i-1][j]=='X') dfs(i-1,j,board,m,n,start,end); 7 | if(i+1=0 && (start==i || end==j-1) && board[i][j-1]=='X') dfs(i,j-1,board,m,n,start,end); 9 | if(j+1>& board) { 14 | int m=board.size(); 15 | int n=board[0].size(); 16 | int count=0; 17 | 18 | for(int i=0;i majorityElement(vector& nums) { 4 | int n=nums.size(); 5 | int cnt1 = 0, cnt2 = 0; 6 | int el1 = INT_MIN, el2 = INT_MIN; 7 | 8 | for(int i = 0; i < n; i++){ 9 | if(cnt1 == 0 && el2 != nums[i]){ 10 | el1 = nums[i]; 11 | cnt1 = 1; 12 | } 13 | else if(cnt2 == 0 && el1 != nums[i]){ 14 | el2 = nums[i]; 15 | cnt2 = 1; 16 | } 17 | else if(nums[i] == el1) cnt1++; 18 | else if(nums[i] == el2) cnt2++; 19 | else{ 20 | cnt1--; 21 | cnt2--; 22 | } 23 | } 24 | 25 | cnt1 = 0, cnt2 = 0; 26 | 27 | for(auto it:nums){ 28 | if(it == el1) cnt1++; 29 | if(it == el2) cnt2++; 30 | } 31 | vectorans; 32 | if(cnt1 > n/3) ans.push_back(el1); 33 | if(cnt2 > n/3) ans.push_back(el2); 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Merge two sorted linked lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 14 | ListNode* t1=list1; 15 | ListNode* t2=list2; 16 | ListNode* dnode=new ListNode(-1); 17 | ListNode* temp=dnode; 18 | 19 | while(t1!=NULL && t2!=NULL){ 20 | if(t1->valval){ 21 | temp->next=t1; 22 | temp=t1; 23 | t1=t1->next; 24 | } 25 | else{ 26 | temp->next=t2; 27 | temp=t2; 28 | t2=t2->next; 29 | } 30 | } 31 | if(t1) temp->next=t1; 32 | if(t2) temp->next=t2; 33 | 34 | return dnode->next; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Number of Provinces.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void dfs(int node, vector>& isConnected, vector&vis){ 5 | vis[node]=1; 6 | for(int j=0;j>& isConnected) { 14 | int v=isConnected.size(); 15 | // vectoradjls[v]; 16 | 17 | // for(int i=0;ivis(v,0); 26 | int cnt=0; 27 | 28 | for(int i=0;i& arr, int n) 2 | { 3 | long long int sum = 0; 4 | 5 | for(int i = 0; i < n; i++) sum+=arr[i]; 6 | 7 | int k = sum; 8 | vector>dp(n, vector(k+1,false)) ; 9 | 10 | for(int i=0;i&vis,vector>&edges, 4 | stack&st){ 5 | vis[node]=1; 6 | 7 | for(auto it:edges[node]){ 8 | if(!vis[it]){ 9 | dfs(it,vis,edges,st); 10 | } 11 | } 12 | st.push(node); 13 | } 14 | 15 | public: 16 | vector topoSort(int V, vector>& edges) { 17 | // code here 18 | vectorvis(V,0); 19 | stackst; 20 | vector>adj(V); 21 | 22 | for(auto it:edges){ 23 | int u=it[0]; 24 | int v=it[1]; 25 | adj[u].push_back(v); 26 | } 27 | 28 | for(int i=0;ians; 35 | while(!st.empty()){ 36 | ans.push_back(st.top()); 37 | st.pop(); 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Add 1 to the number in the linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of linked list: 3 | * 4 | * class Node { 5 | * public: 6 | * int data; 7 | * Node *next; 8 | * Node() { 9 | * this->data = 0; 10 | * this->next = NULL; 11 | * } 12 | * Node(int data) { 13 | * this->data = data; 14 | * this->next = NULL; 15 | * } 16 | * Node (int data, Node *next) { 17 | * this->data = data; 18 | * this->next = next; 19 | * } 20 | * }; 21 | * 22 | *************************************************************************/ 23 | 24 | int helper(Node* head){ 25 | if(head==NULL) return 1; 26 | 27 | int carry=helper(head->next); 28 | head->data=head->data+carry; 29 | carry=head->data/10; 30 | head->data=head->data%10; 31 | return carry; 32 | } 33 | 34 | Node *addOne(Node *head) 35 | { 36 | int carry=helper(head); 37 | 38 | if(carry){ 39 | Node* newnode=new Node(1); 40 | newnode->next=head; 41 | return newnode; 42 | } 43 | return head; 44 | } 45 | -------------------------------------------------------------------------------- /Best Time to buy and sell stock with cooldown.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int helper(int ind, int buy,vector&a, vector>&dp){ 4 | if(ind>=a.size()) return 0; 5 | 6 | if(dp[ind][buy]!=-1) return dp[ind][buy]; 7 | 8 | if(buy==1){ 9 | return dp[ind][buy]=max(-a[ind]+helper(ind+1,0,a,dp),helper(ind+1,1,a,dp)); 10 | } 11 | else{ 12 | return dp[ind][buy]=max(a[ind]+helper(ind+2,1,a,dp),helper(ind+1,0,a,dp)); 13 | } 14 | } 15 | public: 16 | int maxProfit(vector& a) { 17 | int n=a.size(); 18 | vector>dp(n+2,vector(2,0)); 19 | 20 | for(int ind=n-1;ind>=0;ind--){ 21 | for(int buy=0;buy<=1;buy++){ 22 | if(buy==1){ 23 | dp[ind][buy]=max(-a[ind]+dp[ind+1][0],dp[ind+1][1]); 24 | } 25 | else{ 26 | dp[ind][buy]=max(a[ind]+dp[ind+2][1],dp[ind+1][0]); 27 | } 28 | } 29 | } 30 | return dp[0][1]; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Best time to buy and sell stock with transaction fee.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int helper(int ind, int buy, vector&a, int fee, vector>&dp){ 4 | if(ind==a.size()) return 0; 5 | 6 | if(dp[ind][buy]!=-1) return dp[ind][buy]; 7 | 8 | if(buy){ 9 | return dp[ind][buy]=max(-a[ind]+helper(ind+1,0,a,fee,dp),helper(ind+1,1,a,fee,dp)); 10 | } 11 | else{ 12 | return dp[ind][buy]=max(a[ind]-fee+helper(ind+1,1,a,fee,dp),helper(ind+1,0,a,fee,dp)); 13 | } 14 | } 15 | int maxProfit(vector&a, int fee) { 16 | int n=a.size(); 17 | vector>dp(n+1,vector(2,0)); 18 | 19 | for(int ind=n-1;ind>=0;ind--){ 20 | for(int buy=0;buy<=1;buy++){ 21 | if(buy){ 22 | dp[ind][buy]=max(-a[ind]+dp[ind+1][0],dp[ind+1][1]); 23 | } 24 | else{ 25 | dp[ind][buy]=max(a[ind]-fee+dp[ind+1][1],dp[ind+1][0]); 26 | } 27 | } 28 | } 29 | return dp[0][1]; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Set Matrix Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | int m=matrix.size(); 5 | int n=matrix[0].size(); 6 | int row0=1; 7 | int col0=1; 8 | 9 | for(int i=0;i postorderTraversal(TreeNode* root) { 15 | vectorans; 16 | if(root==NULL) return ans; 17 | 18 | stackst1,st2; 19 | st1.push(root); 20 | while(!st1.empty()){ 21 | root=st1.top(); 22 | st1.pop(); 23 | st2.push(root); 24 | if(root->left!=NULL) st1.push(root->left); 25 | if(root->right) st1.push(root->right); 26 | } 27 | 28 | while(!st2.empty()){ 29 | TreeNode* temp=st2.top(); 30 | ans.push_back(temp->val); 31 | st2.pop(); 32 | } 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> levelOrder(TreeNode* root) { 15 | vector>ans; 16 | if(root==NULL) return ans; 17 | queueq; 18 | q.push(root); 19 | 20 | while(!q.empty()){ 21 | int s=q.size(); 22 | vectorlevel; 23 | for(int i=0;ileft) q.push(node->left); 27 | if(node->right) q.push(node->right); 28 | level.push_back(node->val); 29 | } 30 | ans.push_back(level); 31 | } 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Minimum Number of Days to make m bouquets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool f(vector&arr, int m, int k, int mid){ 5 | long long int cnt=0; 6 | long long int ans=0; 7 | 8 | for(int i=0;i=m; 21 | } 22 | int minDays(vector& bloomDay, int m, int k) { 23 | long long int mini=*min_element(bloomDay.begin(),bloomDay.end()); 24 | long long int maxi=*max_element(bloomDay.begin(),bloomDay.end()); 25 | 26 | long long int low=mini; 27 | long long int high=maxi; 28 | long long int ans=-1; 29 | 30 | while(low<=high){ 31 | int mid=low+(high-low)/2; 32 | 33 | if(f(bloomDay,m,k,mid)){ 34 | ans=mid; 35 | high=mid-1; 36 | } 37 | else low=mid+1; 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Dave Aditya 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 | -------------------------------------------------------------------------------- /Dijkstra Algorithm.cpp: -------------------------------------------------------------------------------- 1 | // User Function Template 2 | class Solution { 3 | public: 4 | vector dijkstra(int V, vector> &edges, int src) { 5 | // Code here 6 | 7 | vector>>adj(V); 8 | 9 | for(auto it:edges){ 10 | int u=it[0],v=it[1],w=it[2]; 11 | adj[u].push_back({v,w}); 12 | adj[v].push_back({u,w}); 13 | } 14 | priority_queue,vector>,greater<>>pq; 15 | vectordis(V,1e9); 16 | dis[src]=0; 17 | 18 | pq.push({0,src}); 19 | 20 | while(!pq.empty()){ 21 | int edgeweight=pq.top().first; 22 | int adjacentnode=pq.top().second; 23 | pq.pop(); 24 | 25 | for(auto &[neighbour,weight]:adj[adjacentnode]){ 26 | if(edgeweight+weight 2 | 3 | int f(int i, int j1, int j2, int r, int c, vector> &grid, 4 | vector>>&dp){ 5 | 6 | if(j1<0 || j2<0 || j1>=c || j2>=c) return -1e8; 7 | 8 | if(i==r-1){ 9 | if(j1 == j2) return grid[i][j1]; 10 | else return grid[i][j1] + grid[i][j2]; 11 | } 12 | 13 | if(dp[i][j1][j2] != -1) return dp[i][j1][j2]; 14 | 15 | long long int maxi=0; 16 | 17 | // explore all 9 paths, for each path of alice, 3 paths of bob 18 | for(int dj1 = -1; dj1 < 2; dj1++){ 19 | for(int dj2 = -1; dj2 < 2; dj2++){ 20 | long long int value=0; 21 | 22 | if(j1 == j2) value+=grid[i][j1]; 23 | else value+=grid[i][j1]+grid[i][j2]; 24 | 25 | value+=f(i+1, j1+dj1, j2+dj2, r, c, grid, dp); 26 | maxi=max(maxi,value); 27 | } 28 | } 29 | return dp[i][j1][j2]=maxi; 30 | } 31 | 32 | 33 | int maximumChocolates(int r, int c, vector> &grid) { 34 | vector>>dp(r,vector>(c,vector(c,-1))); 35 | 36 | return f(0, 0, c-1, r, c, grid, dp); 37 | } 38 | -------------------------------------------------------------------------------- /Course Schedule 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool dfs(int node,vector>& a,vector&vis,vector&pathvis,vector&ans){ 4 | vis[node]=1; 5 | pathvis[node]=1; 6 | 7 | for(auto it:a[node]){ 8 | if(!vis[it]){ 9 | if(dfs(it,a,vis,pathvis,ans)) return 1; 10 | } 11 | else if(pathvis[it]==1) return true; 12 | } 13 | 14 | pathvis[node]=0; 15 | ans.push_back(node); 16 | return false; 17 | } 18 | public: 19 | vector findOrder(int numCourses, vector>& prerequisites) { 20 | vector>adj(numCourses); 21 | 22 | for(auto it:prerequisites){ 23 | adj[it[1]].push_back(it[0]); 24 | } 25 | 26 | vectorvis(numCourses,0); 27 | vectorpathvis(numCourses,0); 28 | vectorans; 29 | 30 | for(int i=0;ival<=val){ 20 | if(curr->right!=NULL) curr=curr->right; 21 | else{ 22 | curr->right=new TreeNode(val); 23 | break; 24 | } 25 | } 26 | else{ 27 | if(curr->left!=NULL) curr=curr->left; 28 | else{ 29 | curr->left=new TreeNode(val); 30 | break; 31 | } 32 | } 33 | } 34 | return root; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Union of two sorted arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector unionArray(vector& nums1, vector& nums2) { 4 | int n1=nums1.size(); 5 | int n2=nums2.size(); 6 | int i=0,j=0; 7 | vectorans; 8 | 9 | while(inext; 21 | } 22 | return temp; 23 | } 24 | ListNode* rotateRight(ListNode* head, int k) { 25 | if(head==NULL || k==0) return head; 26 | ListNode* temp=head; 27 | int len=1; 28 | 29 | while(temp->next!=NULL){ 30 | temp=temp->next; 31 | len++; 32 | } 33 | 34 | if(k%len==0) return head; 35 | k=k%len; 36 | temp->next=head; 37 | 38 | ListNode* newnode=findnthnode(head,len-k); 39 | head=newnode->next; 40 | newnode->next=NULL; 41 | return head; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Sum of left leaves.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | void dfs(TreeNode* root, TreeNode* parent,long long int &sum){ 15 | if(root->right==NULL && root->left==NULL){ 16 | if(parent->left==root){ 17 | sum+=root->val; 18 | } 19 | } 20 | 21 | if(root->left) dfs(root->left,root,sum); 22 | if(root->right) dfs(root->right,root, sum); 23 | } 24 | 25 | public: 26 | int sumOfLeftLeaves(TreeNode* root) { 27 | if(root->left==NULL && root->right==NULL) return 0; 28 | 29 | long long int sum=0; 30 | if(root->left) 31 | dfs(root->left,root,sum); 32 | if(root->right){ 33 | dfs(root->right,root,sum); 34 | } 35 | return sum; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Add 2 numbers in linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 14 | ListNode* t1=l1; 15 | ListNode* t2=l2; 16 | ListNode* dnode=new ListNode(-1); 17 | ListNode* temp=dnode; 18 | int sum=0,carry=0; 19 | 20 | while(t1!=NULL || t2!=NULL){ 21 | sum=carry; 22 | if(t1) sum+=t1->val; 23 | if(t2) sum+=t2->val; 24 | 25 | ListNode* newnode=new ListNode(sum%10); 26 | temp->next=newnode; 27 | temp=temp->next; 28 | carry=sum/10; 29 | if(t1) t1=t1->next; 30 | if(t2) t2=t2->next; 31 | } 32 | if(carry){ 33 | ListNode* nnode=new ListNode(carry); 34 | temp->next=nnode; 35 | } 36 | return dnode->next; 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /4 sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> fourSum(vector& nums, int target) { 4 | int n=nums.size(); 5 | vector>ans; 6 | sort(nums.begin(),nums.end()); 7 | 8 | for(int i=0;i0 && nums[i]==nums[i-1]) continue; 10 | for(int j=i+1;ji+1 && nums[j]==nums[j-1]) continue; 12 | int k=j+1; 13 | int l=n-1; 14 | while(ktemp={nums[i],nums[j],nums[k],nums[l]}; 19 | ans.push_back(temp); 20 | k++; 21 | l--; 22 | while(k>& edges) { 4 | // code here 5 | int sum=0; 6 | vector>>adj(V); 7 | 8 | for(auto it:edges){ 9 | int u=it[0]; 10 | int v=it[1]; 11 | int w=it[2]; 12 | 13 | adj[u].push_back({v,w}); 14 | adj[v].push_back({u,w}); 15 | } 16 | 17 | priority_queue,vector>, 18 | greater>>pq; 19 | 20 | vectorvis(V,0); 21 | 22 | pq.push({0,0}); 23 | 24 | while(!pq.empty()){ 25 | int edgw=pq.top().first; 26 | int node=pq.top().second; 27 | pq.pop(); 28 | 29 | if(vis[node]) continue; 30 | 31 | vis[node]=1; 32 | sum+=edgw; 33 | 34 | for(auto &[neighbour,weight]:adj[node]){ 35 | if(!vis[neighbour]){ 36 | pq.push({weight,neighbour}); 37 | } 38 | } 39 | } 40 | 41 | return sum; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | bool dfs(TreeNode* root, int sum, int target){ 15 | if(root==NULL){ 16 | return 0; 17 | } 18 | sum+=root->val; 19 | 20 | if(root->left==NULL && root->right==NULL){ 21 | if(sum==target) return 1; 22 | return 0; 23 | } 24 | 25 | bool f1=0,f2=0; 26 | if(root->left){ 27 | f1=dfs(root->left,sum,target); 28 | } 29 | if(root->right){ 30 | f2=dfs(root->right,sum,target); 31 | } 32 | return f1| f2; 33 | } 34 | 35 | public: 36 | bool hasPathSum(TreeNode* root, int targetSum) { 37 | 38 | int sum=0; 39 | return dfs(root,sum,targetSum); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Ceil in a BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /************************************************************ 3 | 4 | Following is the TreeNode class structure: 5 | 6 | class BinaryTreeNode { 7 | public: 8 | T data; 9 | BinaryTreeNode *left; 10 | BinaryTreeNode *right; 11 | 12 | BinaryTreeNode(T data) { 13 | this->data = data; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | 18 | ~BinaryTreeNode() { 19 | if (left) { 20 | delete left; 21 | } 22 | if (right) { 23 | delete right; 24 | } 25 | } 26 | }; 27 | 28 | ************************************************************/ 29 | 30 | int findCeil(BinaryTreeNode *node, int key){ 31 | // Write your code here. 32 | BinaryTreeNode* temp=node; 33 | 34 | int ceil=-1; 35 | 36 | while(temp){ 37 | if(temp->data==key){ 38 | ceil=temp->data; 39 | return ceil; 40 | } 41 | if(key>temp->data) temp=temp->right; 42 | else{ 43 | ceil=temp->data; 44 | temp=temp->left; 45 | } 46 | } 47 | return ceil; 48 | } 49 | -------------------------------------------------------------------------------- /Shortest common supersequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shortestCommonSupersequence(string str1, string str2) { 4 | int n=str1.size(); 5 | int m=str2.size(); 6 | vector>dp(n+1,vector(m+1,0)); 7 | 8 | for(int i=1;i<=n;i++){ 9 | for(int j=1;j<=m;j++){ 10 | if(str1[i-1]==str2[j-1]) dp[i][j]=1+dp[i-1][j-1]; 11 | else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 12 | } 13 | } 14 | 15 | string ans=""; 16 | int i=n,j=m; 17 | 18 | while(i>0 && j>0){ 19 | if(str1[i-1]==str2[j-1]){ 20 | ans+=str1[i-1]; 21 | i--; 22 | j--; 23 | } 24 | else if(dp[i-1][j]>dp[i][j-1]){ 25 | ans+=str1[i-1]; 26 | i--; 27 | } 28 | else{ 29 | ans+=str2[j-1]; 30 | j--; 31 | } 32 | } 33 | 34 | while(i>0){ 35 | ans+=str1[i-1]; 36 | i--; 37 | } 38 | while(j>0){ 39 | ans+=str2[j-1]; 40 | j--; 41 | } 42 | reverse(ans.begin(),ans.end()); 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Remove duplicates from sorted doubly linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of doubly linked list: 3 | * class Node { 4 | * public: 5 | * int data; 6 | * Node *prev; 7 | * Node *next; 8 | * Node() { 9 | * this->data = 0; 10 | * this->prev = NULL; 11 | * this->next = NULL; 12 | * } 13 | * Node(int data) { 14 | * this->data = data; 15 | * this->prev = NULL; 16 | * this->next = NULL; 17 | * } 18 | * Node (int data, Node *next, Node *prev) { 19 | * this->data = data; 20 | * this->prev = prev; 21 | * this->next = next; 22 | * } 23 | * }; 24 | * 25 | *************************************************************************/ 26 | 27 | Node * removeDuplicates(Node *head) 28 | { 29 | Node* temp=head; 30 | 31 | while(temp!=NULL && temp->next!=NULL){ 32 | Node* nextnode=temp->next; 33 | while(nextnode!=NULL && nextnode->data==temp->data){ 34 | Node* duplicate=nextnode; 35 | nextnode=nextnode->next; 36 | free(duplicate); 37 | } 38 | temp->next=nextnode; 39 | if(nextnode) nextnode->prev=temp; 40 | temp=temp->next; 41 | } 42 | return head; 43 | } 44 | -------------------------------------------------------------------------------- /Median of two sorted arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | int n1=nums1.size(),n2=nums2.size(); 5 | int i=0,j=0; 6 | int n=(n1+n2); 7 | int ind1=n/2,ind2=n/2-1; 8 | int cnt=0,ele1=-1,ele2=-1; 9 | 10 | while(i>&grid, vector>&vis,long long int &sum, int m, int n){ 4 | vis[i][j]=1; 5 | sum+=grid[i][j]; 6 | 7 | if(i+1=0 && vis[i-1][j]==0 && grid[i-1][j]!=0){ 12 | dfs(i-1,j,grid,vis,sum,m,n); 13 | } 14 | 15 | if(j+1=0 && vis[i][j-1]==0 && grid[i][j-1]!=0){ 20 | dfs(i,j-1,grid,vis,sum,m,n); 21 | } 22 | } 23 | 24 | int countIslands(vector>& grid, int k) { 25 | int m=grid.size(),n=grid[0].size(); 26 | vector>vis(m,vector(n,0)); 27 | 28 | int cnt=0; 29 | 30 | for(int i=0;i> updateMatrix(vector>& mat) { 4 | int m=mat.size(); 5 | int n=mat[0].size(); 6 | vector>vis(m,vector(n,0)); 7 | vector>dis(m,vector(n,0)); 8 | queue,int>>q; 9 | 10 | for(int i=0;i=0 && nrow=0 && ncoldata = 0; 11 | * this->prev = NULL; 12 | * this->next = NULL; 13 | * } 14 | * Node(int data) { 15 | * this->data = data; 16 | * this->prev = NULL; 17 | * this->next = NULL; 18 | * } 19 | * Node (int data, Node *next, Node *prev) { 20 | * this->data = data; 21 | * this->prev = prev; 22 | * this->next = next; 23 | * } 24 | * }; 25 | * 26 | *************************************************************************/ 27 | 28 | Node * deleteAllOccurrences(Node* head, int k) { 29 | // Write your code here 30 | Node* temp=head; 31 | 32 | while(temp!=NULL){ 33 | if(temp->data==k){ 34 | if(temp==head) head=head->next; 35 | 36 | Node* nextnode=temp->next; 37 | Node* prevnode=temp->prev; 38 | if(nextnode) nextnode->prev=temp; 39 | if(prevnode) prevnode->next=nextnode; 40 | temp=nextnode; 41 | } 42 | else temp=temp->next; 43 | } 44 | return head; 45 | } 46 | -------------------------------------------------------------------------------- /Binary Tree Zigzag Order traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> zigzagLevelOrder(TreeNode* root) { 15 | vector>ans; 16 | if(root==NULL) return ans; 17 | queueq; 18 | q.push(root); 19 | bool f=1; 20 | 21 | while(!q.empty()){ 22 | int size=q.size(); 23 | vectortemp(size); 24 | for(int i=0;ival; 30 | if(node->left){ 31 | q.push(node->left); 32 | } 33 | if(node->right){ 34 | q.push(node->right); 35 | } 36 | } 37 | f=!f; 38 | ans.push_back(temp); 39 | } 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Sum Of Subarray minimums.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void findnse(vector&ans, vector&arr){ 5 | stackst; 6 | int n=arr.size(); 7 | 8 | for(int i=n-1;i>=0;i--){ 9 | while(!st.empty() && arr[st.top()]>=arr[i]){ 10 | st.pop(); 11 | } 12 | if(st.empty()) ans[i]=n; 13 | else ans[i]=st.top(); 14 | st.push(i); 15 | } 16 | } 17 | 18 | void findpse(vector&ans, vector&arr){ 19 | stackst; 20 | int n=arr.size(); 21 | 22 | for(int i=0;iarr[i]){ 24 | st.pop(); 25 | } 26 | if(st.empty()) ans[i]=-1; 27 | else ans[i]=st.top(); 28 | st.push(i); 29 | } 30 | } 31 | 32 | int sumSubarrayMins(vector& arr) { 33 | int n=arr.size(); 34 | long long int mod=1e9+7; 35 | vectornse(n); 36 | findnse(nse,arr); 37 | vectorpse(n); 38 | findpse(pse,arr); 39 | 40 | long long int total=0; 41 | for(int i=0;i>& edges, vector&vis){ 5 | vis[src]=1; 6 | queue>q; 7 | q.push({src,-1}); 8 | 9 | while(!q.empty()){ 10 | int node=q.front().first; 11 | int parent=q.front().second; 12 | q.pop(); 13 | 14 | for(auto adjacentnode:edges[node]){ 15 | if(!vis[adjacentnode]){ 16 | vis[adjacentnode]=1; 17 | q.push({adjacentnode,node}); 18 | } 19 | else if(parent!=adjacentnode) return 1; 20 | } 21 | } 22 | return 0; 23 | } 24 | 25 | 26 | public: 27 | bool isCycle(int v, vector>& edges) { 28 | // Code here 29 | vector>adj(v); 30 | 31 | for(auto it:edges){ 32 | adj[it[0]].push_back(it[1]); 33 | adj[it[1]].push_back(it[0]); 34 | } 35 | vectorvis(v,0); 36 | 37 | for(int i=0;i&val, vector&wt, vector>&dp){ 5 | // if(ind==0){ 6 | // if(wt[0]<=w) return val[0]; 7 | // return 0; 8 | // } 9 | 10 | // if(dp[ind][w]!=-1) return dp[ind][w]; 11 | 12 | // int nottake=0,take=0; 13 | // nottake=helper(ind-1,w,val,wt,dp); 14 | 15 | // if(wt[ind]<=w) take=val[ind]+helper(ind-1,w-wt[ind],val,wt,dp); 16 | 17 | // return dp[ind][w]=max(take,nottake); 18 | // } 19 | 20 | 21 | public: 22 | int knapsack(int W, vector &val, vector &wt) { 23 | // code here 24 | int n=wt.size(); 25 | 26 | // vector>dp(n,vector(W+1,0)); 27 | 28 | vectorcurr(W+1,0); 29 | 30 | for(int i=wt[0];i<=W;i++){ 31 | curr[i]=val[0]; 32 | } 33 | 34 | for(int i=1;i=0;j--){ 36 | int nottake=0,take=0; 37 | nottake=curr[j]; 38 | if(wt[i]<=j) take=val[i]+curr[j-wt[i]]; 39 | 40 | curr[j]=max(take,nottake); 41 | } 42 | // prev=curr; 43 | } 44 | return curr[W]; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /0/1 Knapsack.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // private: 3 | // int helper(int ind, int w, vector&val, vector&wt, vector>&dp){ 5 | // if(ind==0){ 6 | // if(wt[0]<=w) return val[0]; 7 | // return 0; 8 | // } 9 | 10 | // if(dp[ind][w]!=-1) return dp[ind][w]; 11 | 12 | // int nottake=0,take=0; 13 | // nottake=helper(ind-1,w,val,wt,dp); 14 | 15 | // if(wt[ind]<=w) take=val[ind]+helper(ind-1,w-wt[ind],val,wt,dp); 16 | 17 | // return dp[ind][w]=max(take,nottake); 18 | // } 19 | 20 | 21 | public: 22 | int knapsack(int W, vector &val, vector &wt) { 23 | // code here 24 | int n=wt.size(); 25 | 26 | // vector>dp(n,vector(W+1,0)); 27 | 28 | vectorcurr(W+1,0); 29 | 30 | for(int i=wt[0];i<=W;i++){ 31 | curr[i]=val[0]; 32 | } 33 | 34 | for(int i=1;i=0;j--){ 36 | int nottake=0,take=0; 37 | nottake=curr[j]; 38 | if(wt[i]<=j) take=val[i]+curr[j-wt[i]]; 39 | 40 | curr[j]=max(take,nottake); 41 | } 42 | // prev=curr; 43 | } 44 | return curr[W]; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Cycle detection in undirected graph using bfs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | 4 | bool detect(int src, vector>& edges, vector&vis){ 5 | vis[src]=1; 6 | queue>q; 7 | q.push({src,-1}); 8 | 9 | while(!q.empty()){ 10 | int node=q.front().first; 11 | int parent=q.front().second; 12 | q.pop(); 13 | 14 | for(auto adjacentnode:edges[node]){ 15 | if(!vis[adjacentnode]){ 16 | vis[adjacentnode]=1; 17 | q.push({adjacentnode,node}); 18 | } 19 | else if(parent!=adjacentnode) return 1; 20 | } 21 | } 22 | return 0; 23 | } 24 | 25 | 26 | public: 27 | bool isCycle(int v, vector>& edges) { 28 | // Code here 29 | vector>adj(v); 30 | 31 | for(auto it:edges){ 32 | adj[it[0]].push_back(it[1]); 33 | adj[it[1]].push_back(it[0]); 34 | } 35 | vectorvis(v,0); 36 | 37 | for(int i=0;i