├── Trees ├── maximum-depth-of-binary-tree.cpp ├── path-sum.cpp ├── convert-bst-to-greater-tree.cpp ├── LeetCode-98-Validate-Binary-Search-Tree.cpp ├── binary_tree_pruning.cpp ├── range-sum-of-bst.cpp ├── bst-to-greater-sum-tree.cpp ├── LeetCode-1008-Construct-Binary-Search-Tree-from-Preorder-Traversal.cpp ├── LeetCode-235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cpp ├── trim-a-binary-search-tree.cpp ├── Leetcode-653-Two-Sum-IV-Input-is-a-BST.cpp ├── binary-tree-right-side-view.cpp ├── diagonal-traversal-of-binary-tree.cpp ├── increasing-order-search-tree.cpp ├── LeetCode-173-Binary-Search-Tree-Iterator.cpp ├── LeetCode-337-House-Robber-III.cpp ├── deepest-leaves-sum.cpp ├── bst-to-max-heap.cpp ├── n-ary-tree-level-order-traversal.cpp ├── Leetcode-701-Insert-into-a-Binary-Search-Tree.cpp ├── LeetCode-1372-Longest-ZigZag-Path-in-a-Binary-Tree.cpp ├── pseudo-palindromic-paths-in-a-binary-tree.cpp ├── average-of-levels-in-binary-tree.cpp ├── Leetcode-99-Recover-Binary-Search-Tree.cpp ├── vertical-order-traversal-of-a-binary-tree.cpp ├── Construct-the-Binary-Tree-from-Postorder-and-Inorder-Traversal.cpp ├── Construct-a-Binary-Tree-from-Preorder-and-Inorder-Traversal.cpp ├── LeetCode-114-Flatten-Binary-Tree-to-Linked-List.cpp ├── LeetCode-230-Kth-Smallest-Element-in-a-BST.cpp └── LeetCode-450-Delete-Node-in-a-BST.cpp ├── Bit-Manipulation ├── number-of-1-bits.cpp ├── finding-profession.cpp └── counting-bits.cpp ├── Mathematics ├── count-odd-numbers-in-an-interval-range.cpp ├── power_of_four.cpp ├── arithmetic-slices.cpp ├── check-if-it-is-a-straight-line.cpp ├── counting-divisors.cpp ├── Exponentiation.cpp ├── Exponentiation-II.cpp ├── broken-calculator.cpp └── maximum-split-of-positive-even-integers.cpp ├── code-studio-contest ├── minimize-bill.cpp ├── two-zeroes.cpp ├── lucky-string.cpp ├── maximum-value-of-F(x).cpp └── count-the-people.cpp ├── Vector-Array ├── rotate-array.cpp ├── reshape-the-matrix.cpp ├── static-range-sum-queries.cpp ├── range-xor-queries.cpp ├── wiggle-subsequence.cpp ├── maximum-points-you-can-obtain-from-cards.cpp ├── container-with-most-water.cpp ├── non-decreasing-array.cpp ├── Kadane.cpp ├── find-the-duplicate-number.cpp ├── sum-of-even-numbers-after-queries.cpp ├── hit-and-blow.cpp ├── next-permutation.cpp ├── forest-queries.cpp ├── TappingRainWater.cpp ├── shortest-unsorted-continuous-subarray.cpp ├── Max_circular_sub_array.cpp ├── find-pivot-index.cpp └── minimum-average-difference.cpp ├── README.md ├── LinkedList ├── Reverse-Linked-List.cpp ├── maximum-twin-sum-of-a-linked-list.cpp ├── LeetCode-141-Cycle-Detection.cpp ├── remove-duplicate-from-sorted-list.cpp ├── rotate-list.cpp ├── swap-nodes-in-pair.cpp ├── copy-list-with-random-pointer.cpp ├── merge-nodes-in-between-zeros.cpp ├── remove-duplicates-from-sorted-list-II.cpp ├── circular_LinkedList.cpp ├── intersection-of-two-linked-lists.cpp ├── LeetCode-234-Palindrome-Linked-List.cpp └── Create_list.cpp ├── Hashmap-Heap ├── isAnagram.cpp ├── redistribute-characters-to-make-all-strings-equal.cpp ├── smaller-on-left.cpp ├── encode-and-decode-tinyurl.cpp ├── kth-largest-element-in-a-stream.cpp ├── two-sum.cpp ├── queue-reconstruction-by-height.cpp ├── top-k-frequent-elements.cpp ├── continuous-subarray-sum.cpp ├── find-original-array-from-doubled-array.cpp ├── three-sum-with-multiplicity.cpp ├── last-stone-weight.cpp ├── longest-consecutive-sequence.cpp ├── minimize-deviation-in-array.cpp ├── maximum-erasure-value.cpp ├── furthest-building-you-can-reach.cpp ├── find-all-anagrams-in-a-string.cpp ├── minimum-deletions-to-make-character-frequencies-unique.cpp ├── minimum number of steps to Make two strings anagram II.cpp ├── split-array-into-consecutive-subsequences.cpp ├── longest-substring-without-repeating-characters.cpp └── valid-sudoku.cpp ├── Dynamic-Programming ├── n-th-tribonacci-number.cpp ├── count-possible-ways-to-construct-buildings.cpp ├── house-robber.cpp ├── unique-paths.cpp ├── knapsac_-with_duplicate_items4201.cpp ├── longest_common_substring.cpp ├── rod-cutting.cpp ├── zero_one_knapsnap.cpp ├── coin_change.cpp ├── house-robber-II.cpp ├── fibonacci.cpp ├── minimum-falling-path-sum.cpp ├── partition-equal-subset-sum.cpp ├── frog-jump.cpp ├── target_sum.cpp ├── print-longest-common-subsequence-dp.cpp ├── shortest-common-supersequence.cpp ├── max-sum-without-adjacents.cpp └── vacation.cpp ├── CSES-Problem-Set ├── searching-sorting │ ├── reading-books.cpp │ ├── stick-lengths.cpp │ ├── collecting-numbers.cpp │ ├── missing-coin-sum.cpp │ ├── josephus-problem-I.cpp │ ├── tasks-and-deadlines.cpp │ ├── towers.cpp │ ├── factory-machines.cpp │ ├── restaurant-customers.cpp │ ├── ferris-wheel.cpp │ ├── playlist.cpp │ ├── apartments.cpp │ ├── learest-smaller-values.cpp │ ├── movie-festival-II.cpp │ ├── concert-tickets.cpp │ ├── traffic-lights.cpp │ └── room-alocation.cpp ├── trees │ ├── Tree-Diameter.cpp │ ├── subordinates.cpp │ ├── finding-a-centroid.cpp │ ├── Tree-Distances-I.cpp │ ├── distinct-colors.cpp │ ├── company-queries-I.cpp │ ├── company-queries-II.cpp │ └── distance-queries.cpp └── graph │ ├── building-roads.cpp │ ├── shortest-routes-II.cpp │ ├── counting-rooms.cpp │ ├── road-construction.cpp │ ├── message-route.cpp │ ├── flight-routes.cpp │ ├── shortest-routes-I.cpp │ ├── road-reparation.cpp │ ├── round-trip.cpp │ ├── building-teams.cpp │ └── course-schedule.cpp ├── Adv-Graph-Trees ├── sum-of-left-leaves.cpp ├── delete-edge.cpp ├── chef-and-reversing.cpp ├── city-and-flood.cpp └── city-and-campers.cpp ├── Matrix ├── transpose-matrix.cpp ├── spiral-matrix-ii.cpp ├── shift-2d-grid.cpp └── spiral-matrix.cpp ├── Strings ├── minimum-times-A-has-to-be-repeated-such-that-B-is-a-substring-of-it.cpp ├── implement-strStr().cpp ├── partition-labels.cpp ├── Smallest String With a-given-numeric-value.cpp ├── backspace-string-compare.cpp ├── word-subsets.cpp ├── gray-code.cpp ├── find-duplicate-file-in-system.cpp └── minimum-remove-to-make-valid-parentheses.cpp ├── Searching ├── Binary-Search.cpp ├── smallest-greater-elements-in-whole-array.cpp ├── search-a-2D-matrix.cpp ├── search-in-rotated-sorted-array-II.cpp ├── kth-smallest-element-in-a-sorted-matrix.cpp ├── split-array-largest-sum.cpp ├── successful-pairs-of-spells-and-potions.cpp └── maximum-candies-allocated-to-k-children.cpp ├── Stack-Queue ├── validate-stack-sequences.cpp ├── maximum-frequency-stack.cpp ├── simplify-path.cpp ├── longest-valid-parentheses.cpp ├── implement-stack-using-queues.cpp ├── sliding-window-maximum.cpp ├── remove-K-digits.cpp ├── remove-all-adjacent-duplicates-in-string-ii.cpp ├── score-of-parentheses.cpp └── smallest-subsequence-of-distinct-characters.cpp ├── Sorting ├── boats to-save-people.cpp ├── minimum-moves-to-equal-array-elements-ii.cpp ├── maximum-units-on-a-truck.cpp ├── merge-intervals.cpp ├── InsertionSort.cpp ├── SelectionSort.cpp ├── BubbleSort.cpp ├── max-number-of-k-sum-pairs.cpp ├── the-k-weakest-rows-in-a-matrix.cpp └── MergeSort.cpp ├── Greedy ├── candy.cpp ├── two-city-scheduling.cpp ├── trapping-rain-water.cpp └── stamping-the-sequence.cpp ├── Recursion-Backtracking ├── subsets-II.cpp ├── k-th-symbol-in-grammar.cpp ├── permutation-sequence.cpp ├── numbers-with-same-consecutive-differences.cpp ├── combination-sum.cpp ├── combination-sum-II.cpp ├── permutations-II.cpp ├── letter-case-permutation.cpp ├── palindrome-partitioning.cpp ├── count-occurences-of-a-given-word-in-a-2-d-array.cpp └── n-queens.cpp ├── Graphs ├── keys-and-rooms.cpp ├── time-needed-to-inform-all-employees.cpp ├── stepping-numbers.cpp ├── flood-fill.cpp ├── Dijkstra.cpp ├── number-of-enclaves.cpp ├── possible-bipartition.cpp ├── count-sub-islands.cpp ├── find-eventual-safe-states.cpp ├── zero-one-matrix.cpp ├── path-with-minimum-effort.cpp ├── Leetcode-743-network-delay-time.cpp ├── dfs.cpp ├── bellman-ford.cpp ├── as-far-from-land-as-possible.cpp ├── shortest-path-in-binary-matrix.cpp ├── number-of-ways-to-arrive-at-destination.cpp ├── bfs.cpp ├── coloring-a-border.cpp └── min-cost-to-connect-all-points.cpp ├── OOPS └── design-underground-system.cpp └── number-of-nodes-in-the-sub-tree-with-the-same-label.cpp /Trees/maximum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(TreeNode* root) { 4 | if(root==NULL) return 0; 5 | return max(maxDepth(root->left),maxDepth(root->right))+1; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Bit-Manipulation/number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int cnt=0; 5 | while(n){ 6 | cnt++; 7 | n=n&(n-1); 8 | } 9 | return cnt; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Mathematics/count-odd-numbers-in-an-interval-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOdds(int low, int high) { 4 | int num=high-low; 5 | num=num/2; 6 | if(low&1 || high&1)num++; 7 | return num; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /code-studio-contest/minimize-bill.cpp: -------------------------------------------------------------------------------- 1 | long long totalBill(int n, vector& a) 2 | { 3 | long long sum=0; 4 | int maxi=a[0]; 5 | for(auto it:a){ 6 | maxi=max(maxi,it); 7 | sum+=it; 8 | } 9 | sum=sum-(2*maxi); 10 | return sum; 11 | } 12 | -------------------------------------------------------------------------------- /Vector-Array/rotate-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | int n=nums.size(); 5 | k=k%n; 6 | reverse(nums.begin(),nums.begin()+n-k); 7 | reverse(nums.begin()+n-k,nums.end()); 8 | reverse(nums.begin(),nums.end()); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Bit-Manipulation/finding-profession.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://practice.geeksforgeeks.org/problems/finding-profession3834/1 3 | 4 | char profession(int n, int pos){ 5 | bool flip = false ; 6 | while(pos != 1){ 7 | if(pos%2 == 0) 8 | flip = !flip ; 9 | pos = (pos+1)/2 ; 10 | } 11 | return (flip ? 'd' : 'e') ; 12 | } 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-structure-and-Algorithm 2 | ## In C++ 3 | ### Data structure implementation :slightly_smiling_face: 4 | ### Application of DSA 5 | ### problems from LeetCode , InterviewBit , GFG , CSES 6 | ### DSA Notes :notebook_with_decorative_cover: 7 | ![DSA](https://user-images.githubusercontent.com/55646472/93663733-9d037580-fa87-11ea-9941-f383226a34f2.png) 8 | 9 | 10 | -------------------------------------------------------------------------------- /Trees/path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasPathSum(TreeNode* root, int targetSum) { 4 | if(root==NULL) return false; 5 | targetSum=targetSum-root->val; 6 | if(targetSum==0 && root->left==NULL && root->right==NULL) return true; 7 | return hasPathSum(root->left,targetSum) || hasPathSum(root->right,targetSum); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /LinkedList/Reverse-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverseList(ListNode* head) { 4 | ListNode* cnt =head; 5 | ListNode* prev=nullptr; 6 | while(head){ 7 | head=head->next; 8 | cnt->next=prev; 9 | prev=cnt; 10 | cnt=head; 11 | } 12 | return prev; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Mathematics/power_of_four.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/power-of-four/ 3 | 4 | bool isPowerOfFour(int n) { 5 | if(n<=0 ){ 6 | return false; 7 | } 8 | if(n==1){ 9 | return true; 10 | } 11 | if(n%4!=0){ 12 | return false; 13 | } 14 | return isPowerOfFour(n/4); 15 | } 16 | -------------------------------------------------------------------------------- /Mathematics/arithmetic-slices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector& A) { 4 | int curr = 0, sum = 0; 5 | for (int i = 2; i < A.size(); i++) { 6 | if ((long)A[i] - A[i - 1] == (long)A[i - 1] - A[i - 2]) { 7 | curr += 1; 8 | sum += curr; 9 | } 10 | else curr = 0; 11 | } 12 | return sum; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Hashmap-Heap/isAnagram.cpp: -------------------------------------------------------------------------------- 1 | // Anagram 2 | class Solution { 3 | public: 4 | bool isAnagram(string s, string t) { 5 | mapmp; 6 | for(auto x:s){ 7 | mp[x]++; 8 | } 9 | for(auto x:t){ 10 | mp[x]--; 11 | } 12 | for(auto it:mp){ 13 | if(it.second!=0)return false; 14 | } 15 | return true; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Trees/convert-bst-to-greater-tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/convert-bst-to-greater-tree/ 3 | 4 | class Solution { 5 | public: 6 | int sum=0; 7 | TreeNode* convertBST(TreeNode* root) { 8 | if(root==NULL)return NULL; 9 | convertBST(root->right); 10 | sum+=root->val; 11 | root->val=sum; 12 | convertBST(root->left); 13 | return root; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Trees/LeetCode-98-Validate-Binary-Search-Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isv(TreeNode* root,long maxi,long mini){ 4 | if(root==NULL)return true; 5 | if(root->val>=maxi || root->val<=mini) return false; 6 | return (isv(root->left,root->val,mini) && isv(root->right,maxi,root->val)); 7 | } 8 | bool isValidBST(TreeNode* root) { 9 | return isv(root,LONG_MAX,LONG_MIN); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Vector-Array/reshape-the-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> matrixReshape(vector>& mat, int r, int c) { 4 | int n=mat.size(); 5 | int m=mat[0].size(); 6 | if(r*c!=n*m)return mat; 7 | vector>vec(r,vector(c)); 8 | for(int i=0;i=l && num<=r){ 11 | ans++; 12 | } 13 | } 14 | } 15 | } 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Trees/binary_tree_pruning.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/binary-tree-pruning/ 3 | 4 | class Solution { 5 | public: 6 | TreeNode* pruneTree(TreeNode* root) { 7 | if (root == NULL) return NULL; 8 | root->left = pruneTree(root->left); 9 | root->right = pruneTree(root->right); 10 | if (root->val == 1 || root->left != NULL || root->right != NULL) return root; 11 | return NULL; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Dynamic-Programming/n-th-tribonacci-number.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/n-th-tribonacci-number/ 3 | 4 | 5 | class Solution { 6 | public: 7 | int tribonacci(int n) { 8 | if(n<2)return n; 9 | vectordp(n+1,0); 10 | dp[0]=0; 11 | dp[1]=1; 12 | dp[2]=1; 13 | for(int i=3;i<=n;i++){ 14 | dp[i]=dp[i-1]+dp[i-2]+dp[i-3]; 15 | } 16 | return dp[n]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Hashmap-Heap/redistribute-characters-to-make-all-strings-equal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool makeEqual(vector& words) { 4 | mapmp; 5 | for(auto c:words){ 6 | for(auto x:c){ 7 | mp[x]++; 8 | } 9 | } 10 | int n=words.size(); 11 | for(auto it:mp){ 12 | if(it.second%n!=0)return false; 13 | } 14 | return true; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Trees/range-sum-of-bst.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeSumBST(TreeNode* root, int L, int R) { 4 | if(root==NULL){ 5 | return 0; 6 | } 7 | else{ 8 | int sum=rangeSumBST( root->left, L, R)+rangeSumBST(root->right, L, R); 9 | if(root->val>=L && root->val<=R){ 10 | sum+=root->val; 11 | } 12 | return sum; 13 | } 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Vector-Array/static-range-sum-queries.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1646 2 | #include 3 | using namespace std; 4 | #define int long long 5 | signed main() { 6 | int n,m; 7 | cin>>n>>m; 8 | vectorarr(n+5); 9 | vectorpref(n+5); 10 | for(int i=1;i<=n;i++){ 11 | cin>>arr[i]; 12 | pref[i]=pref[i-1]+arr[i]; 13 | } 14 | while(m--){ 15 | int a,b; 16 | cin>>a>>b; 17 | cout< 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | vectorarr(n); 11 | for(auto &a:arr){ 12 | cin>>a; 13 | } 14 | int maxi=INT_MIN,sum=0; 15 | for(auto a:arr){ 16 | sum+=a; 17 | maxi=max(maxi,a); 18 | } 19 | cout<>& coordinates ) { 4 | int dY = coordinates[1][1] - coordinates[0][1]; 5 | int dX = coordinates[1][0] - coordinates[0][0]; 6 | for( int i=2; i < coordinates.size(); i++ ) { 7 | auto p = coordinates[i]; 8 | if( dX*(p[1] - coordinates[0][1]) != dY*(p[0] - coordinates[0][0]) ) 9 | return false; 10 | } 11 | return true; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Trees/bst-to-greater-sum-tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://practice.geeksforgeeks.org/problems/bst-to-greater-sum-tree/1# 3 | 4 | class Solution 5 | { 6 | public: 7 | int prev=0; 8 | void transformTree(struct Node *root) 9 | { 10 | if(root==NULL)return; 11 | transformTree(root->right); 12 | int s=root->data+prev; 13 | root->data=prev; 14 | prev=s; 15 | transformTree(root->left); 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /code-studio-contest/lucky-string.cpp: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/lucky-string_3583485?source=youtube&campaign=Strivercontest6thfeb&utm_source=youtube&utm_medium=affiliate&utm_campaign=Strivercontest6thfeb&leftPanelTab=0 2 | 3 | int makeLucky(string s, int n) 4 | { 5 | int cnt=0; 6 | 7 | for(int i=1;ileft && !root->right){ 10 | if(is_left) 11 | return root->val; 12 | } 13 | 14 | return sumOfLeftLeaves(root->left,true) + sumOfLeftLeaves(root->right,false); 15 | } 16 | 17 | }; 18 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/stick-lengths.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1074/ 2 | #include 3 | using namespace std; 4 | #define mod (int) (1e9+7) 5 | #define int long long 6 | signed main() { 7 | int n; 8 | cin>>n; 9 | vector nums(n); 10 | for(auto &N:nums){ 11 | cin>>N; 12 | } 13 | int ans=0; 14 | sort(nums.begin(),nums.end()); 15 | for(auto x:nums){ 16 | ans+=abs(x-nums[n/2]); 17 | } 18 | cout< 4 | using namespace std; 5 | #define int long long 6 | signed main() { 7 | int n,m; 8 | cin>>n>>m; 9 | vectorarr(n+5); 10 | vectorpref(n+5); 11 | for(int i=1;i<=n;i++){ 12 | cin>>arr[i]; 13 | pref[i]=pref[i-1]^arr[i]; 14 | } 15 | while(m--){ 16 | int a,b; 17 | cin>>a>>b; 18 | cout<<(pref[b]^pref[a-1])<vec; 5 | while(head){ 6 | vec.push_back(head->val); 7 | head=head->next; 8 | } 9 | int i=0,j=vec.size()-1; 10 | int ans=INT_MIN; 11 | while(i 4 | using namespace std; 5 | #define MOD (int) (1e9+7) 6 | signed main() { 7 | int t; 8 | cin>>t; 9 | while(t--){ 10 | int n; 11 | cin>>n; 12 | vectorvec; 13 | for(int i=1;i*i<=n;i++){ 14 | if(n%i==0){ 15 | vec.push_back(i); 16 | if((i*i)!=n){ 17 | vec.push_back(n/i); 18 | } 19 | } 20 | } 21 | cout<next) 8 | { 9 | slow=slow->next; 10 | fast=fast->next->next; 11 | 12 | if(slow==fast) 13 | return true; 14 | 15 | } 16 | 17 | return false; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Mathematics/Exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MOD (int) (1e9+7) 4 | #define int long long 5 | int powfast(int a,int b,int m){ 6 | if(b==0)return 1; 7 | int val=powfast(a,b/2,m); 8 | if(b & 1){ 9 | return (((a*val)%m)*val)%m; 10 | } 11 | else{ 12 | return (val*val)%m; 13 | } 14 | } 15 | signed main() { 16 | 17 | int t; 18 | cin>>t; 19 | while(t--){ 20 | int a,b; 21 | cin>>a>>b; 22 | cout< 3 | using namespace std; 4 | #define mod (int) (1e9+7) 5 | #define int long long 6 | signed main() { 7 | int n; 8 | cin>>n; 9 | vector nums(n); 10 | for(auto &N:nums){ 11 | cin>>N; 12 | } 13 | int ans=0; 14 | vectorfreq(n+1,-1); 15 | for(auto t:nums){ 16 | if(freq[t-1]==-1){ 17 | ans++; 18 | } 19 | freq[t]++; 20 | } 21 | cout< 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | vector nums(n); 11 | for(auto &N:nums){ 12 | cin>>N; 13 | } 14 | int ans=1; 15 | sort(nums.begin(),nums.end()); 16 | for(auto x:nums){ 17 | if(ans> transpose(vector>& matrix) { 7 | int n=matrix.size(); 8 | int m=matrix[0].size(); 9 | vector>trans(m,vector(n)); 10 | for(int i=0;i& p,int& i,int maxi){ 4 | if(i==p.size()|| p[i]>maxi) return NULL; 5 | TreeNode* root=new TreeNode(p[i++]); 6 | root->left=buildt(p,i,root->val); 7 | root->right=buildt(p,i,maxi); 8 | return root; 9 | } 10 | TreeNode* bstFromPreorder(vector& p) { 11 | int i=0; 12 | return buildt(p,i,INT_MAX); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Hashmap-Heap/smaller-on-left.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://practice.geeksforgeeks.org/problems/smaller-on-left20360700/1 2 | 3 | vector Smallestonleft(int arr[], int n) 4 | { 5 | setst; 6 | vectorvec; 7 | for(int i=0;inext!=nullptr){ 8 | if(it->val==it->next->val){ 9 | it->next=it->next->next; 10 | } 11 | else{ 12 | it=it->next; 13 | } 14 | } 15 | return head; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Trees/LeetCode-235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 5 | if(root==NULL)return NULL; 6 | if(p->val< root->val && q->valval){ 7 | return lowestCommonAncestor(root->left,p,q); 8 | } 9 | if(p->val> root->val && q->val>root->val){ 10 | return lowestCommonAncestor(root->right,p,q); 11 | } 12 | return root; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Trees/trim-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/trim-a-binary-search-tree/ 3 | 4 | class Solution { 5 | public: 6 | TreeNode* trimBST(TreeNode* root, int low, int high) { 7 | if(!root)return NULL; 8 | if(root->valright,low,high); 9 | else if(root->val>high)return trimBST(root->left,low,high); 10 | root->left=trimBST(root->left,low,high); 11 | root->right=trimBST(root->right,low,high); 12 | return root; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/josephus-problem-I.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/2162/ 2 | 3 | #include 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | dequedq; 11 | for(int i=1;i<=n;i++){ 12 | dq.push_back(i); 13 | } 14 | while(!dq.empty()){ 15 | int x=dq.front(); 16 | dq.push_back(x); 17 | dq.pop_front(); 18 | cout< 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | vector>arr(n); 11 | for(auto &a:arr){ 12 | cin>>a.first>>a.second; 13 | } 14 | sort(arr.begin(),arr.end()); 15 | int time=0,rew=0; 16 | for(auto t:arr){ 17 | time+=t.first; 18 | rew+=(t.second-time); 19 | } 20 | cout< 2 | #define ll long long int 3 | using namespace std; 4 | vectoradj[200005]; 5 | int d=0,x=0; 6 | void dfs(int s,int p,int dep){ 7 | for(auto c:adj[s]){ 8 | if(c!=p) dfs(c,s,dep+1); 9 | } 10 | if(dep>d)d=dep,x=s; 11 | } 12 | int main() { 13 | int n; 14 | cin>>n; 15 | for(int i=0;i>a>>b; 18 | 19 | adj[a].push_back(b); 20 | adj[b].push_back(a); 21 | } 22 | dfs(1,0,0); 23 | dfs(x,0,0); 24 | cout<& nums) { 7 | int n=nums.size(); 8 | int prev1=nums[0]; 9 | int prev2=0; 10 | for(int i=1;i1)pick+=prev2; 13 | int notpick=0+prev1; 14 | int curr=max(pick,notpick); 15 | prev2=prev1; 16 | prev1=curr; 17 | } 18 | return prev1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Trees/Leetcode-653-Two-Sum-IV-Input-is-a-BST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | setst; 4 | bool ans=false; 5 | void inord(TreeNode* root,int k){ 6 | if(root==NULL)return; 7 | if(st.find(k-(root->val))!=st.end()){ 8 | ans=true; 9 | return; 10 | } 11 | st.insert(root->val); 12 | 13 | inord(root->left,k); 14 | inord(root->right,k); 15 | } 16 | 17 | bool findTarget(TreeNode* root, int k) { 18 | inord(root,k); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/towers.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1073/ 2 | 3 | #include 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | vector nums(n); 11 | for(auto &N:nums){ 12 | cin>>N; 13 | } 14 | multisetmt; 15 | for(auto a:nums){ 16 | auto it=mt.upper_bound(a); 17 | if(it!=mt.end()){ 18 | mt.erase(it); 19 | mt.insert(a); 20 | } 21 | else{ 22 | mt.insert(a); 23 | } 24 | } 25 | cout<>dp(m,vector(n)); 8 | for(int i=0;i& nums, int target) { 4 | int lo=0; 5 | int hi=nums.size()-1; 6 | while(lo<=hi){ 7 | int mid=lo+(hi-lo)/2; 8 | if(nums[mid]==target){ 9 | return mid; 10 | } 11 | else if(nums[mid]>target){ 12 | hi=mid-1; 13 | } 14 | else{ 15 | lo=mid+1; 16 | 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LinkedList/rotate-list.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* rotateRight(ListNode* head, int k) { 4 | if (!head || !head->next || k == 0) return head; 5 | ListNode *cur = head; 6 | int len = 1; 7 | while (cur->next && ++len) 8 | cur = cur->next; 9 | 10 | cur->next = head; 11 | k = k % len; 12 | k = len - k; 13 | while (k--) cur = cur->next; 14 | 15 | head = cur->next; 16 | cur->next = NULL; 17 | 18 | 19 | return head; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Mathematics/Exponentiation-II.cpp: -------------------------------------------------------------------------------- 1 | // pow of a,b,c 2 | 3 | #include 4 | using namespace std; 5 | #define MOD (int) (1e9+7) 6 | #define int long long 7 | int powfast(int a,int b,int m){ 8 | if(b==0)return 1; 9 | int val=powfast(a,b/2,m); 10 | if(b & 1){ 11 | return (((a*val)%m)*val)%m; 12 | } 13 | else{ 14 | return (val*val)%m; 15 | } 16 | } 17 | signed main() { 18 | int t; 19 | cin>>t; 20 | while(t--){ 21 | int a,b,c; 22 | cin>>a>>b>>c; 23 | int y=powfast(b,c,MOD-1); 24 | int ans=powfast(a,y,MOD); 25 | cout<& pushed, vector& popped) { 6 | int n=pushed.size(); 7 | int m=popped.size(); 8 | stackst; 9 | int j=0; 10 | for(int i=0;imp; 7 | int n=1; 8 | 9 | // Encodes a URL to a shortened URL. 10 | string encode(string longUrl) { 11 | string res="http://tinyurl.com/"+to_string(n); 12 | n++; 13 | mp[res]=longUrl; 14 | return res; 15 | } 16 | 17 | // Decodes a shortened URL to its original URL. 18 | string decode(string shortUrl) { 19 | return mp[shortUrl]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /CSES-Problem-Set/trees/subordinates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long int 3 | using namespace std; 4 | const int maxi = 2e5+7; 5 | vector adj[maxi]; 6 | int res[maxi]; 7 | void dfs(int v,int p){ 8 | for(int x:adj[v]){ 9 | if(x!=p){ 10 | dfs(x,v); 11 | res[v]+=res[x]+1; 12 | } 13 | } 14 | } 15 | 16 | int main() { 17 | int n; 18 | cin>>n; 19 | for(int i=2;i<=n;i++){ 20 | int p; 21 | cin>>p; 22 | adj[p].push_back(i); 23 | adj[i].push_back(p); 24 | } 25 | dfs(1,-1); 26 | for(int i=1;i<=n;i++){ 27 | cout<, greater> pq; 7 | int k; 8 | KthLargest(int _k, vector& nums) { 9 | k=_k; 10 | for(auto it:nums){ 11 | pq.push(it); 12 | if(pq.size()>k)pq.pop(); 13 | 14 | } 15 | } 16 | 17 | int add(int val) { 18 | pq.push(val); 19 | if(pq.size()>k)pq.pop(); 20 | return pq.top(); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Stack-Queue/maximum-frequency-stack.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/maximum-frequency-stack/ 2 | 3 | class FreqStack { 4 | public: 5 | unordered_mapfreq; 6 | unordered_map>m; 7 | int maxfreq=0; 8 | FreqStack() { 9 | 10 | } 11 | 12 | void push(int x) { 13 | maxfreq = max(maxfreq, ++freq[x]); 14 | m[freq[x]].push(x); 15 | } 16 | 17 | int pop() { 18 | int x = m[maxfreq].top(); 19 | m[maxfreq].pop(); 20 | if (!m[freq[x]--].size()) maxfreq--; 21 | return x; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Vector-Array/wiggle-subsequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/wiggle-subsequence/ 3 | 4 | class Solution { 5 | public: 6 | int wiggleMaxLength(vector& nums) { 7 | int n=nums.size(); 8 | if(n==1)return 1; 9 | int prev=nums[1]-nums[0]; 10 | int cnt=(prev!=0)?2:1; 11 | for(int i=2;i=0) || (curr>0 && prev<=0)){ 14 | cnt++; 15 | prev=curr; 16 | } 17 | } 18 | return cnt; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Trees/binary-tree-right-side-view.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/binary-tree-right-side-view/ 3 | 4 | class Solution { 5 | public: 6 | void recurs(TreeNode* root,int level,vector& res){ 7 | if(root==NULL)return; 8 | if(res.size()==level){ 9 | res.push_back(root->val); 10 | } 11 | recurs(root->right,level+1,res); 12 | recurs(root->left,level+1,res); 13 | } 14 | 15 | vector rightSideView(TreeNode* root) { 16 | vectorres; 17 | recurs(root,0,res); 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Mathematics/broken-calculator.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/broken-calculator/ 2 | 3 | class Solution { 4 | public: 5 | int brokenCalc(int startValue, int target) { 6 | int cnt=0; 7 | while(1){ 8 | if(target==startValue)return cnt; 9 | if(target&1)target++; 10 | else { 11 | if(target>startValue){ 12 | target/=2; 13 | }else{ 14 | return cnt+(startValue-target); 15 | } 16 | }; 17 | cnt++; 18 | } 19 | return cnt; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Sorting/boats to-save-people.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/boats-to-save-people/ 2 | 3 | class Solution { 4 | public: 5 | int numRescueBoats(vector& p, int l) { 6 | int n=p.size(); 7 | sort(p.begin(),p.end()); 8 | int i=0; 9 | int j=n-1; 10 | int cnt=0; 11 | while(i<=j){ 12 | if(p[i]+p[j]<=l){ 13 | cnt++; 14 | i++; 15 | j--; 16 | } 17 | else{ 18 | j--; 19 | cnt++; 20 | } 21 | } 22 | return cnt; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Trees/diagonal-traversal-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://practice.geeksforgeeks.org/problems/diagonal-traversal-of-binary-tree/1 3 | 4 | void diagnalTraversal(Node*root, queue&q, vector &v){ 5 | if (root==NULL) return; 6 | q.push(root->left); 7 | v.push_back(root->data); 8 | diagnalTraversal(root->right,q,v); 9 | } 10 | vector diagonal(Node *root) 11 | { 12 | queueq; 13 | vectorv; 14 | q.push(root); 15 | while(!q.empty()){ 16 | Node * x = q.front(); 17 | q.pop(); 18 | diagnalTraversal(x,q,v); 19 | } 20 | return v; 21 | } 22 | -------------------------------------------------------------------------------- /Vector-Array/maximum-points-you-can-obtain-from-cards.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ 3 | 4 | class Solution { 5 | public: 6 | int maxScore(vector& cp, int k) { 7 | int n=cp.size(); 8 | int i=0; 9 | int j=n-k; 10 | int sum=0; 11 | for(int l=j;l twoSum(vector& nums, int target) { 4 | vectorvec; 5 | unordered_mapmp; 6 | int n=nums.size(); 7 | for(int i=0;i& height) { 7 | int res=0; 8 | int i=0; 9 | int j=height.size()-1; 10 | while(i& nums) { 7 | bool isc=false; 8 | int n=nums.size(); 9 | for(int i=0;i=nums[i-1]){ 13 | nums[i]=nums[i+1]; 14 | }else{ 15 | nums[i+1]=nums[i]; 16 | } 17 | isc=true; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Vector-Array/Kadane.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int subarr(vector &v,int n){ 5 | int res=v[0]; 6 | int maxend=v[0]; 7 | for(int i=1;i>t; 16 | while(t--){ 17 | int n,res; 18 | cin>>n; 19 | vectorv; 20 | for(int i=0;i>p; 23 | v.push_back(p); 24 | } 25 | res=subarr(v,n); 26 | cout<& nums) { 7 | int i=0; 8 | while(i 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n,t; 9 | cin>>n>>t; 10 | vectorarr(n); 11 | for(auto &it:arr)cin>>it; 12 | int lo=0,hi=1e18; 13 | int res=0; 14 | while(lo<=hi){ 15 | int mid=(hi+lo)/2; 16 | int cnt=0; 17 | for(auto &it:arr){ 18 | cnt+=(min(mid/it,t)); 19 | } 20 | if(cnt>=t){ 21 | res=mid; 22 | hi=mid-1; 23 | } 24 | else{ 25 | lo=mid+1; 26 | } 27 | } 28 | cout<& nums) { 7 | sort(nums.begin(),nums.end()); 8 | int n=nums.size(); 9 | 10 | int median=0; 11 | if(n&1){ 12 | median=nums[n/2]; 13 | } 14 | else{ 15 | median=(nums[n/2]+nums[(n/2-1)])/2; 16 | } 17 | int res=0; 18 | for(auto &it:nums){ 19 | res+=abs(median-it); 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Strings/partition-labels.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/partition-labels/ 2 | 3 | class Solution { 4 | public: 5 | vector partitionLabels(string s) { 6 | vectorfreq(26,0); 7 | for(int i=0;ivec; 11 | int prev=-1; 12 | int maxi=0; 13 | for(int i=0;ileft); 10 | node->left=NULL; 11 | curr->right=node; 12 | curr=node; 13 | inorder(node->right); 14 | } 15 | TreeNode* increasingBST(TreeNode* root) { 16 | if(root==NULL)return NULL; 17 | TreeNode* res=new TreeNode(0); 18 | curr=res; 19 | inorder(root); 20 | return res->right; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/restaurant-customers.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1619/ 2 | #include 3 | using namespace std; 4 | #define mod (int) (1e9+7) 5 | #define int long long 6 | signed main() { 7 | int n; 8 | cin>>n; 9 | vector>res; 10 | for(int i=0;i>a>>b; 13 | res.push_back({a,0}); 14 | res.push_back({b,1}); 15 | } 16 | sort(res.begin(),res.end()); 17 | int ans=0,maxi=0; 18 | for(auto e:res){ 19 | if(e.second==0){ 20 | ans++; 21 | } 22 | else{ 23 | ans--; 24 | } 25 | maxi=max(maxi,ans); 26 | } 27 | cout<& a, vector& b){ 7 | if(a[0] == b[0]) return a[1] < b[1]; 8 | return a[0] > b[0]; 9 | } 10 | vector> reconstructQueue(vector>& people) { 11 | sort(people.begin(), people.end(), comp); 12 | vector> ans; 13 | for(auto man : people){ 14 | ans.insert(ans.begin()+man[1], man); 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/ferris-wheel.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define mod (int) (1e9+7) 4 | #define int long long 5 | signed main() { 6 | int n,k; 7 | cin>>n>>k; 8 | vectorvec(n); 9 | for(auto &it:vec){ 10 | cin>>it; 11 | } 12 | sort(vec.begin(),vec.end()); 13 | int cnt=0; 14 | int i=0,j=n-1; 15 | while(i<=j){ 16 | if(vec[i]+vec[j]<=k){ 17 | i++; 18 | j--; 19 | cnt++; 20 | } 21 | else if(vec[j]<=k){ 22 | j--; 23 | cnt++; 24 | } 25 | else if(vec[i]<=k){ 26 | i++; 27 | cnt++; 28 | } 29 | else{ 30 | i++; 31 | j--; 32 | } 33 | } 34 | cout<& ratings) { 7 | int res=0; 8 | int n=ratings.size(); 9 | 10 | vectorrig(n,1); 11 | vectorlef(n,1); 12 | 13 | for(int i=1;iratings[i-1])lef[i]=lef[i-1]+1; 15 | } 16 | for(int i=n-2;i>=0;i--){ 17 | if(ratings[i]>ratings[i+1])rig[i]=rig[i+1]+1; 18 | } 19 | for(int i=0;i&vec1,vector&vec2){ 7 | return vec1[1]-vec1[0]>vec2[1]-vec2[0]; 8 | } 9 | int twoCitySchedCost(vector>& costs) { 10 | int n=costs.size(); 11 | sort(costs.begin(),costs.end(),comp); 12 | int ans=0; 13 | for(int i=0;ist; 6 | void pushAll(TreeNode* node){ 7 | for(;node!=NULL;st.push(node),node=node->left){ 8 | } 9 | } 10 | public: 11 | BSTIterator(TreeNode* root) { 12 | pushAll(root); 13 | } 14 | 15 | int next() { 16 | TreeNode* temp=st.top(); 17 | st.pop(); 18 | pushAll(temp->right); 19 | return temp->val; 20 | } 21 | 22 | bool hasNext() { 23 | return !st.empty(); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Hashmap-Heap/top-k-frequent-elements.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/top-k-frequent-elements/ 3 | 4 | class Solution { 5 | public: 6 | vector topKFrequent(vector& nums, int k) { 7 | unordered_mapmp; 8 | for(auto it:nums){ 9 | mp[it]++; 10 | } 11 | priority_queue>pq; 12 | for(auto it:mp){ 13 | pq.push({it.second,it.first}); 14 | } 15 | vectorans; 16 | while(k--){ 17 | auto it=pq.top(); 18 | pq.pop(); 19 | ans.push_back(it.second); 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LinkedList/swap-nodes-in-pair.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* swapPairs(ListNode* head) { 4 | if(head==NULL || head->next==NULL) return head; 5 | ListNode* dummy=new ListNode(0); 6 | ListNode* prev=dummy; 7 | ListNode* curr=head; 8 | while(curr!=NULL && curr->next!=NULL){ 9 | ListNode* nxt=curr->next->next; 10 | ListNode* seco=curr->next; 11 | seco->next=curr; 12 | curr->next=nxt; 13 | prev->next=seco; 14 | 15 | prev=curr; 16 | curr=nxt; 17 | 18 | } 19 | return dummy->next; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Searching/smallest-greater-elements-in-whole-array.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://practice.geeksforgeeks.org/problems/smallest-greater-elements-in-whole-array2751/1# 3 | 4 | int* greaterElement(int arr[], int n) 5 | { 6 | 7 | int *ans = new int[n]; 8 | vector res; 9 | for(int i = 0; i < n; i++) 10 | { 11 | res.push_back(arr[i]); 12 | } 13 | sort(res.begin(),res.end()); 14 | for(int i=0;i&a,vector&b){ 7 | return a[1]>b[1]; 8 | } 9 | int maximumUnits(vector>& bt, int ts) { 10 | sort(bt.begin(),bt.end(),comp); 11 | int ans=0; 12 | for(auto it:bt){ 13 | if(ts 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | vector nums(n); 11 | for(auto &N:nums){ 12 | cin>>N; 13 | } 14 | int p1=0,p2=0; 15 | int ans=0; 16 | setst; 17 | while(p2> merge(vector>& intv) { 7 | sort(intv.begin(),intv.end()); 8 | vector>vec; 9 | int n=intv.size(); 10 | auto it=intv[0]; 11 | for(int i=1;i=intv[i][0]){ 13 | it[1]=max(it[1],intv[i][1]); 14 | 15 | }else{ 16 | vec.push_back(it); 17 | it=intv[i]; 18 | } 19 | } 20 | vec.push_back(it); 21 | return vec; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Hashmap-Heap/continuous-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSubarraySum(vector& nums, int k) { 4 | unordered_mapm; 5 | int sum=0; 6 | for(int i=0;i0) 11 | { 12 | return true; 13 | } 14 | if(m.find(rem)==m.end()) 15 | { 16 | m[rem]=i; 17 | } 18 | else if(i-m[rem]>=2) 19 | { 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Trees/LeetCode-337-House-Robber-III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | pair rob_(TreeNode* root){ 4 | pair myans; 5 | myans.first=0; 6 | myans.second=0; 7 | if(root==NULL)return myans; 8 | pair left=rob_(root->left); 9 | pair right=rob_(root->right); 10 | 11 | myans.first=left.second+root->val+right.second; 12 | myans.second=max(left.first,left.second)+max(right.first,right.second); 13 | return myans; 14 | } 15 | int rob(TreeNode* root) { 16 | pair res; 17 | res=rob_(root); 18 | return max(res.first,res.second); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Strings/Smallest String With a-given-numeric-value.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/ 2 | 3 | class Solution { 4 | public: 5 | string getSmallestString(int n, int k) { 6 | string s(n,'a'); 7 | k=k-n; 8 | // string 9 | // initially aaaaaaa n times 10 | // we need z count at the end (z/25) and a separator w at between z and a calculated k%25; 11 | int zc=k/25; 12 | int wc=k%25; 13 | int i=n-1; 14 | while(zc-->0){ 15 | s[i--]='z'; 16 | } 17 | if(wc>0){ 18 | s[i]=(char)('a'+wc); 19 | } 20 | return s; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Hashmap-Heap/find-original-array-from-doubled-array.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/find-original-array-from-doubled-array/ 3 | 4 | class Solution { 5 | public: 6 | vector findOriginalArray(vector& ch) { 7 | sort(ch.begin(),ch.end()); 8 | if(ch.size()&1)return {}; 9 | vectorans; 10 | multisetmt(ch.begin(),ch.end()); 11 | for(int i=0;i &s,vector&ds,vector>&ans){ 7 | ans.push_back(ds); 8 | for(int i=ind;i> subsetsWithDup(vector& s) { 16 | sort(s.begin(),s.end()); 17 | vector> ans; 18 | vectords; 19 | swd(0,s,ds,ans); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Trees/deepest-leaves-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/deepest-leaves-sum/ 3 | 4 | class Solution { 5 | public: 6 | int deepestlvl, deepestsum; 7 | void dfs(TreeNode* s, int level){ 8 | if(s == nullptr) return; 9 | if(level == deepestlvl){ 10 | deepestsum += s->val; 11 | } else if(level > deepestlvl){ 12 | deepestlvl = level; 13 | deepestsum = s->val; 14 | } 15 | dfs(s->left, level+1); 16 | dfs(s->right, level+1); 17 | } 18 | int deepestLeavesSum(TreeNode* root) { 19 | deepestlvl = 0, deepestsum = 0; 20 | dfs(root, 0); 21 | return deepestsum; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Hashmap-Heap/three-sum-with-multiplicity.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/3sum-with-multiplicity 3 | 4 | class Solution { 5 | private: 6 | int mod = 1e9 + 7; 7 | 8 | public: 9 | int threeSumMulti(vector& arr, int target) { 10 | 11 | int n = arr.size(), res = 0; 12 | unordered_map mp; 13 | 14 | for(int i = 0; i < n; i++) 15 | { 16 | res += mp[target - arr[i]]; 17 | res %= mod; 18 | 19 | for(int j = 0; j < i; j++) 20 | { 21 | mp[arr[i] + arr[j]]++; 22 | } 23 | } 24 | 25 | 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Hashmap-Heap/last-stone-weight.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/last-stone-weight/ 3 | 4 | class Solution { 5 | public: 6 | int lastStoneWeight(vector& stones) { 7 | priority_queuepq; 8 | for(auto it:stones){ 9 | pq.push(it); 10 | } 11 | while(pq.size()){ 12 | if(pq.size()==1)return pq.top(); 13 | if(pq.size()>=2){ 14 | int y=pq.top(); 15 | pq.pop(); 16 | int x=pq.top(); 17 | pq.pop(); 18 | if(x!=y){ 19 | pq.push(y-x); 20 | } 21 | } 22 | } 23 | return 0; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Stack-Queue/simplify-path.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/simplify-path/ 2 | 3 | class Solution { 4 | public: 5 | string simplifyPath(string path) { 6 | path += '/'; 7 | string str = ""; 8 | vectorst; 9 | for (auto x : path) { 10 | if (x == '/') { 11 | if (str == ".." ) { 12 | if (st.size() > 0) { 13 | st.pop_back(); 14 | } 15 | } else if (str != "." && str != "") 16 | st.push_back(str); 17 | str = ""; 18 | } else { 19 | str += x; 20 | } 21 | } 22 | str = "/"; 23 | for (int i = 0; i < st.size(); i++) { 24 | str += st[i]; 25 | if (i != st.size() - 1) { 26 | str += '/'; 27 | } 28 | } 29 | return str; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Vector-Array/sum-of-even-numbers-after-queries.cpp: -------------------------------------------------------------------------------- 1 | 2 | // https://leetcode.com/problems/sum-of-even-numbers-after-queries/ 3 | 4 | class Solution { 5 | public: 6 | vector sumEvenAfterQueries(vector& nums, vector>& queries) { 7 | vectorres; 8 | int evsum=0; 9 | for(auto it:nums){ 10 | if((it%2)==0)evsum+=it; 11 | } 12 | for(auto it:queries){ 13 | int ind=it[1]; 14 | int val=it[0]; 15 | if(nums[ind]%2==0)evsum-=nums[ind]; 16 | nums[ind]+=val; 17 | if(nums[ind]%2==0)evsum+=nums[ind]; 18 | res.push_back(evsum); 19 | } 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/apartments.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define mod (int) (1e9+7) 4 | #define int long long 5 | signed main() { 6 | int n,m,k; 7 | cin>>n>>m>>k; 8 | vectorvec(n); 9 | vectorarr(m); 10 | for(auto &it:vec){ 11 | cin>>it; 12 | } 13 | for(auto &it:arr){ 14 | cin>>it; 15 | } 16 | sort(vec.begin(),vec.end()); 17 | sort(arr.begin(),arr.end()); 18 | int p1=0,p2=0,cnt=0; 19 | while(p1=vec[p1]-k)){ 21 | cnt++; 22 | p1++; 23 | p2++; 24 | } 25 | else if(arr[p2]< (vec[p1]-k)){ 26 | p2++; 27 | } 28 | else{ 29 | p1++; 30 | } 31 | } 32 | cout<curr(w+1,0), prev(w+1,0); 7 | for(int i=0;i<=w;i++){ 8 | prev[i]=((int)i/wt[0])*val[0]; 9 | } 10 | for(int ind=1;ind prev(m+1,0), cur(m+1,0); 10 | 11 | int ans = 0; 12 | 13 | for(int i=1;i<=n;i++){ 14 | for(int j=1;j<=m;j++){ 15 | if(s1[i-1]==s2[j-1]){ 16 | int val = 1 + prev[j-1]; 17 | cur[j] = val; 18 | ans = max(ans,val); 19 | } 20 | else 21 | cur[j] = 0; 22 | } 23 | prev=cur; 24 | } 25 | 26 | return ans; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Recursion-Backtracking/permutation-sequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/permutation-sequence/ 3 | 4 | class Solution { 5 | public: 6 | string getPermutation(int n, int k) { 7 | int fact=1; 8 | vectornumb; 9 | for(int i=1;i 2 | #include 3 | using namespace std; 4 | void insertion_sort(vector& arr, int size) { 5 | for (int i=1;i=0 && arr[j]>key) { 10 | arr[j+1]=arr[j]; 11 | j--; 12 | } 13 | arr[j+1]=key; 14 | } 15 | } 16 | int main() { 17 | int size; 18 | cin>>size; 19 | vectorvec; 20 | for (int i=0;i>p; 23 | vec.push_back(p); 24 | 25 | } 26 | insertion_sort(vec, size); 27 | for (int i=0;i&vec){ 7 | if(root==NULL)return; 8 | inorder(root->left,vec); 9 | vec.push_back(root->data); 10 | inorder(root->right,vec); 11 | } 12 | void postorder(Node* root,vector&vec,int &i){ 13 | if(root==NULL)return; 14 | postorder(root->left,vec,i); 15 | postorder(root->right,vec,i); 16 | root->data=vec[i++]; 17 | } 18 | void convertToMaxHeapUtil(Node* root) 19 | { 20 | vectorvec; 21 | int i=0; 22 | inorder(root,vec); 23 | postorder(root,vec,i); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Hashmap-Heap/longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/longest-consecutive-sequence/ 3 | 4 | class Solution { 5 | public: 6 | int longestConsecutive(vector& nums) { 7 | unordered_setst; 8 | for(auto it:nums){ 9 | st.insert(it); 10 | } 11 | int res=0; 12 | for(int num:nums){ 13 | if(!st.count(num-1)){ 14 | int currn=num; 15 | int count=1; 16 | while(st.count(currn+1)){ 17 | currn++; 18 | count++; 19 | } 20 | res=max(res,count); 21 | } 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic-Programming/rod-cutting.cpp: -------------------------------------------------------------------------------- 1 | 2 | // https://practice.geeksforgeeks.org/problems/rod-cutting0840/1 3 | 4 | int cutRod(int price[], int n) { 5 | vectorprev(n+1,0),curr(n+1,0); 6 | for(int i=0;i<=n;i++){ 7 | prev[i]=i*price[0]; 8 | } 9 | for(int ind=1;ind& nums) { 6 | priority_queuepq; 7 | int mini=INT_MAX; 8 | for(int it:nums){ 9 | if(it%2==1)it=it*2; 10 | mini=min(it,mini); 11 | pq.push(it); 12 | } 13 | int differ=INT_MAX; 14 | while((pq.top()%2==0)){ 15 | int maxi=pq.top(); 16 | pq.pop(); 17 | differ=min(differ,maxi-mini); 18 | mini=min(mini,maxi/2); 19 | pq.push(maxi/2); 20 | } 21 | return min(differ,pq.top()-mini); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Graphs/keys-and-rooms.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/keys-and-rooms/ 3 | 4 | class Solution { 5 | public: 6 | bool canVisitAllRooms(vector>& rooms) { 7 | int n=rooms.size(); 8 | vectorvis(n,0); 9 | vis[0]=1; 10 | queueq; 11 | q.push(0); 12 | while(!q.empty()){ 13 | auto pt=q.front(); 14 | q.pop(); 15 | for(auto it:rooms[pt]){ 16 | if(vis[it]==0){ 17 | vis[it]=1; 18 | q.push(it); 19 | } 20 | } 21 | } 22 | for(auto it:vis){ 23 | if(it==0)return false; 24 | } 25 | return true; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Sorting/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | void selection_sort(vector& arr, int size) { 5 | for (int i=0;i>size; 18 | vectorvec; 19 | for (int i=0;i>p; 22 | vec.push_back(p); 23 | 24 | } 25 | selection_sort(vec, size); 26 | for (int i=0;i&res){ 6 | if(n==0){ 7 | res.push_back(num); 8 | return; 9 | } 10 | int last=num%10; 11 | if(last>=k)dfs((num*10)+last-k,n-1,k,res); 12 | if(k>0 && last+k<10)dfs((num*10)+last+k,n-1,k,res); 13 | } 14 | public: 15 | vector numsSameConsecDiff(int n, int k) { 16 | vectorres; 17 | if(n==1)res.push_back(0); 18 | for(int i=1;i<=9;i++){ 19 | dfs(i,n-1,k,res); 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Hashmap-Heap/maximum-erasure-value.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/maximum-erasure-value/ 3 | 4 | class Solution { 5 | public: 6 | int maximumUniqueSubarray(vector& nums) { 7 | int i=0; 8 | int j=0; 9 | int sum=0; 10 | int ans=0; 11 | unordered_mapmp; 12 | while(j1){ 18 | int prev=nums[i]; 19 | mp[prev]--; 20 | sum-=prev; 21 | i++; 22 | } 23 | 24 | ans=max(ans,sum); 25 | } 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Vector-Array/hit-and-blow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | const int M = 1e7 + 7; 5 | 6 | int n; 7 | cin >> n; 8 | vectorvec1, vec2; 9 | for (int i = 0; i < n; i++) { 10 | int p; 11 | cin >> p; 12 | vec1.push_back(p); 13 | 14 | } 15 | for (int i = 0; i < n; i++) { 16 | int p; 17 | cin >> p; 18 | vec2.push_back(p); 19 | 20 | } 21 | int cnt1 = 0, cnt2 = 0; 22 | for (int i = 0; i < n; i++) { 23 | int pp = vec1[i]; 24 | for (int j = 0; j < n; j++) { 25 | if (pp == vec2[j] && i == j) { 26 | cnt1++; 27 | } else if (pp == vec2[j] && i != j) { 28 | cnt2++; 29 | } 30 | } 31 | } 32 | cout << cnt1 << endl; 33 | cout << cnt2 << endl; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Stack-Queue/longest-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/longest-valid-parentheses/ 3 | 4 | class Solution { 5 | public: 6 | int longestValidParentheses(string s) { 7 | stackst; 8 | st.push(-1); 9 | int maxi=0; 10 | int n=s.length(); 11 | for(int i=0;i 4 | #define ll long long int 5 | using namespace std; 6 | #define MOD 1000000007 7 | int sumd(int _a){int res=0;while(_a){res=res+(_a%10);_a=_a/10;}return res;} 8 | int main() { 9 | ios_base::sync_with_stdio(0); 10 | cin.tie(0); 11 | int n; 12 | cin>>n; 13 | vectorarr(n); 14 | for(auto &it:arr){ 15 | cin>>it; 16 | } 17 | stackst; 18 | for(int i=0;i=arr[i]){ 20 | st.pop(); 21 | } 22 | if(st.empty()){ 23 | cout<<0<<" "; 24 | } 25 | else{ 26 | cout< 4 | #define int long long 5 | using namespace std; 6 | #define MOD 1000000007 7 | 8 | signed main() { 9 | ios_base::sync_with_stdio(0); 10 | cin.tie(0); 11 | int n,k; 12 | cin>>n>>k; 13 | vector>vec(n); 14 | for(auto &it:vec){ 15 | cin>>it.second>>it.first; 16 | } 17 | sort(vec.begin(),vec.end()); 18 | multisetmp; 19 | int cnt=0; 20 | for(auto it:vec){ 21 | auto up=mp.upper_bound(it.second); 22 | if(up!=mp.begin()){ 23 | up--; 24 | mp.erase(up); 25 | } 26 | if(size(mp)& heights, int bricks, int ladders) { 5 | priority_queue , greater> pq; 6 | int n=heights.size(); 7 | int br=0; 8 | for(int i=1;i0){ 11 | pq.push(diff); 12 | if(pq.size()>ladders){ 13 | int top=pq.top(); 14 | pq.pop(); 15 | br+=top; 16 | if(br>bricks)return i-1; 17 | } 18 | } 19 | } 20 | return n-1; 21 | } 22 | -------------------------------------------------------------------------------- /Searching/search-a-2D-matrix.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/search-a-2d-matrix/ 3 | 4 | class Solution { 5 | public: 6 | bool searchMatrix(vector>& matrix, int target) { 7 | if(!matrix.size()) return false; 8 | int m=matrix.size(); 9 | int n=matrix[0].size(); 10 | int lo=0; 11 | int hi=(m*n)-1; 12 | while(lo<=hi){ 13 | int mid=(lo+(hi-lo)/2); 14 | if(matrix[mid/n][mid%n]==target){ 15 | return true; 16 | } 17 | else if(matrix[mid/n][mid%n] into; 7 | 8 | public: 9 | MyStack() {} 10 | 11 | void push(int x) { 12 | int i = 0; 13 | into.push(x); 14 | 15 | while(i < into.size() - 1){ 16 | into.push(into.front()); 17 | into.pop(); i++; 18 | } 19 | } 20 | 21 | int pop() { 22 | int top = into.front(); 23 | into.pop(); 24 | 25 | return top; 26 | } 27 | 28 | int top() { 29 | return into.front(); 30 | } 31 | 32 | bool empty() { 33 | return into.empty(); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Trees/n-ary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/n-ary-tree-level-order-traversal/ 3 | 4 | class Solution { 5 | public: 6 | vector> levelOrder(Node* root) { 7 | if (root == nullptr) return {}; 8 | queue q; 9 | q.push(root); 10 | vector> ans; 11 | while (!q.empty()) { 12 | ans.push_back({}); 13 | for (int i = q.size(); i >= 1; i--) { 14 | Node* curr = q.front(); q.pop(); 15 | ans.back().push_back(curr->val); 16 | for (Node* child : curr->children) { 17 | q.push(child); 18 | } 19 | } 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /code-studio-contest/maximum-value-of-F(x).cpp: -------------------------------------------------------------------------------- 1 | // link : https://www.codingninjas.com/codestudio/problems/maximum-value-of-f-x-ii_2245751?source=youtube&campaign=Strivercontest6thfeb&utm_source=youtube&utm_medium=affiliate&utm_campaign=Strivercontest6thfeb&leftPanelTab=0 2 | 3 | int f(int i,int j,string &s,string &g, int n,int m,vector>&dp){ 4 | if(i<0 || j<0)return 0; 5 | if(dp[i][j]!=-1)return dp[i][j]; 6 | int cmp=0; 7 | if(s[i]==g[j])cmp=1+f(i-1,j-1,s,g,n,m,dp); 8 | int ncmp=max(f(i-1,j,s,g,n,m,dp),f(i,j-1,s,g,n,m,dp)); 9 | return dp[i][j] = max(cmp,ncmp); 10 | 11 | } 12 | 13 | int maxFXII(string &s, string &t, int n, int m){ 14 | vector>dp(n,vector(m,-1)); 15 | return 2 * f(n-1,m-1,s,t,n,m,dp); 16 | } 17 | -------------------------------------------------------------------------------- /Strings/backspace-string-compare.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/backspace-string-compare/ 3 | 4 | class Solution { 5 | public: 6 | bool backspaceCompare(string S, string T) { 7 | string res1=""; 8 | string res2=""; 9 | 10 | 11 | for(int i=0;i='a'&&S[i]<='z'){ 13 | res1+=S[i]; 14 | } 15 | else if(!res1.empty()) 16 | res1.pop_back(); 17 | } 18 | for(int i=0;i='a'&&T[i]<='z'){ 20 | res2+=T[i]; 21 | } 22 | else if(!res2.empty()) 23 | res2.pop_back(); 24 | } 25 | return res1==res2; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Vector-Array/next-permutation.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/next-permutation/ 2 | 3 | class Solution { 4 | public: 5 | void nextPermutation(vector& nums) { 6 | int n=nums.size(); 7 | int k,l; 8 | for( k=n-2;k>=0;k--){ 9 | if(nums[k]k;l--){ 19 | if(nums[l]>nums[k]){ 20 | break; 21 | } 22 | } 23 | swap(nums[k],nums[l]); 24 | reverse(nums.begin()+k+1,nums.end()); 25 | } 26 | 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LinkedList/copy-list-with-random-pointer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* copyRandomList(Node* head) { 4 | mapmp; 5 | Node* curr=head; 6 | Node* nhead=new Node(-1); 7 | Node* prev=nhead; 8 | while(curr!=NULL){ 9 | Node* temn=new Node(curr->val); 10 | prev->next=temn; 11 | mp[curr]=temn; 12 | curr=curr->next; 13 | prev=prev->next; 14 | 15 | } 16 | nhead=nhead->next; 17 | Node* c1=head; 18 | Node* c2=nhead; 19 | while(c1!=NULL){ 20 | c2->random=mp[c1->random]; 21 | c1=c1->next; 22 | c2=c2->next; 23 | 24 | } 25 | return nhead; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Trees/Leetcode-701-Insert-into-a-Binary-Search-Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* insertIntoBST(TreeNode* root, int val) { 4 | if(root==NULL) return new TreeNode(val); 5 | TreeNode* curr=root; 6 | while(true){ 7 | if(curr->val<=val){ 8 | if(curr->right)curr=curr->right; 9 | else{ 10 | curr->right=new TreeNode(val); 11 | break; 12 | } 13 | } 14 | else{ 15 | if(curr->left)curr=curr->left; 16 | else{ 17 | curr->left=new TreeNode(val); 18 | break; 19 | } 20 | } 21 | } 22 | return root; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /CSES-Problem-Set/graph/building-roads.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | int n,m; 5 | const int maxi=1e5+10; 6 | vectorg[maxi]; 7 | bool vis[maxi]; 8 | void dfs(int x){ 9 | vis[x]=true; 10 | for(auto c:g[x]){ 11 | if(!vis[c]){ 12 | dfs(c); 13 | } 14 | } 15 | 16 | } 17 | int main() { 18 | cin>>n>>m; 19 | int cnt=0; 20 | for(int i=0;i>a>>b; 23 | g[a].push_back(b); 24 | g[b].push_back(a); 25 | } 26 | vectorv; 27 | for(int i=1;i<=n;i++){ 28 | if(!vis[i]){ 29 | dfs(i); 30 | cnt++; 31 | v.push_back(i); 32 | } 33 | 34 | } 35 | cout<& wt, vector& val, int n, int W){ 5 | vector> dp(n,vector(W+1,0)); 6 | for(int i=wt[0]; i<=W; i++){ 7 | dp[0][i] = val[0]; 8 | } 9 | 10 | for(int ind =1; indadj[],int id,vector& informTime){ 8 | maxi=max(maxi,ans); 9 | for(auto emp:adj[id]){ 10 | ans+=informTime[id]; 11 | dfs(adj,emp,informTime); 12 | ans-=informTime[id]; 13 | } 14 | } 15 | int numOfMinutes(int n, int hid, vector& manager, vector& informTime) { 16 | vectoradj[n]; 17 | for(int i=0;i&nums,int target,vector>&ans,vector&tem){ 4 | if(idx==nums.size()){ 5 | if(target==0){ 6 | ans.push_back(tem); 7 | } 8 | return; 9 | } 10 | if(nums[idx]<=target){ 11 | tem.push_back(nums[idx]); 12 | combi(idx,nums,target-nums[idx],ans,tem); 13 | tem.pop_back(); 14 | } 15 | combi(idx+1,nums,target,ans,tem); 16 | } 17 | vector> combinationSum(vector& nums, int target) { 18 | vector>ans; 19 | vectortem; 20 | combi(0,nums,target,ans,tem); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Stack-Queue/sliding-window-maximum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/sliding-window-maximum/ 3 | 4 | vector max_of_subarrays(vector arr, int n, int k) { 5 | vectorres; 6 | list lst; 7 | int i=0; 8 | int j=0; 9 | while(j0 && lst.back()& height) { 4 | int l=0; 5 | int r=height.size()-1; 6 | int lmax=0; 7 | int rmax=0; 8 | int res=0; 9 | while(l<=r){ 10 | if(height[l]<=height[r]){ 11 | if(lmax>st; 8 | st.insert({0,0}); 9 | for(int i=0;i> longestZigZag_(TreeNode* root){ 4 | pair>ans={-1,{-1,0}}; 5 | if(root==NULL)return ans; 6 | 7 | pair> left=longestZigZag_(root->left); 8 | pair> right=longestZigZag_(root->right); 9 | ans.second.second=max(max(left.second.second,right.second.second),max(left.second.first,right.first)+1); 10 | ans.first=left.second.first+1; 11 | ans.second.first=right.first+1; 12 | return ans; 13 | } 14 | int longestZigZag(TreeNode* root) { 15 | 16 | pair>ans=longestZigZag_(root); 17 | return ans.second.second; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Sorting/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | void bubble(vector& vec, int size) { 5 | for (int i=0;ivec[j+1]) { 9 | swap(vec[j], vec[j+1]); 10 | swapped=true; 11 | } 12 | } 13 | if (swapped==false) { 14 | break; 15 | } 16 | } 17 | } 18 | int main() { 19 | int size; 20 | cin>>size; 21 | vectorvec; 22 | for (int i=0;i>p; 25 | vec.push_back(p); 26 | 27 | } 28 | bubble(vec, size); 29 | for (int i=0;i& nums, int target) { 6 | int l=0, r = nums.size()-1; 7 | while(l <= r){ 8 | int mid = l + (r-l)/2; 9 | if(nums[mid] == target) return true; 10 | if( (nums[l] == nums[mid]) && (nums[r] == nums[mid])) {l++; r--;} 11 | else if(nums[l] <= nums[mid]){ 12 | if((nums[l] <= target) && (nums[mid] > target)) r = mid-1; 13 | else l = mid + 1; 14 | } else { 15 | if((nums[mid] < target) && (nums[r] >= target)) l = mid + 1; 16 | else r = mid-1; 17 | } 18 | } 19 | return false; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Stack-Queue/remove-K-digits.cpp: -------------------------------------------------------------------------------- 1 | // link : https://leetcode.com/problems/remove-k-digits/ 2 | 3 | class Solution { 4 | public: 5 | string removeKdigits(string num, int k) { 6 | int p=k; 7 | stackst; 8 | for(auto it:num){ 9 | while(!st.empty() && k>0 && st.top()>it){ 10 | st.pop(); 11 | k--; 12 | } 13 | if(!st.empty() || it!='0'){ 14 | st.push(it); 15 | } 16 | } 17 | while(!st.empty() && k--){ 18 | st.pop(); 19 | } 20 | if(st.empty())return "0"; 21 | string res=""; 22 | while(!st.empty()){ 23 | res+=st.top(); 24 | st.pop(); 25 | } 26 | reverse(res.begin(),res.end()); 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/concert-tickets.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1091/ 2 | 3 | #include 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n,m; 9 | cin>>n>>m; 10 | vectorvec(n); 11 | for(auto &V:vec)cin>>V; 12 | multisetmt; 13 | for(auto t:vec){ 14 | mt.insert(t); 15 | } 16 | 17 | vectorarr(m); 18 | for(auto &it:arr){ 19 | cin>>it; 20 | } 21 | vectorres(m,-1); 22 | for(int i=0;i& coins, int amount) { 4 | int n=coins.size(); 5 | vector>dp(n,vector(amount+1,0)); 6 | 7 | for(int i=0;i<=amount;i++){ 8 | if(i%coins[0]==0)dp[0][i]=i/coins[0]; 9 | else dp[0][i]=1e9; 10 | } 11 | for(int ind=1;ind&vec,int &cnt){ 7 | if(root==NULL)return; 8 | vec[root->val]++; 9 | helper(root->left,vec,cnt); 10 | helper(root->right,vec,cnt); 11 | if(root->right==NULL && root->left==NULL){ 12 | int odd=0; 13 | for(int i=1;i<=9;i++){ 14 | if(vec[i]&1)odd++; 15 | } 16 | if(odd<=1)cnt++; 17 | } 18 | vec[root->val]--; 19 | } 20 | int pseudoPalindromicPaths (TreeNode* root) { 21 | vectorvec(10,0); 22 | int cnt=0; 23 | helper(root,vec,cnt); 24 | return cnt; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LinkedList/merge-nodes-in-between-zeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* mergeNodes(ListNode* head) { 4 | int sum=0; 5 | vectorvec; 6 | ListNode* hi=head; 7 | ListNode* hit=new ListNode(-1); 8 | ListNode* headi=hit; 9 | while(hi!=NULL){ 10 | if(hi->val==0){ 11 | if(sum){ 12 | hit->next=new ListNode(sum); 13 | hit=hit->next; 14 | 15 | } 16 | sum=0; 17 | }else{ 18 | sum+=hi->val; 19 | } 20 | hi=hi->next; 21 | } 22 | if(sum){ 23 | hit->next=new ListNode(sum); 24 | hit=hit->next; 25 | } 26 | hit->next=NULL; 27 | 28 | return headi->next; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Vector-Array/forest-queries.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1652/ 2 | 3 | #include 4 | using namespace std; 5 | #define int long long 6 | signed main() { 7 | int n,m; 8 | cin>>n>>m; 9 | int mat[n+5][n+5],pref[n+5][n+5]; 10 | memset(mat,0,sizeof mat); 11 | memset(pref,0,sizeof pref); 12 | for(int i=1;i<=n;i++){ 13 | for(int j=1;j<=n;j++){ 14 | char x; 15 | cin>>x; 16 | if(x=='*'){ 17 | mat[i][j]=1; 18 | } 19 | // update col matrix 20 | pref[i][j]=pref[i][j-1]+mat[i][j]; 21 | } 22 | } 23 | for(int i=1;i<=n;i++){ 24 | for(int j=1;j<=n;j++){ 25 | pref[i][j]=pref[i-1][j]+pref[i][j]; 26 | } 27 | } 28 | while(m--){ 29 | int x1,y1,x2,y2; 30 | cin>>x1>>y1>>x2>>y2; 31 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | 5 | int n,q; 6 | const int maxi=2e5+5; 7 | vector adj[maxi]; 8 | int sizes[maxi]; 9 | 10 | void dfs1(int u,int p){ 11 | sizes[u]=1; 12 | for(auto x:adj[u]){ 13 | if(x!=p){ 14 | dfs1(x,u); 15 | sizes[u]+=sizes[x]; 16 | } 17 | } 18 | } 19 | int dfs2(int u,int p){ 20 | for(auto x:adj[u]){ 21 | if(x!=p){ 22 | if((sizes[x]*2)>n){ 23 | return dfs2(x,u); 24 | } 25 | } 26 | } 27 | return u; 28 | } 29 | 30 | int main() { 31 | 32 | cin>>n; 33 | for(int i=0;i<(n-1);i++){ 34 | int a,b; 35 | cin>>a>>b; 36 | adj[a].push_back(b); 37 | adj[b].push_back(a); 38 | } 39 | 40 | dfs1(1,1); 41 | cout< findAnagrams(string s, string p) { 7 | vectorph(26,0); 8 | vectorsh(26,0); 9 | if(s.length()ans; 21 | while(j& c,int t,vector>&ans,vector&ds){ 7 | if(t==0){ 8 | ans.push_back(ds); 9 | return; 10 | } 11 | for(int i=ind;iind && c[i]==c[i-1])continue; 13 | if(c[i]>t)break; 14 | ds.push_back(c[i]); 15 | fcs(i+1,c,t-c[i],ans,ds); 16 | ds.pop_back(); 17 | } 18 | 19 | } 20 | vector> combinationSum2(vector& c, int t) { 21 | sort(c.begin(),c.end()); 22 | vector>ans; 23 | vectords; 24 | fcs(0,c,t,ans,ds); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LinkedList/remove-duplicates-from-sorted-list-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteDuplicates(ListNode* head) { 4 | unordered_mapmp; 5 | ListNode* tem=head; 6 | while(tem!=NULL){ 7 | mp[tem->val]++; 8 | tem=tem->next; 9 | } 10 | tem=head; 11 | 12 | ListNode* nhead=new ListNode(-1); 13 | ListNode* res=nhead; 14 | while(tem!=NULL){ 15 | 16 | if(mp[tem->val]==1){ 17 | //cout<val]<next=tem; 20 | nhead=nhead->next; 21 | } 22 | 23 | tem=tem->next; 24 | // cout<next->val; 25 | } 26 | nhead->next=NULL; 27 | return res->next; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Sorting/max-number-of-k-sum-pairs.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/max-number-of-k-sum-pairs/ 3 | class Solution { 4 | public: 5 | int maxOperations(vector& nums, int k) { 6 | sort(nums.begin(),nums.end()); 7 | int i =0; 8 | int j =nums.size()-1; 9 | int count =0; 10 | while(ik){ 12 | j--; 13 | continue; 14 | } 15 | if(nums[i]+nums[j]==k){ 16 | count++; 17 | i++; 18 | j--; 19 | continue; 20 | } 21 | 22 | if(nums[i]+nums[j]freq(26,0); 9 | for(auto &it:s){ 10 | freq[it-'a']++; 11 | } 12 | unordered_setst; 13 | int res=0; 14 | for(int i=0;i<26;i++){ 15 | int currfreq=freq[i]; 16 | while(currfreq>0){ 17 | if(st.find(currfreq)!=st.end()){ 18 | currfreq--; 19 | res++; 20 | }else{ 21 | break; 22 | } 23 | } 24 | if(currfreq!=0)st.insert(currfreq); 25 | } 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Vector-Array/TappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int trap(int v[],int n){ 6 | int res=0; 7 | int lmax[n]; 8 | int rmax[n]; 9 | lmax[0]=v[0]; 10 | for(int i=1;i=0;i--){ 15 | rmax[i]=max(v[i],rmax[i+1]); 16 | } 17 | for(int i=1;i>t; 26 | while(t--){ 27 | int n,res; 28 | cin>>n; 29 | int v[n]; 30 | for(int i=0;i>p; 33 | 34 | v[i]=p; 35 | } 36 | res=trap(v,n); 37 | cout<>& matrix, int k) { 5 | 6 | int n = matrix.size(); 7 | int low = matrix[0][0]; 8 | int high = matrix[n-1][n-1]; 9 | while(low < high){ 10 | 11 | int mid = low + (high - low)/2; 12 | int count = 0; 13 | for(int i = 0; i < n; i++){ 14 | count += upper_bound(matrix[i].begin(), matrix[i].end(), mid)-matrix[i].begin(); 15 | 16 | } 17 | 18 | if(count < k){ 19 | low = mid + 1; 20 | }else{ 21 | high = mid; 22 | } 23 | 24 | } 25 | 26 | return low; 27 | } 28 | -------------------------------------------------------------------------------- /Trees/average-of-levels-in-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/average-of-levels-in-binary-tree/ 2 | 3 | class Solution { 4 | public: 5 | vector averageOfLevels(TreeNode* root) { 6 | vectorans; 7 | queueq; 8 | if(root==NULL)return ans; 9 | q.push(root); 10 | int cnt=0; 11 | 12 | while(q.size()>0){ 13 | int sz=q.size(); 14 | int tem=sz; 15 | double res=0; 16 | 17 | while(sz--){ 18 | auto it=q.front(); 19 | q.pop(); 20 | res+=(it->val); 21 | if(it->left)q.push(it->left); 22 | if(it->right)q.push(it->right); 23 | } 24 | 25 | res=res/tem; 26 | ans.push_back(res); 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Adv-Graph-Trees/delete-edge.cpp: -------------------------------------------------------------------------------- 1 | const int m=1e9+7; 2 | void dfs(int vertex,int par,vector g[],vector&sub_tree,vector &val){ 3 | sub_tree[vertex]+=val[vertex-1]; 4 | for(int child:g[vertex]){ 5 | if(child==par)continue; 6 | dfs(child,vertex,g,sub_tree,val); 7 | sub_tree[vertex]+=sub_tree[child]; 8 | } 9 | } 10 | 11 | int Solution::deleteEdge(vector &A, vector > &B) { 12 | vector g[A.size()+1]; 13 | vector sub_tree(A.size()+1,0); 14 | for(auto &it:B){ 15 | g[it[0]].push_back(it[1]); 16 | g[it[1]].push_back(it[0]); 17 | 18 | } 19 | dfs(1,0,g,sub_tree,A); 20 | long long ans=0; 21 | for(int i=2;i<=A.size();i++){ 22 | int part1=sub_tree[i]; 23 | int part2=sub_tree[1]-part1; 24 | ans=max(ans,(part1*1LL*part2)%m); 25 | } 26 | return ans; 27 | } 28 | -------------------------------------------------------------------------------- /Bit-Manipulation/counting-bits.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/counting-bits/ 2 | 3 | // Naive approach 4 | 5 | class Solution { 6 | public: 7 | vector countBits(int num) { 8 | vectorcb; 9 | for(int i=0;i<=num;i++){ 10 | int cnt=0; 11 | int n=i; 12 | while(n){ 13 | cnt++; 14 | n=n&(n-1); 15 | } 16 | cb.push_back(cnt); 17 | 18 | } 19 | 20 | return cb; 21 | } 22 | }; 23 | 24 | // optimized dp O(n) 25 | 26 | class Solution { 27 | public: 28 | vector countBits(int n) { 29 | vectorres(n+1,0); 30 | res[0]=0; 31 | for(int i=1;i<=n;i++){ 32 | res[i]+=(res[i/2]+(i&1)); 33 | } 34 | return res; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /CSES-Problem-Set/graph/shortest-routes-II.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1672/ 2 | #include 3 | using namespace std; 4 | #define int long long 5 | #define INF (int) (1e18) 6 | const int N=1e5+10; 7 | signed main() { 8 | int n,m,q; 9 | cin>>n>>m>>q; 10 | int arr[n+1][n+1]; 11 | for(int i=1;i<=n;i++){ 12 | for(int j=1;j<=n;j++){ 13 | arr[i][j]=INF; 14 | if(i==j)arr[i][j]=0; 15 | } 16 | } 17 | for(int i=0;i>a>>b>>w; 20 | arr[a][b]=min(arr[a][b],w); 21 | arr[b][a]=min(arr[b][a],w); 22 | } 23 | for(int k=1;k<=n;k++){ 24 | for(int i=1;i<=n;i++){ 25 | for(int j=1;j<=n;j++){ 26 | arr[i][j]=min(arr[i][j],arr[i][k]+arr[k][j]); 27 | } 28 | } 29 | } 30 | while(q--){ 31 | int t,r; 32 | cin>>t>>r; 33 | if(arr[t][r]==INF)cout<<-1<>st; 8 | for(auto c:s){ 9 | if(!st.empty() && st.top().first==c){ 10 | st.top().second++; 11 | }else{ 12 | st.push({c,1}); 13 | } 14 | if(st.top().second==k){ 15 | st.pop(); 16 | } 17 | } 18 | string res=""; 19 | while(!st.empty()){ 20 | auto it=st.top(); 21 | while(it.second-->0){ 22 | res+=it.first; 23 | } 24 | st.pop(); 25 | } 26 | reverse(res.begin(),res.end()); 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Recursion-Backtracking/permutations-II.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/permutations-ii/ 3 | 4 | class Solution { 5 | public: 6 | void findPermutation(vector nums, vector> &result,int index){ 7 | if(index >= nums.size()){ 8 | result.push_back(nums); 9 | return; 10 | } 11 | unordered_setst; 12 | for(int i=index; i> permuteUnique(vector& nums) { 21 | vector> result; 22 | findPermutation(nums, result ,0); 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Vector-Array/shortest-unsorted-continuous-subarray.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ 3 | 4 | class Solution { 5 | public: 6 | int findUnsortedSubarray(vector& nums) { 7 | int mini=INT_MAX,maxi=INT_MIN; 8 | int n=nums.size(); 9 | for(int i=1;i=0;i--){ 15 | if(nums[i]>nums[i+1]){ 16 | maxi=max(nums[i],maxi); 17 | } 18 | } 19 | if(mini==INT_MAX && maxi==INT_MIN)return 0; 20 | int s=0,e=n-1; 21 | for(;smini)break; 23 | } 24 | for(;e>=0;e--){ 25 | if(nums[e]& nums) { 7 | int n=nums.size(); 8 | int prev1=nums[0]; 9 | int prev2=0; 10 | for(int i=1;i1)pick+=prev2; 13 | int notpick=0+prev1; 14 | int curr=max(pick,notpick); 15 | prev2=prev1; 16 | prev1=curr; 17 | } 18 | return prev1; 19 | } 20 | int rob(vector& nums) { 21 | vectorvec1,vec2; 22 | if(nums.size()==1)return nums[0]; 23 | for(int i=0;i q; 8 | for(int i=0;i<=9;i++){ 9 | q.push(i); 10 | } 11 | while(!q.empty()){ 12 | int curr=q.front(); 13 | q.pop(); 14 | if(curr>=n&&curr<=m){ 15 | ans++; 16 | } 17 | if(curr==0||curr>=m)continue; 18 | // ld = last digit 19 | int ld=curr%10; 20 | int step1=curr*10+(ld-1); 21 | int step2=curr*10+(ld+1); 22 | if(ld==0)q.push(step2); 23 | else if(ld==9)q.push(step1); 24 | else{ 25 | q.push(step1); 26 | q.push(step2); 27 | } 28 | } 29 | return ans; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /OOPS/design-underground-system.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/design-underground-system/ 3 | 4 | class UndergroundSystem { 5 | public: 6 | map> customer; 7 | map, pair> total; 8 | UndergroundSystem() { 9 | customer.clear(); 10 | total.clear(); 11 | } 12 | void checkIn(int id, string stationName, int t) { 13 | customer[id]={stationName, t}; 14 | } 15 | void checkOut(int id, string stationName, int t) { 16 | total[{customer[id].first, stationName}]={total[{customer[id].first, stationName}].first+(t-customer[id].second),total[{customer[id].first, stationName}].second+1}; 17 | } 18 | 19 | double getAverageTime(string startStation, string endStation) { 20 | return total[{startStation,endStation}].first/total[{startStation,endStation}].second; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Matrix/spiral-matrix-ii.cpp: -------------------------------------------------------------------------------- 1 | 2 | // https://leetcode.com/problems/spiral-matrix-ii 3 | 4 | class Solution { 5 | public: 6 | vector> generateMatrix(int n) { 7 | vector>vec(n,vector(n,0)); 8 | int rs=0; 9 | int cs=0; 10 | int re=n-1; 11 | int ce=n-1; 12 | int num=1; 13 | while(rs<=re && cs<=ce){ 14 | for(int i=cs;i<=ce;i++){ 15 | vec[rs][i]=num++; 16 | } 17 | rs++; 18 | for(int i=rs;i<=re;i++){ 19 | vec[i][ce]=num++; 20 | } 21 | ce--; 22 | for(int i=ce;i>=cs;i--){ 23 | vec[re][i]=num++; 24 | } 25 | re--; 26 | for(int i=re;i>=rs;i--){ 27 | vec[i][cs]=num++; 28 | } 29 | cs++; 30 | } 31 | return vec; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Trees/Leetcode-99-Recover-Binary-Search-Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | TreeNode* first; 4 | TreeNode* prev; 5 | TreeNode* middle; 6 | TreeNode* last; 7 | public: 8 | void inorder(TreeNode* root){ 9 | if(root==NULL)return; 10 | inorder(root->left); 11 | if(prev!=NULL && (root->val < prev->val)){ 12 | if(first==NULL){ 13 | first=prev; 14 | middle=root; 15 | } 16 | else{ 17 | last=root; 18 | } 19 | } 20 | prev=root; 21 | inorder(root->right); 22 | } 23 | void recoverTree(TreeNode* root) { 24 | first=middle=last=NULL; 25 | prev=new TreeNode(INT_MIN); 26 | inorder(root); 27 | if(first && last) swap(first->val,last->val); 28 | else if(first && middle) swap(first->val,middle->val); 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Vector-Array/Max_circular_sub_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int normalMax(int arr[],int n){ 4 | int res=arr[0],max_end=arr[0]; 5 | for(int i=1;i>t; 29 | while(t--){ 30 | int n,res; 31 | cin>>n; 32 | int arr[n]; 33 | for(int i=0;i>arr[i]; 35 | } 36 | res=overallMax(arr,n); 37 | cout< f(n+1); 17 | if(n == 0){ 18 | return 0; 19 | } 20 | f[0] = 0, f[1] = 1; 21 | for(int i = 2;i<=n;i++){ 22 | f[i] = f[i-1] + f[i-2]; 23 | } 24 | return f[n]; 25 | } 26 | }; 27 | 28 | 29 | 30 | // space optimize 31 | 32 | class Solution { 33 | public: 34 | int fib(int n) { 35 | if(n==0)return 0; 36 | int prev2=0; 37 | int prev1=1; 38 | for(int i=2;i<=n;i++){ 39 | int curr=prev2+prev1; 40 | prev2=prev1; 41 | prev1=curr; 42 | } 43 | return prev1; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Stack-Queue/score-of-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfParentheses(string s) { 4 | 5 | int cnt=0; 6 | stackst; 7 | for(auto x:s){ 8 | if(x=='('){ 9 | st.push(0); 10 | } 11 | else{ 12 | if(st.top()==0){ 13 | st.pop(); 14 | st.push(1); 15 | }else{ 16 | int sum=0; 17 | while(st.top()!=0){ 18 | sum=sum+st.top(); 19 | st.pop(); 20 | } 21 | st.pop(); 22 | st.push(sum*2); 23 | } 24 | } 25 | 26 | } 27 | int res=0; 28 | while(!st.empty()){ 29 | res+=st.top(); 30 | st.pop(); 31 | } 32 | return res; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Matrix/shift-2d-grid.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/shift-2d-grid/ 3 | 4 | class Solution { 5 | public: 6 | void reverse(vector&vec,int l,int r){ 7 | while(l> shiftGrid(vector>& grid, int k) { 12 | vectorvec; 13 | int n=grid.size(); 14 | int m=grid[0].size(); 15 | for(int i=0;i wordSubsets(vector& words1, vector& words2) { 4 | vector fre2(26,0); 5 | for (auto word: words2){ 6 | vector temp(26,0); 7 | for (auto ch:word) 8 | temp[ch-'a']++; 9 | for (int i=0;i<26;i++){ 10 | fre2[i] = max(fre2[i],temp[i]); 11 | } 12 | } 13 | vector ans; 14 | for (auto word:words1){ 15 | vector fre1(26,0); 16 | for (auto ch:word) 17 | fre1[ch-'a']++; 18 | bool flag = true; 19 | for (int i =0;i<26;i++){ 20 | if (fre1[i]freq1(26,0); 7 | vectorfreq2(26,0); 8 | mapmp1,mp2; 9 | for(auto x:s){ 10 | freq1[x-'a']++; 11 | 12 | } 13 | for(auto it:t){ 14 | freq2[it-'a']++; 15 | } 16 | int cnt=0; 17 | for(auto it:s){ 18 | if(freq2[it-'a']<=0){ 19 | 20 | cnt++; 21 | }else{ 22 | freq2[it-'a']--; 23 | } 24 | } 25 | for(auto it:t){ 26 | if(freq1[it-'a']<=0){ 27 | 28 | 29 | cnt++; 30 | }else{ 31 | freq1[it-'a']--; 32 | } 33 | } 34 | return cnt; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Sorting/the-k-weakest-rows-in-a-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | static bool compare(pair c1, pair c2){ 5 | if(c1.second != c2.second) 6 | return c1.second < c2.second; 7 | else 8 | return c1.first < c2.first; 9 | } 10 | 11 | vector kWeakestRows(vector>& mat, int k) { 12 | vector> vec; 13 | vector ans; 14 | 15 | for(int i = 0; i < mat.size(); ++i){ 16 | int soldiers = 0; 17 | for(int j = 0; j < mat[i].size(); ++j){ 18 | if(mat[i][j] == 1) 19 | soldiers++; 20 | } 21 | vec.push_back(make_pair(i,soldiers)); 22 | 23 | } 24 | 25 | sort(vec.begin(),vec.end(),compare); 26 | 27 | for(int i = 0; i < k; ++i) 28 | ans.push_back(vec[i].first); 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Recursion-Backtracking/letter-case-permutation.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/letter-case-permutation/ 3 | 4 | 5 | class Solution { 6 | public: 7 | void lcp(int ind,string s,vector&ans,string res){ 8 | if(ind>=s.length()){ 9 | ans.push_back(res); 10 | return; 11 | } 12 | int ch = s[ind]; 13 | if(ch>=48 && ch<=57){ 14 | res.push_back(s[ind]); 15 | lcp(ind+1,s,ans,res); 16 | } 17 | else{ 18 | res.push_back(tolower(s[ind])); 19 | lcp(ind+1,s,ans,res); 20 | res.pop_back(); 21 | 22 | res.push_back(toupper(s[ind])); 23 | lcp(ind+1,s,ans,res); 24 | res.pop_back(); 25 | } 26 | } 27 | vector letterCasePermutation(string s) { 28 | vectorans; 29 | string res=""; 30 | lcp(0,s,ans,res); 31 | return ans; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /number-of-nodes-in-the-sub-tree-with-the-same-label.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fun(vector> &adj, string &labels, int i,vector&result){ 4 | vector ans(26, 0); 5 | result[i] = 1; 6 | ans[labels[i] - 'a'] = 1; 7 | 8 | for(int j = 0; j != adj[i].size(); j++) 9 | if(!result[adj[i][j]]){ 10 | vector tmp = fun(adj, labels,adj[i][j],result); 11 | for(int k = 0; k != 26; k++) ans[k] += tmp[k]; 12 | } 13 | 14 | result[i] = ans[labels[i] - 'a']; 15 | 16 | return ans; 17 | } 18 | 19 | vector countSubTrees(int n, vector>& edges, string labels) { 20 | vector> adj(n); 21 | vector result(n,0); 22 | for(int i = 0; i != edges.size(); i++) 23 | {adj[edges[i][0]].push_back(edges[i][1]); 24 | adj[edges[i][1]].push_back(edges[i][0]); 25 | } 26 | 27 | fun(adj, labels, 0,result); 28 | return result; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Dynamic-Programming/minimum-falling-path-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/minimum-falling-path-sum/ 3 | 4 | class Solution { 5 | public: 6 | int minFallingPathSum(vector>& mat) { 7 | int n=mat.size(); 8 | int m=mat[0].size(); 9 | vector>dp(n,vector(m,0)); 10 | for(int i=0;i=0)ld+=(dp[i-1][j-1]); 16 | else ld+=(1e7); 17 | int rd=mat[i][j]; 18 | if(j+1>& image, int sr, int sc, int newColor,int rows,int cols,int source){ 4 | if(sr<0 || sr>=rows || sc<0 || sc>=cols) 5 | return; 6 | else if(image[sr][sc]!=source){ 7 | return; 8 | } 9 | image[sr][sc]=newColor; 10 | dfs(image,sr-1,sc,newColor,rows,cols,source); 11 | dfs(image,sr+1,sc,newColor,rows,cols,source); 12 | dfs(image,sr,sc-1,newColor,rows,cols,source); 13 | dfs(image,sr,sc+1,newColor,rows,cols,source); 14 | } 15 | vector> floodFill(vector>& image, int sr, int sc, int newColor) { 16 | if(newColor==image[sr][sc]){ 17 | return image; 18 | } 19 | int rows=image.size(); 20 | int cols=image[0].size(); 21 | int source=image[sr][sc]; 22 | dfs(image,sr,sc,newColor,rows,cols,source); 23 | return image; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Searching/split-array-largest-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/split-array-largest-sum/ 3 | 4 | class Solution { 5 | public: 6 | int splitArray(vector& nums, int m) { 7 | int start=0; 8 | int end=0; 9 | 10 | for(int i=0;imid){ 20 | sum=x; 21 | pieces++; 22 | } 23 | else{ 24 | sum+=x; 25 | } 26 | } 27 | if(pieces>m){ 28 | start=mid+1; 29 | } 30 | else{ 31 | end=mid; 32 | } 33 | } 34 | return end; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Strings/gray-code.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/gray-code/ 3 | 4 | class Solution { 5 | public: 6 | vector grayCode(int n) { 7 | vector garyString = generate(n); 8 | vector ans; 9 | for(auto i:garyString) 10 | { 11 | ans.push_back(stoi(i,0,2)); 12 | } 13 | return ans; 14 | } 15 | 16 | vector generate(int n) 17 | { 18 | if(n==1) 19 | { 20 | vector an; 21 | an.push_back("0"); 22 | an.push_back("1"); 23 | return an; 24 | } 25 | vector ans; 26 | vector temp = generate(n-1); 27 | for(int i=0;i=0;i--) 32 | { 33 | ans.push_back("1"+temp[i]); 34 | } 35 | return ans; 36 | } 37 | 38 | }; 39 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/traffic-lights.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1163/ 2 | 3 | #include 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | 7 | signed main() { 8 | ios_base::sync_with_stdio(0); 9 | cin.tie(0); 10 | int len,q; 11 | cin>>len>>q; 12 | multisetlens; 13 | lens.insert(len); 14 | 15 | set>ranges ; // store (end,start) easy to do lower bound in pair 16 | 17 | as we need to find equal or greater element of ranges 18 | ranges.insert({len,0}); 19 | while(q--){ 20 | int x; 21 | cin>>x; 22 | auto lb=ranges.lower_bound({x,-1}); 23 | int start=(*lb).second; 24 | int end=(*lb).first; 25 | int diff=end-start; 26 | 27 | ranges.erase(lb); 28 | ranges.insert({x,start}); 29 | ranges.insert({end,x}); 30 | 31 | lens.erase(lens.find(diff)); 32 | lens.insert(x-start); 33 | lens.insert(end-x); 34 | 35 | cout<<*(lens.rbegin())<<" ";//prints greater element in mset. 36 | 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /CSES-Problem-Set/searching-sorting/room-alocation.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1164/ 2 | 3 | #include 4 | using namespace std; 5 | #define mod (int) (1e9+7) 6 | #define int long long 7 | signed main() { 8 | int n; 9 | cin>>n; 10 | vector>>vec; 11 | // vec stores {point (time of event) ,type(in/out),index (value of i) } 12 | for(int i=1;i<=n;i++){ 13 | int start,end; 14 | cin>>start>>end; 15 | vec.push_back({start,{0,i}}); 16 | vec.push_back({end,{1,i}}); 17 | } 18 | sort(vec.begin(),vec.end()); 19 | setavail; 20 | for(int i=1;i<=n;i++){ 21 | avail.insert(i); 22 | } 23 | vectorres(n); 24 | for(auto it:vec){ 25 | if(it.second.first==0){ 26 | res[it.second.second]=*avail.begin(); 27 | avail.erase(avail.begin()); 28 | } 29 | else{ 30 | avail.insert( res[it.second.second]); 31 | } 32 | } 33 | cout<<*max_element(res.begin(),res.end())<&res,vector>&ans){ 15 | if(ind==s.length()){ 16 | ans.push_back(res); 17 | return; 18 | } 19 | for(int i=ind;i> partition(string s) { 28 | vector>ans; 29 | vectorres; 30 | solve(0,s,res,ans); 31 | return ans; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /CSES-Problem-Set/graph/counting-rooms.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | int n,m; 5 | const int maxi=1005; 6 | vector> mov={{0,1},{0,-1},{1,0},{-1,0}}; 7 | char mat[maxi][maxi]; 8 | bool vis[maxi][maxi]; 9 | bool isValid(int x,int y){ 10 | return (x>=0 && y>=0 && x< n && y>n>>m; 28 | for(int i=0;i>mat[i][j]; 31 | } 32 | } 33 | int cnt=0; 34 | for(int i=0;i successfulPairs(vector& spells, vector& potions, long long success) { 7 | sort(potions.begin(),potions.end()); 8 | vectorres; 9 | for(auto it:spells){ 10 | int i=0; 11 | int j=potions.size()-1; 12 | int tem=j+1; 13 | int ans=-1; 14 | while(i<=j){ 15 | int mid=(i+j)/2; 16 | long long res=(long long)it*potions[mid]; 17 | if(res>=success){ 18 | j=mid-1; 19 | ans=mid; 20 | }else{ 21 | i=mid+1; 22 | } 23 | } 24 | // cout< 3 | using namespace std; 4 | #define int long long 5 | #define mod (int) (1e9+7); 6 | const int N=1e5+10; 7 | const int INF=1e18; 8 | int parent[N]; 9 | int sizet[N]; 10 | int n,m; 11 | 12 | void make(int v){ 13 | parent[v]=v; 14 | sizet[v]=1; 15 | } 16 | int find(int v){ 17 | if(parent[v]==v)return parent[v]; 18 | return parent[v]=find(parent[v]); 19 | } 20 | int Union(int a,int b){ 21 | a=find(a); 22 | b=find(b); 23 | if(a!=b){ 24 | if(sizet[a]>n>>m; 34 | int cnm=n; 35 | int sz=1; 36 | for(int i=1;i<=n;i++)make(i); 37 | for(int i=0;i>a>>b; 40 | if(!(find(a)==find(b))){ 41 | int curr_siz=Union(a,b); 42 | cnm--; 43 | sz=max(sz,curr_siz); 44 | } 45 | cout<> verticalTraversal(TreeNode* root) { 6 | map>>mp; 7 | queue>>q; 8 | q.push({root,{0,0}}); 9 | while(!q.empty()){ 10 | auto it=q.front(); 11 | q.pop(); 12 | auto nod=it.first; 13 | int x=it.second.first; 14 | int y=it.second.second; 15 | mp[x][y].insert(nod->val); 16 | if(nod->left)q.push({nod->left,{x-1,y+1}}); 17 | if(nod->right)q.push({nod->right,{x+1,y+1}}); 18 | } 19 | vector>res; 20 | for(auto it:mp){ 21 | vectorcol; 22 | for(auto pt:it.second){ 23 | col.insert(col.end(),pt.second.begin(),pt.second.end()); 24 | } 25 | res.push_back(col); 26 | } 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /CSES-Problem-Set/trees/Tree-Distances-I.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long int 3 | using namespace std; 4 | vector adj[200005]; 5 | int ans[200005]; 6 | int d=0,x=0; 7 | int d1=0,x1=0; 8 | void dfs(int s,int p,int dep){ 9 | for(auto c:adj[s]){ 10 | if(c!=p) dfs(c,s,dep+1); 11 | } 12 | if(dep>d)d=dep,x=s; 13 | } 14 | void dfs3(int s,int p,int dep){ 15 | for(auto c:adj[s]){ 16 | if(c!=p) dfs3(c,s,dep+1); 17 | } 18 | if(dep>d1)d1=dep,x1=s; 19 | } 20 | void dfs2(int s,int p,int dep){ 21 | ans[s]=max(ans[s],dep); 22 | for(auto c:adj[s]){ 23 | if(c!=p) dfs2(c,s,dep+1); 24 | } 25 | 26 | } 27 | int main() { 28 | int n; 29 | cin>>n; 30 | for(int i=0;i>a>>b; 33 | adj[a].push_back(b); 34 | adj[b].push_back(a); 35 | } 36 | dfs(1,0,0); 37 | // cout<&arr){ 7 | vector>dp(n,vector(k+1,0)); 8 | for(int i=0;i& nums) { 21 | if(nums.size()==1)return false; 22 | int sum=0; 23 | for(auto it:nums){ 24 | sum+=it; 25 | } 26 | if(sum&1)return false; 27 | sum=sum/2; 28 | return subst(nums.size(),sum,nums); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /CSES-Problem-Set/trees/distinct-colors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | 5 | int n,q; 6 | const int maxi=2e5+5; 7 | vector adj[maxi]; 8 | int values[maxi],ans[maxi]; 9 | 10 | set dfs(int c,int p){ 11 | setst; 12 | st.insert(values[c]); 13 | for(auto x:adj[c]){ 14 | if(x!=p){ 15 | set st_child=dfs(x,c); 16 | if(size(st)>size(st_child)){ 17 | for(int it:st_child){ 18 | st.insert(it); 19 | } 20 | }else{ 21 | for(int it:st){ 22 | st_child.insert(it); 23 | } 24 | swap(st,st_child); 25 | } 26 | } 27 | } 28 | ans[c]=size(st); 29 | return st; 30 | } 31 | 32 | int main() { 33 | cin>>n; 34 | for(int i=1;i<=n;i++){ 35 | cin>>values[i]; 36 | } 37 | for(int i=0;i< (n-1);i++){ 38 | int a,b; 39 | cin>>a>>b; 40 | adj[a].push_back(b); 41 | adj[b].push_back(a); 42 | } 43 | dfs(1,1); 44 | for(int i=1;i<=n;i++){ 45 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | const int N=1e5+10; 5 | const int INF=1e9+10; 6 | vector>g[N]; 7 | 8 | void dijkstra(int s,int n){ 9 | vectorvis(N,0); 10 | vectordistance(N,INF); 11 | set>st; 12 | st.insert({0,s}); 13 | distance[s]=0; 14 | while(st.size()>0){ 15 | auto node=*st.begin(); 16 | int v=node.second; 17 | int dist=node.first; 18 | st.erase(st.begin()); 19 | if(vis[v])continue; 20 | vis[v]=1; 21 | for(auto it:g[v]){ 22 | int child_v=it.first; 23 | int wt=it.second; 24 | if(distance[v]+wt>n>>m; 38 | for(int i=0;i>x>>y>>wt; 41 | g[x].push_back({y,wt}); 42 | } 43 | dijkstra(1,n); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /CSES-Problem-Set/trees/company-queries-I.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | 5 | int n,q; 6 | const int lg=22,maxi=2e5+5; 7 | int depth[maxi]; 8 | vector adj[maxi]; 9 | int up[maxi][lg+1]; 10 | void dfs(int v,int p,int d){ 11 | depth[v]=d; 12 | up[v][0]=p; 13 | for(int i=1;i<=lg;i++){ 14 | up[v][i]=up[up[v][i-1]][i-1]; 15 | } 16 | for(int u:adj[v]){ 17 | if(u!=p){ 18 | dfs(u,v,d+1); 19 | } 20 | } 21 | } 22 | int getParent(int a,int k){ 23 | int ans=a; 24 | for(int i=0;i>n>>q; 34 | for(int i=2;i<=n;i++){ 35 | int a; 36 | cin>>a; 37 | adj[a].push_back(i); 38 | adj[i].push_back(a); 39 | } 40 | dfs(1,1,0); 41 | while(q--){ 42 | int node,dist; 43 | cin>>node>>dist; 44 | if(dist>depth[node]){ 45 | cout<<-1<& nums) { 8 | unordered_map freq; 9 | for(int x: nums) freq[x]++; 10 | 11 | unordered_map hm; 12 | 13 | for(int n: nums){ 14 | 15 | if(freq[n] == 0) continue; 16 | 17 | if(hm[n] > 0){ 18 | hm[n]--; 19 | freq[n]--; 20 | 21 | hm[n+1]++; 22 | } 23 | 24 | else if(freq[n]>0 && freq[n+1]>0 && freq[n+2]>0){ 25 | freq[n]--; 26 | freq[n+1]--; 27 | freq[n+2]--; 28 | 29 | hm[n+3]++; 30 | } 31 | 32 | else{ 33 | return false; 34 | } 35 | } 36 | 37 | return true; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /CSES-Problem-Set/graph/message-route.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1667/ 2 | #include 3 | using namespace std; 4 | #define ll long long 5 | int n,m; 6 | const int maxi=1e5+10; 7 | vectorg[maxi]; 8 | int vis[maxi]; 9 | void bfs(){ 10 | vis[1]=-1; 11 | queueq; 12 | q.push(1); 13 | while(!q.empty()){ 14 | auto curr=q.front(); 15 | q.pop(); 16 | for(auto it:g[curr]){ 17 | if(!vis[it]){ 18 | vis[it]=curr; 19 | q.push(it); 20 | } 21 | } 22 | } 23 | } 24 | int main() { 25 | cin>>n>>m; 26 | int cnt=0; 27 | for(int i=0;i>a>>b; 30 | g[a].push_back(b); 31 | g[b].push_back(a); 32 | } 33 | bfs(); 34 | vectorres; 35 | int tem=n; 36 | while(vis[tem] && vis[tem]!=-1){ 37 | res.push_back(vis[tem]); 38 | tem=vis[tem]; 39 | } 40 | if(size(res)){ 41 | reverse(res.begin(),res.end()); 42 | res.push_back(n); 43 | cout<& inorder, vector& postorder) { 4 | if (inorder.size() != postorder.size()) 5 | return NULL; 6 | map hm; 7 | for (int i=0;i &inorder, int is, int ie, vector &postorder, int ps, int pe, map &hm){ 13 | if (ps>pe || is>ie) return NULL; 14 | TreeNode* root = new TreeNode(postorder[pe]); 15 | int ri = hm[postorder[pe]]; 16 | TreeNode* leftchild = buildTreePostIn(inorder, is, ri-1, postorder, ps, ps+ri-is-1, hm); 17 | TreeNode* rightchild = buildTreePostIn(inorder,ri+1, ie, postorder, ps+ri-is, pe-1, hm); 18 | root->left = leftchild; 19 | root->right = rightchild; 20 | return root; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Matrix/spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/spiral-matrix/ 3 | 4 | class Solution { 5 | public: 6 | vector spiralOrder(vector>& matrix) { 7 | int n=matrix.size(); 8 | int m=matrix[0].size(); 9 | vectorvec; 10 | int rs=0; 11 | int cs=0; 12 | int re=n-1; 13 | int ce=m-1; 14 | 15 | while(rs<=re && cs<=ce){ 16 | for(int i=cs;i<=ce;i++){ 17 | vec.push_back(matrix[rs][i]); 18 | } 19 | rs++; 20 | for(int i=rs;i<=re;i++){ 21 | vec.push_back(matrix[i][ce]); 22 | } 23 | ce--; 24 | if(rs<=re){ 25 | for(int i=ce;i>=cs;i--){ 26 | vec.push_back(matrix[re][i]); 27 | } 28 | re--; 29 | } 30 | if(cs<=ce){ 31 | for(int i=re;i>=rs;i--){ 32 | vec.push_back(matrix[i][cs]); 33 | } 34 | cs++; 35 | } 36 | 37 | } 38 | return vec; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Stack-Queue/smallest-subsequence-of-distinct-characters.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/remove-duplicate-letters/ 2 | // Link : https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ 3 | 4 | class Solution { 5 | public: 6 | string removeDuplicateLetters(string s) { 7 | int n=s.length(); 8 | stackst; 9 | vectorcnt(26,false); 10 | vectorfreq(26,0); 11 | for(auto x:s){ 12 | freq[x-'a']++; 13 | } 14 | for(int i=0;ich && freq[st.top()-'a'] ){ 19 | cnt[st.top()-'a']=false; 20 | st.pop(); 21 | } 22 | st.push(ch); 23 | cnt[ch-'a']=true; 24 | } 25 | string ans; 26 | while(!st.empty()){ 27 | ans+=st.top(); 28 | st.pop(); 29 | } 30 | reverse(ans.begin(),ans.end()); 31 | return ans; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Trees/Construct-a-Binary-Tree-from-Preorder-and-Inorder-Traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* buildTree(vector& preorder, vector& inorder) { 4 | map inMap; 5 | 6 | for(int i = 0; i < inorder.size(); i++) { 7 | inMap[inorder[i]] = i; 8 | } 9 | 10 | TreeNode* root = buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1, inMap); 11 | return root; 12 | } 13 | TreeNode* buildTree(vector& preorder, int preStart, int preEnd, vector& inorder, int inStart, int inEnd, map &inMap) { 14 | if(preStart > preEnd || inStart > inEnd) return NULL; 15 | 16 | TreeNode* root = new TreeNode(preorder[preStart]); 17 | int inRoot = inMap[root->val]; 18 | int numsLeft = inRoot - inStart; 19 | 20 | root->left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap); 21 | root->right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap); 22 | 23 | return root; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic-Programming/frog-jump.cpp: -------------------------------------------------------------------------------- 1 | 2 | // https://www.codingninjas.com/codestudio/problems/frog-jump_3621012 3 | 4 | // MEMOIZ 5 | 6 | int fun(int n,vector &h,vector &dp){ 7 | if(n==0){ 8 | 9 | return 0; 10 | } 11 | if(dp[n]!=-1)return dp[n]; 12 | int l=fun(n-1,h,dp)+abs(h[n]-h[n-1]); 13 | int r=1e7; 14 | if(n>1){ 15 | r=fun(n-2,h,dp)+abs(h[n]-h[n-2]); 16 | } 17 | return dp[n]=min(l,r); 18 | } 19 | 20 | // TABULATION 21 | 22 | int frogJump(int n, vector &heights) 23 | { 24 | int res; 25 | vectordp(n,0); 26 | for(int i=1;i1){ 30 | r=dp[i-2]+abs(heights[i]-heights[i-2]); 31 | } 32 | dp[i]=min(l,r); 33 | } 34 | return dp[n-1]; 35 | } 36 | 37 | // SPACE OPTIMIZATION 38 | 39 | int frogJump(int n, vector &h) 40 | { 41 | int prev2=0; 42 | int prev1=0; 43 | for(int i=1;i1) 47 | r=prev2+abs(h[i]-h[i-2]); 48 | int curr=min(l,r); 49 | prev2=prev1; 50 | prev1=curr; 51 | } 52 | return prev1; 53 | } 54 | -------------------------------------------------------------------------------- /Adv-Graph-Trees/chef-and-reversing.cpp: -------------------------------------------------------------------------------- 1 | // problem-link : codechef.com/problems/REVERSE 2 | // 0/1 bfs 3 | 4 | 5 | #include 6 | using namespace std; 7 | #define ll long long int 8 | const int N=1e5+10; 9 | const int INF=1e9+10; 10 | vector> adj[N]; 11 | vectorlev(N,INF); 12 | int n,m; 13 | int bfs(){ 14 | dequedq; 15 | dq.push_back(1); 16 | lev[1]=0; 17 | while(!dq.empty()){ 18 | int cur_v=dq.front(); 19 | dq.pop_front(); 20 | for(auto &child:adj[cur_v]){ 21 | int child_v=child.first; 22 | int wt=child.second; 23 | if(lev[cur_v]+wt>n>>m; 39 | for(int i=0;i>x>>y; 42 | if(x==y)continue; 43 | adj[x].push_back(make_pair(y,0)); 44 | adj[y].push_back(make_pair(x,1)); 45 | } 46 | cout< 3 | using namespace std; 4 | #define int long long 5 | const int N=1e5+10; 6 | const int INF=1e18; 7 | int n,m,k; 8 | vector> dijkstra(int s,int n,vector>g[]){ 9 | vector>distance(n+1); 10 | multiset>st; 11 | st.insert({0,s}); 12 | 13 | while(st.size()>0){ 14 | auto node=*st.begin(); 15 | int v=node.second; 16 | int dist=node.first; 17 | st.erase(st.begin()); 18 | 19 | if(size(distance[v])>=k)continue; 20 | distance[v].push_back(dist); 21 | for(auto it:g[v]){ 22 | int child_v=it.first; 23 | int wt=it.second; 24 | st.insert({wt+dist,child_v}); 25 | } 26 | } 27 | return distance; 28 | } 29 | signed main() { 30 | cin>>n>>m>>k; 31 | vector>g[n+1]; 32 | for(int i=0;i>x>>y>>wt; 35 | g[x].push_back({y,wt}); 36 | } 37 | vector>res=dijkstra(1,n,g); 38 | for(int i=0;i 3 | using namespace std; 4 | #define int long long 5 | #define mod (int) (1e9+7); 6 | const int N=1e5+10; 7 | const int INF=1e18; 8 | int parent[N]; 9 | int sizet[N]; 10 | int n,m; 11 | void make(int v){ 12 | parent[v]=v; 13 | sizet[v]=1; 14 | } 15 | int find(int v){ 16 | if(parent[v]==v)return parent[v]; 17 | return parent[v]=find(parent[v]); 18 | } 19 | void Union(int a,int b){ 20 | a=find(a); 21 | b=find(b); 22 | if(a!=b){ 23 | if(sizet[a]>n>>m; 32 | for(int i=1;i<=n;i++)make(i); 33 | for(int i=0;i>a>>b; 36 | if(!(find(a)==find(b))){ 37 | Union(a,b); 38 | 39 | } 40 | } 41 | int cnt=0; 42 | for(int i=1;i<=n;i++){ 43 | if(find(i)==i){ 44 | cnt++; 45 | } 46 | } 47 | cout<>& grid, int i, int j){ 8 | if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j]==0){ 9 | return; 10 | } 11 | grid[i][j]=0; 12 | dfs(grid,i+1,j); 13 | dfs(grid,i,j+1); 14 | dfs(grid,i-1,j); 15 | dfs(grid,i,j-1); 16 | } 17 | int numEnclaves(vector>& grid) { 18 | for(int i=0;i& nums, int target){ 7 | int n=nums.size(); 8 | vector>dp(n,vector(target+1,0)); 9 | if(nums[0]==0)dp[0][0]=2; 10 | else dp[0][0]=1; 11 | 12 | if(nums[0]!=0 && nums[0]<=target)dp[0][nums[0]]=1; 13 | 14 | for(int ind=1;ind& nums, int target) { 28 | int sumi=0; 29 | for(auto it:nums){ 30 | sumi+=it; 31 | } 32 | if(sumi-target<0 || (sumi-target)%2==1)return 0; 33 | int val= eqtsum(nums,(sumi-target)/2); 34 | 35 | return val; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Dynamic-Programming/print-longest-common-subsequence-dp.cpp: -------------------------------------------------------------------------------- 1 | void lcs(string s1, string s2) { 2 | 3 | int n = s1.size(); 4 | int m = s2.size(); 5 | 6 | vector < vector < int >> dp(n + 1, vector < int > (m + 1, 0)); 7 | for (int i = 0; i <= n; i++) { 8 | dp[i][0] = 0; 9 | } 10 | for (int i = 0; i <= m; i++) { 11 | dp[0][i] = 0; 12 | } 13 | 14 | for (int ind1 = 1; ind1 <= n; ind1++) { 15 | for (int ind2 = 1; ind2 <= m; ind2++) { 16 | if (s1[ind1 - 1] == s2[ind2 - 1]) 17 | dp[ind1][ind2] = 1 + dp[ind1 - 1][ind2 - 1]; 18 | else 19 | dp[ind1][ind2] = 0 + max(dp[ind1 - 1][ind2], dp[ind1][ind2 - 1]); 20 | } 21 | } 22 | 23 | int len = dp[n][m]; 24 | int i = n; 25 | int j = m; 26 | 27 | int index = len - 1; 28 | string str = ""; 29 | for (int k = 1; k <= len; k++) { 30 | str += "$"; // dummy string 31 | } 32 | 33 | while (i > 0 && j > 0) { 34 | if (s1[i - 1] == s2[j - 1]) { 35 | str[index] = s1[i - 1]; 36 | index--; 37 | i--; 38 | j--; 39 | } else if (dp[i - 1][j]> dp[i][j - 1]) { 40 | i--; 41 | } else j--; 42 | } 43 | cout << str; 44 | } 45 | -------------------------------------------------------------------------------- /Graphs/possible-bipartition.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/possible-bipartition/ 3 | 4 | class Solution { 5 | public: 6 | bool possibleBipartition(int n, vector>& dis) { 7 | vector>graph(n+1); 8 | for(int i=0;icolor(n+1,0); 13 | for(int i=1;i<=n;i++){ 14 | if(color[i]==0){ 15 | queueq; 16 | q.push(i); 17 | color[i]=1; 18 | while(!q.empty()){ 19 | int node=q.front(); 20 | q.pop(); 21 | for(int it:graph[node]){ 22 | if(color[it]==color[node])return false; 23 | else if(color[it]==0){ 24 | q.push(it); 25 | color[it]=-color[node]; 26 | } 27 | } 28 | } 29 | } 30 | } 31 | return true; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Searching/maximum-candies-allocated-to-k-children.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/contest/weekly-contest-287/problems/maximum-candies-allocated-to-k-children/ 3 | 4 | class Solution { 5 | public: 6 | long long maxi(long long x,long long y){ 7 | if(x>=y)return x; 8 | return y; 9 | } 10 | bool isp(vector&c,long long mid,long long k){ 11 | long long cnt=0; 12 | for(auto it:c){ 13 | cnt+=(it/mid); 14 | } 15 | if(cnt>=k)return true; 16 | return false; 17 | } 18 | int maximumCandies(vector& c, long long k) { 19 | long long sum=0; 20 | for(int i=0;i 2 | using namespace std; 3 | #define int long long 4 | const int N=1e5+10; 5 | const int INF=1e18; 6 | int n,m; 7 | vector>g[N]; 8 | vector dijkstra(int s,int n){ 9 | vectorvis(n+1,0); 10 | vectordistance(n+1,INF); 11 | set>st; 12 | st.insert({0,s}); 13 | distance[s]=0; 14 | while(st.size()>0){ 15 | auto node=*st.begin(); 16 | int v=node.second; 17 | int dist=node.first; 18 | st.erase(st.begin()); 19 | if(vis[v])continue; 20 | vis[v]=1; 21 | for(auto it:g[v]){ 22 | int child_v=it.first; 23 | int wt=it.second; 24 | if(distance[v]+wt>n>>m; 36 | for(int i=0;i>x>>y>>wt; 39 | g[x].push_back({y,wt}); 40 | } 41 | vectorres=dijkstra(1,n); 42 | for(int i=1;i<=n;i++){ 43 | cout<>& grid1, vector>& grid2,int n,int m,int i,int j,int &flag){ 6 | if(i<0 || j<0 || i>=n || j>=m || grid2[i][j]==0 ){ 7 | return; 8 | } 9 | grid2[i][j]=0; 10 | if(grid1[i][j]==0)flag=0; 11 | dfs(grid1,grid2,n,m,i-1,j,flag); 12 | dfs(grid1,grid2,n,m,i+1,j,flag); 13 | dfs(grid1,grid2,n,m,i,j-1,flag); 14 | dfs(grid1,grid2,n,m,i,j+1,flag); 15 | } 16 | int countSubIslands(vector>& grid1, vector>& grid2) { 17 | int n=grid2.size(); 18 | int m=grid2[0].size(); 19 | int cnt=0; 20 | for(int i=0;i&vis,vector&dfsvis,vector&res,vector>& graph){ 7 | vis[ind]=true; 8 | dfsvis[ind]=true; 9 | for(auto it:graph[ind]){ 10 | if(!vis[it]){ 11 | if(dfs(it,vis,dfsvis,res,graph)){ 12 | return res[ind]=true; 13 | } 14 | }else if(vis[it] && dfsvis[it]){ 15 | return res[ind]=true; 16 | } 17 | } 18 | dfsvis[ind]=false; 19 | return false; 20 | } 21 | vector eventualSafeNodes(vector>& graph) { 22 | vectorans; 23 | int n=graph.size(); 24 | vectorvis(n,false),dfsvis(n,false),res(n,false); 25 | for(int i=0;i maximumEvenSplit(long long fs) { 6 | if(fs&1)return {}; 7 | long long vem=70; 8 | long long tt=fs; 9 | long long prev=0; 10 | int n=100; 11 | vector ans; 12 | if(fs==2)return {2}; 13 | for(long long i=2;i> findDuplicate(vector& paths) { 7 | vector>ans; 8 | unordered_map>mp; 9 | for(string path:paths){ 10 | string pt; 11 | int i; 12 | for(i=0;i1){ 31 | ans.push_back(it.second); 32 | } 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Vector-Array/find-pivot-index.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/find-pivot-index/ 3 | 4 | // O(n) time and space 5 | class Solution { 6 | public: 7 | int pivotIndex(vector& nums) { 8 | vectorsuf(nums.size()+1); 9 | suf[nums.size()]=0; 10 | for(int i=nums.size()-1;i>=0;i--){ 11 | suf[i]=nums[i]+suf[i+1]; 12 | } 13 | 14 | int sum=0; 15 | for(int i=0;i& nums) { 31 | int rightsum = 0; 32 | for(int i=nums.size()-01;i>=0;i--) 33 | rightsum+=nums[i]; 34 | int leftsum =0; 35 | for(int i=0;i 2 | using namespace std; 3 | #define ll long long int 4 | int n,q; 5 | const int lg=22,maxi=2e5+5; 6 | int timer; 7 | int tin[maxi],tout[maxi]; 8 | vector adj[maxi]; 9 | int up[maxi][lg+1]; 10 | void dfs(int v,int p,int d){ 11 | tin[v]=++timer; 12 | up[v][0]=p; 13 | for(int i=1;i<=lg;i++){ 14 | up[v][i]=up[up[v][i-1]][i-1]; 15 | } 16 | for(int u:adj[v]){ 17 | if(u!=p){ 18 | dfs(u,v,d+1); 19 | } 20 | } 21 | tout[v]=++timer; 22 | } 23 | bool isAnc(int u,int v){ 24 | return (tin[u]<=tin[v] && tout[u]>=tout[v]); 25 | } 26 | int lca(int a,int b){ 27 | if(isAnc(a,b)){ 28 | return a; 29 | } 30 | if(isAnc(b,a)){ 31 | return b; 32 | } 33 | for(int i=lg;i>=0;i--){ 34 | if(!isAnc(up[a][i],b)){ 35 | a=up[a][i]; 36 | } 37 | } 38 | return up[a][0]; 39 | } 40 | int main() { 41 | 42 | cin>>n>>q; 43 | for(int i=2;i<=n;i++){ 44 | int a; 45 | cin>>a; 46 | adj[a].push_back(i); 47 | adj[i].push_back(a); 48 | } 49 | dfs(1,1,0); 50 | while(q--){ 51 | int a,b; 52 | cin>>a>>b; 53 | cout<=0 && cy>=0 && cx> updateMatrix(vector>& mat) { 10 | queue>q; 11 | vector> mov={{0,1},{0,-1},{1,0},{-1,0}}; 12 | for(int i=0;i0){ 21 | auto it=q.front(); 22 | q.pop(); 23 | for(auto pt:mov){ 24 | int cx=it.first+pt.first; 25 | int cy=it.second+pt.second; 26 | if(isValid(cx,cy,mat.size(),mat[0].size()) && mat[cx][cy]<0){ 27 | q.push({cx,cy}); 28 | mat[cx][cy]=mat[it.first][it.second]+1; 29 | } 30 | 31 | } 32 | } 33 | return mat; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /CSES-Problem-Set/graph/road-reparation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define int long long 4 | #define mod (int) (1e9+7); 5 | const int N=1e5+10; 6 | int parent[N]; 7 | int sizet[N]; 8 | int n,m; 9 | void make(int v){ 10 | parent[v]=v; 11 | sizet[v]=1; 12 | } 13 | int find(int v){ 14 | if(parent[v]==v)return parent[v]; 15 | return parent[v]=find(parent[v]); 16 | } 17 | void Union(int a,int b){ 18 | a=find(a); 19 | b=find(b); 20 | if(a!=b){ 21 | if(sizet[a]>n>>m; 30 | vector>>vec; 31 | for(int i=0;i>u>>v>>w; 34 | vec.push_back({w,{u,v}}); 35 | } 36 | int ans=0; 37 | int cnt=0; 38 | for(int i=1;i<=n;i++)make(i); 39 | sort(vec.begin(),vec.end()); 40 | for(auto &it:vec){ 41 | int wt=it.first; 42 | int x=it.second.first; 43 | int y=it.second.second; 44 | if(find(x)==find(y))continue; 45 | Union(x,y); 46 | cnt++; 47 | ans+=wt; 48 | } 49 | if(cnt==n-1){ 50 | cout< 3 | using namespace std; 4 | #define ll long long 5 | int n,m; 6 | const int maxi=1e5+5; 7 | vectorg[maxi]; 8 | stackst; 9 | vectorres; 10 | bool vis[maxi]; 11 | void dfs(int node,int parent){ 12 | vis[node]=true; 13 | st.push(node); 14 | for(auto x:g[node]){ 15 | if(x!=parent){ 16 | if(!vis[x]){ 17 | dfs(x,node); 18 | } 19 | else if(size(res)==0){ 20 | res.push_back(x); 21 | while(!st.empty() && (st.top()!=x)){ 22 | res.push_back(st.top()); 23 | st.pop(); 24 | } 25 | res.push_back(x); 26 | } 27 | } 28 | } 29 | if(st.top()==node)st.pop(); 30 | } 31 | int main() { 32 | cin>>n>>m; 33 | int cnt=0; 34 | int a,b; 35 | for(int i=0;i>a>>b; 37 | g[a].push_back(b); 38 | g[b].push_back(a); 39 | } 40 | for(int i=1;i<=n;i++){ 41 | if(!vis[i]){ 42 | dfs(i,-1); 43 | } 44 | } 45 | if(size(res)){ 46 | cout<mp; 8 | int i= -1; 9 | int j= -1; 10 | int res=0; 11 | while(true){ 12 | bool f1=false,f2=false; 13 | while(i<(int)s.size()-1){ 14 | f1=true; 15 | i++; 16 | char ch=s[i]; 17 | if(mp.find(ch)!=mp.end()){ 18 | mp[ch]++; 19 | }else{ 20 | mp[ch]=1; 21 | } 22 | if(mp[ch]==2)break; 23 | else{ 24 | res=max(res,i-j); 25 | } 26 | 27 | } 28 | while(jleft) 7 | { 8 | TreeNode* prev=curr->left; 9 | while(prev->right){ 10 | prev=prev->right; 11 | } 12 | prev->right=curr->right; 13 | curr->right=curr->left; 14 | curr->left=NULL; 15 | } 16 | curr=curr->right; 17 | } 18 | 19 | } 20 | }; 21 | 22 | 23 | // recursion 24 | 25 | class Solution 26 | { 27 | private: 28 | Node* head=NULL;Node* prev=NULL; 29 | void helper(Node* root){ 30 | if(root==NULL)return; 31 | helper(root->left); 32 | if(prev==NULL)head=root; 33 | else{ 34 | root->left=prev; 35 | prev->right=root; 36 | 37 | } 38 | prev=root; 39 | helper(root->right); 40 | } 41 | public: 42 | //Function to convert binary tree to doubly linked list and return it. 43 | 44 | Node * bToDLL(Node *root) 45 | { 46 | helper(root); 47 | return head; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Graphs/path-with-minimum-effort.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : leetcode.com/problems/path-with-minimum-effort/ 3 | 4 | class Solution { 5 | public: 6 | vector>dir={{0,1},{1,0},{-1,0},{0,-1}}; 7 | bool dfs(int i,int j,int n,int m,int mid,vector>& h,int vis[100][100]){ 8 | if(i==n-1 && j==m-1)return true; 9 | vis[i][j]=1; 10 | bool res=false; 11 | for(auto it:dir){ 12 | int nx=i+it.first; 13 | int ny=j+it.second; 14 | if(nx<0 || ny<0 || nx>=n || ny>=m || vis[nx][ny]==1 || abs(h[i][j]-h[nx][ny])>mid){ 15 | continue; 16 | } 17 | res=res||dfs(nx,ny,n,m,mid,h,vis); 18 | 19 | } 20 | return res; 21 | } 22 | int minimumEffortPath(vector>& heights) { 23 | int s=0,e=INT_MAX,ans=INT_MAX,n=heights.size(),m=heights[0].size(); 24 | while(s<=e){ 25 | int mid=s+(e-s)/2; 26 | int v[100][100]; 27 | memset(v,0,sizeof v); 28 | if(dfs(0,0,n,m,mid,heights,v)){ 29 | ans=min(ans,mid); 30 | e=mid-1; 31 | }else{ 32 | s=mid+1; 33 | } 34 | } 35 | return ans; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Graphs/Leetcode-743-network-delay-time.cpp: -------------------------------------------------------------------------------- 1 | //link : https://leetcode.com/problems/network-delay-time/ 2 | 3 | class Solution { 4 | public: 5 | const int N=1e5+10; 6 | const int INF=1e9+10; 7 | int dijkstra(int s,int n,vector>g[]){ 8 | vectorvis(N,0); 9 | vectordistance(N,INF); 10 | set>st; 11 | st.insert({0,s}); 12 | distance[s]=0; 13 | while(st.size()>0){ 14 | auto node=*st.begin(); 15 | int v=node.second; 16 | int dist=node.first; 17 | st.erase(st.begin()); 18 | if(vis[v])continue; 19 | vis[v]=1; 20 | for(auto it:g[v]){ 21 | int child_v=it.first; 22 | int wt=it.second; 23 | if(distance[v]+wt>& times, int n, int k) { 37 | vector>g[N]; 38 | for(auto it:times){ 39 | g[it[0]].push_back({it[1],it[2]}); 40 | } 41 | return dijkstra(k,n,g); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Strings/minimum-remove-to-make-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ 2 | 3 | class Solution { 4 | public: 5 | string minRemoveToMakeValid(string s) { 6 | int cnt=0; 7 | string ans=""; 8 | for(auto x:s){ 9 | if(x=='('){ 10 | ans+=x; 11 | cnt++; 12 | } 13 | else if(x==')'){ 14 | if(cnt>0){ 15 | ans+=x; 16 | cnt--; 17 | } 18 | 19 | } 20 | else { 21 | ans+=x; 22 | } 23 | } 24 | cout<=0;i--){ 30 | if(ans[i]==')'){ 31 | res+=ans[i]; 32 | cnt++; 33 | }else if(ans[i]=='('){ 34 | if(cnt>0){ 35 | res+=ans[i]; 36 | cnt--; 37 | } 38 | }else{ 39 | res+=ans[i]; 40 | } 41 | } 42 | reverse(res.begin(),res.end()); 43 | return res; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /CSES-Problem-Set/graph/building-teams.cpp: -------------------------------------------------------------------------------- 1 | // link : https://cses.fi/problemset/task/1668/ 2 | #include 3 | using namespace std; 4 | #define ll long long 5 | int n,m; 6 | const int maxi=1e5+10; 7 | vectorg[maxi]; 8 | int color[maxi]; 9 | bool mark[maxi]; 10 | bool isbip; 11 | void bfs(int s,int c){ 12 | queueq; 13 | q.push(s); 14 | mark[s]=true; 15 | color[s]=c; 16 | while(!q.empty()){ 17 | int curr=q.front(); 18 | q.pop(); 19 | int child_color=!color[curr]; 20 | for(auto v:g[curr]){ 21 | if(!mark[v]){ 22 | q.push(v); 23 | mark[v]=true; 24 | color[v]=child_color; 25 | } 26 | else if(color[v]!=child_color){ 27 | isbip=false; 28 | return; 29 | } 30 | } 31 | 32 | } 33 | 34 | } 35 | int main() { 36 | cin>>n>>m; 37 | int cnt=0; 38 | for(int i=0;i>a>>b; 41 | g[a].push_back(b); 42 | g[b].push_back(a); 43 | } 44 | memset(color,-1, sizeof color); 45 | isbip=true; 46 | for(int i=1;i<=n;i++){ 47 | if(!mark[i]){ 48 | bfs(i,0); 49 | } 50 | } 51 | if(isbip){ 52 | for(int i=1;i<=n;i++){ 53 | cout<>& board) { 6 | unordered_setst; 7 | for(int i=0;i<9;i++){ 8 | for(int j=0;j<9;j++){ 9 | 10 | if(board[i][j]!='.'){ 11 | 12 | 13 | string sr="row"+to_string(i)+to_string(board[i][j]); 14 | string sc="colom"+to_string(j)+to_string(board[i][j]); 15 | 16 | if(st.count(sr)){ 17 | return false; 18 | } 19 | st.insert(sr); 20 | 21 | if(st.count(sc)){ 22 | return false; 23 | } 24 | st.insert(sc); 25 | 26 | int box=(i/3)*3+j/3; 27 | string sb="box"+to_string(box)+to_string(board[i][j]); 28 | if(st.count(sb)){ 29 | return false; 30 | } 31 | st.insert(sb); 32 | 33 | 34 | } 35 | 36 | } 37 | 38 | } 39 | return true; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Graphs/dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | class Solution { 6 | void dfs(int node, vector &vis, vector adj[], vector &storeDfs) { 7 | storeDfs.push_back(node); 8 | vis[node] = 1; 9 | for(auto it : adj[node]) { 10 | if(!vis[it]) { 11 | dfs(it, vis, adj, storeDfs); 12 | } 13 | } 14 | } 15 | public: 16 | vectordfsOfGraph(int V, vector adj[]){ 17 | vector storeDfs; 18 | vector vis(V+1, 0); 19 | for(int i = 1;i<=V;i++) { 20 | if(!vis[i]) dfs(i, vis, adj, storeDfs); 21 | } 22 | return storeDfs; 23 | } 24 | }; 25 | 26 | 27 | int main(){ 28 | int tc; 29 | cin >> tc; 30 | while(tc--){ 31 | int V, E; 32 | cin >> V >> E; 33 | 34 | vector adj[V]; 35 | 36 | for(int i = 0; i < E; i++) 37 | { 38 | int u, v; 39 | cin >> u >> v; 40 | adj[u].push_back(v); 41 | adj[v].push_back(u); 42 | } 43 | // string s1; 44 | // cin>>s1; 45 | Solution obj; 46 | vectorans=obj.dfsOfGraph(V, adj); 47 | for(int i=0;i > &mat, string &target,int k,int n,int m){ 7 | if(i>=0 && j>=0 && i > &mat, string target){ 27 | int n=mat.size(); 28 | int m=mat[0].size(); 29 | int ans=0; 30 | for(int i=0;i 2 | using namespace std; 3 | struct node { 4 | int u; 5 | int v; 6 | int wt; 7 | node(int first, int second, int weight) { 8 | u = first; 9 | v = second; 10 | wt = weight; 11 | } 12 | }; 13 | 14 | int main(){ 15 | int N,m; 16 | cin >> N >> m; 17 | vector edges; 18 | for(int i = 0;i> u >> v >> wt; 21 | edges.push_back(node(u, v, wt)); 22 | } 23 | 24 | int src; 25 | cin >> src; 26 | 27 | 28 | int inf = 10000000; 29 | vector dist(N, inf); 30 | 31 | dist[src] = 0; 32 | 33 | for(int i = 1;i<=N-1;i++) { 34 | for(auto it: edges) { 35 | if(dist[it.u] + it.wt < dist[it.v]) { 36 | dist[it.v] = dist[it.u] + it.wt; 37 | } 38 | } 39 | } 40 | 41 | int fl = 0; 42 | for(auto it: edges) { 43 | if(dist[it.u] + it.wt < dist[it.v]) { 44 | cout << "Negative Cycle"; 45 | fl = 1; 46 | break; 47 | } 48 | } 49 | 50 | if(!fl) { 51 | for(int i = 0;i>dp(n+1,vector(m+1,0)); 7 | for(int i=1;i<=n;i++){ 8 | for(int j=1;j<=m;j++){ 9 | if(str1[i-1]==str2[j-1]){ 10 | dp[i][j]=1+dp[i-1][j-1]; 11 | }else{ 12 | dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 13 | } 14 | } 15 | } 16 | int i=n; 17 | int j=m; 18 | string res=""; 19 | while(i>0 && j>0){ 20 | if(str1[i-1]==str2[j-1]){ 21 | res+=(str1[i-1]); 22 | i--; 23 | j--; 24 | }else if(dp[i-1][j]>dp[i][j-1]){ 25 | res+=str1[i-1]; 26 | i--; 27 | }else{ 28 | res+=str2[j-1]; 29 | j--; 30 | } 31 | } 32 | while(i>0){ 33 | res+=str1[i-1]; 34 | i--; 35 | } 36 | while(j>0){ 37 | res+=str2[j-1]; 38 | j--; 39 | } 40 | reverse(res.begin(),res.end()); 41 | return res; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Graphs/as-far-from-land-as-possible.cpp: -------------------------------------------------------------------------------- 1 | // Link : https://leetcode.com/problems/as-far-from-land-as-possible/ 2 | 3 | class Solution { 4 | public: 5 | int maxDistance(vector>& grid) { 6 | vector>dir={{0,1},{1,0},{-1,0},{0,-1}}; 7 | int n=grid.size(); 8 | int m=grid[0].size(); 9 | queue>q; 10 | for(int i=0;i0){ 21 | lev++; 22 | int sz=q.size(); 23 | while(sz--){ 24 | auto it=q.front(); 25 | q.pop(); 26 | for(int i=0;i<4;i++){ 27 | int nx=it.first+dir[i].first; 28 | int ny=it.second+dir[i].second; 29 | if(nx<0 || ny<0 || nx>=n || ny>=m || grid[nx][ny]==1){ 30 | continue; 31 | } 32 | grid[nx][ny]=1; 33 | q.push({nx,ny}); 34 | } 35 | } 36 | } 37 | return lev; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /LinkedList/circular_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Pranav Bharadwaj VScode Snipet 5 2 | #include 3 | using namespace std; 4 | struct node{ 5 | int data; 6 | node *next; 7 | }; 8 | 9 | 10 | void printCircularList(node *start){ 11 | node *temp=start; 12 | if(start!=NULL){ 13 | cout<data<next; 15 | while(temp!=start){ 16 | cout<data<next; 18 | } 19 | } 20 | } 21 | int main(){ 22 | 23 | //LinkedList Data set.. 24 | //creation of linked list 25 | node *head=new node(); 26 | node *second=new node(); 27 | node *third=new node(); 28 | node *four=new node(); 29 | node *five=new node(); 30 | node *six=new node(); 31 | node *seven=new node(); 32 | 33 | //list1 34 | head->data=5; 35 | head->next=second; 36 | //list2 37 | second->data=9; 38 | second->next=third; 39 | //list3 40 | third->data=7; 41 | third->next=four; 42 | //list4 43 | four->data=4; 44 | four->next=five; 45 | //list5 46 | five->data=6; 47 | five->next=six; 48 | //list6 49 | six->data=8; 50 | six->next=seven; 51 | //list7 52 | seven->data=10; 53 | seven->next=head; 54 | 55 | //calling of function 56 | 57 | printCircularList(head); 58 | } -------------------------------------------------------------------------------- /Vector-Array/minimum-average-difference.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/contest/biweekly-contest-77/problems/minimum-average-difference/ 3 | 4 | class Solution { 5 | public: 6 | int minimumAverageDifference(vector& nums) { 7 | vectorpref,suf; 8 | long long sum=0; 9 | for(auto it:nums){ 10 | sum+=it; 11 | pref.push_back(sum); 12 | } 13 | sum=0; 14 | for(int i=nums.size()-1;i>=0;i--){ 15 | sum+=nums[i]; 16 | suf.push_back(sum); 17 | } 18 | reverse(suf.begin(),suf.end()); 19 | suf.push_back(0); 20 | long long res=1e17; 21 | int resi=0; 22 | int n=nums.size(); 23 | int p=1; 24 | for(int i=0;i movesToStamp(string stamp, string t) { 23 | int ques = 0, len_st = stamp.size(), len_t = t.size(); 24 | vector vis(len_t), ans; 25 | 26 | while(ques < len_t){ 27 | bool did_stamp = false; 28 | for(int i=0; i<=len_t-len_st; i++){ 29 | if(!vis[i] and isMatch(t, stamp, i)){ 30 | ans.push_back(i); 31 | vis[i] = did_stamp = 1; 32 | replace(t, i, len_st, ques); 33 | } 34 | } 35 | if(!did_stamp) return {}; 36 | } 37 | 38 | reverse(ans.begin(), ans.end()); 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /CSES-Problem-Set/trees/distance-queries.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | 5 | int n,q; 6 | const int lg=22,maxi=2e5+5; 7 | int timer; 8 | int tin[maxi],tout[maxi]; 9 | vector adj[maxi]; 10 | int up[maxi][lg+1]; 11 | int dep[maxi]; 12 | void dfs(int v,int p,int d){ 13 | tin[v]=++timer; 14 | dep[v]=d; 15 | up[v][0]=p; 16 | for(int i=1;i<=lg;i++){ 17 | up[v][i]=up[up[v][i-1]][i-1]; 18 | } 19 | for(int u:adj[v]){ 20 | if(u!=p){ 21 | dfs(u,v,d+1); 22 | } 23 | } 24 | tout[v]=++timer; 25 | } 26 | bool isAnc(int u,int v){ 27 | return (tin[u]<=tin[v] && tout[u]>=tout[v]); 28 | } 29 | int lca(int a,int b){ 30 | if(isAnc(a,b)){ 31 | return a; 32 | } 33 | if(isAnc(b,a)){ 34 | return b; 35 | } 36 | for(int i=lg;i>=0;i--){ 37 | if(!isAnc(up[a][i],b)){ 38 | a=up[a][i]; 39 | } 40 | } 41 | return up[a][0]; 42 | } 43 | int getDist(int n1,int n2){ 44 | return dep[n1]+dep[n2]-2*dep[lca(n1,n2)]; 45 | } 46 | int main() { 47 | 48 | cin>>n>>q; 49 | for(int i=0;i< n-1;i++){ 50 | int a,b; 51 | cin>>a>>b; 52 | adj[a].push_back(b); 53 | adj[b].push_back(a); 54 | } 55 | dfs(1,1,0); 56 | while(q--){ 57 | int a,b; 58 | cin>>a>>b; 59 | cout<>& grid) { 7 | if(grid[0][0]==1)return -1; 8 | int n=grid.size(); 9 | int m=grid[0].size(); 10 | queue>>q; 11 | q.push({1,{0,0}}); 12 | grid[0][0]=1; 13 | vector>dir={{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}}; 14 | while(!q.empty()){ 15 | int s=q.size(); 16 | while(s--){ 17 | auto it=q.front(); 18 | q.pop(); 19 | int nx=it.second.first; 20 | int ny=it.second.second; 21 | int po=it.first; 22 | if(nx==n-1 && ny==m-1)return po; 23 | for(auto pr:dir){ 24 | int nxk = nx+(pr.first); 25 | int nyk = ny+(pr.second); 26 | if(nxk>=0 && nyk>=0 && nxknext==NULL) return NULL; 13 | ListNode *slow=head; 14 | ListNode *fast=head; 15 | 16 | while(fast && fast->next) 17 | { 18 | slow=slow->next; 19 | fast=fast->next->next; 20 | 21 | if(slow==fast) 22 | break; 23 | 24 | } 25 | if(slow!=fast) return NULL; 26 | slow=head; 27 | while(slow!=fast){ 28 | slow=slow->next; 29 | fast=fast->next; 30 | 31 | } 32 | return slow; 33 | 34 | } 35 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 36 | ListNode * a=headA; 37 | ListNode * b=headB; 38 | 39 | while(a!=NULL && a->next!=NULL){ 40 | a=a->next; 41 | } 42 | b=a; 43 | a->next=headB; 44 | ListNode *res = detectCycle(headA); 45 | b->next=NULL; 46 | return res; 47 | 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Graphs/number-of-ways-to-arrive-at-destination.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public: 5 | int countPaths(int n, vector>& roads) { 6 | int mod=(1e9+7); 7 | vectorways(n,0); 8 | vectordist(n,LONG_MAX); 9 | dist[0]=0; 10 | ways[0]=1; 11 | vector>adj[n]; 12 | for(auto it:roads){ 13 | adj[it[0]].push_back({it[1],it[2]}); 14 | adj[it[1]].push_back({it[0],it[2]}); 15 | } 16 | priority_queue,vector>,greater>>pq; 17 | pq.push({0,0}); 18 | while(!pq.empty()){ 19 | long node=pq.top().second; 20 | long dis=pq.top().first; 21 | pq.pop(); 22 | 23 | for(auto it:adj[node]){ 24 | long wt=it.second; 25 | long adjNode=it.first; 26 | if(wt+disbfsOfGraph(int V, vector adj[]){ 8 | vector bfs; 9 | vector vis(V, 0); 10 | queue q; 11 | q.push(0); 12 | vis[0] = 1; 13 | while(!q.empty()) { 14 | int node = q.front(); 15 | q.pop(); 16 | bfs.push_back(node); 17 | 18 | for(auto it : adj[node]) { 19 | if(!vis[it]) { 20 | q.push(it); 21 | vis[it] = 1; 22 | } 23 | } 24 | } 25 | 26 | return bfs; 27 | } 28 | }; 29 | 30 | // { Driver Code Starts. 31 | int main(){ 32 | int tc; 33 | cin >> tc; 34 | // for multiple graphs 35 | while(tc--){ 36 | int V, E; 37 | cin >> V >> E; 38 | 39 | vector adj[V]; 40 | 41 | for(int i = 0; i < E; i++) 42 | { 43 | int u, v; 44 | cin >> u >> v; 45 | adj[u].push_back(v); 46 | // adj[v].push_back(u); // uncomment this for undirected graoh 47 | } 48 | // string s1; 49 | // cin>>s1; 50 | Solution obj; 51 | vectorans=obj.bfsOfGraph(V, adj); 52 | for(int i=0;i& board,vector> &ans,vector& leftrow,vector& updiag,vector& lowdiag,int n){ 7 | if(col==n){ 8 | ans.push_back(board); 9 | return; 10 | } 11 | for(int row=0;row> solveNQueens(int n) { 26 | vector>ans; 27 | vectorboard(n); 28 | string s(n,'.'); 29 | for(int i=0;ileftrow(n,0); 33 | vectorupdiag(2*n-1,0); 34 | vectorlowdiag(2*n-1,0); 35 | nqu(0,board,ans,leftrow,updiag,lowdiag,n); 36 | return ans; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Graphs/coloring-a-border.cpp: -------------------------------------------------------------------------------- 1 | // Link: https://leetcode.com/problems/coloring-a-border 2 | 3 | class Solution { 4 | public: 5 | 6 | void dfs(vector>& grid, int row, int col, int color) 7 | { 8 | grid[row][col]=-color; 9 | int count=0; 10 | int x[]={0,1,0,-1}; 11 | int y[]={1,0,-1,0}; 12 | for(int i=0;i<4;i++) 13 | { 14 | int r=row+x[i]; 15 | int c=col+y[i]; 16 | if(r<0||c<0||r>=grid.size()||c>=grid[0].size()||abs(grid[r][c])!=color) 17 | { 18 | continue; 19 | } 20 | count++; 21 | if(grid[r][c]==color) 22 | { 23 | dfs(grid,r,c,color); 24 | } 25 | } 26 | if(count==4) 27 | { 28 | grid[row][col]=color; 29 | 30 | } 31 | } 32 | 33 | vector> colorBorder(vector>& grid, int row, int col, int color) 34 | { 35 | dfs(grid,row,col,grid[row][col]); 36 | for(int i=0;i&dp){ 9 | if(ind==0)return arr[ind]; 10 | if(ind<0)return 0; 11 | if(dp[ind]!=-1)return dp[ind]; 12 | int pick=arr[ind]+solve(ind-2,arr,dp); 13 | int notpick=0+solve(ind-1,arr,dp); 14 | return dp[ind]=max(pick,notpick); 15 | } 16 | int findMaxSum(int *arr, int n) { 17 | vectordp(n,-1); 18 | 19 | return solve(n-1,arr,dp); 20 | } 21 | }; 22 | 23 | // TABULATION 24 | 25 | class Solution{ 26 | public: 27 | int findMaxSum(int *arr, int n) { 28 | vectordp(n,-1); 29 | dp[0]=arr[0]; 30 | for(int i=1;i1)pick+=dp[i-2]; 32 | int notpick=0+dp[i-1]; 33 | dp[i]=max(pick,notpick); 34 | } 35 | return dp[n-1]; 36 | } 37 | }; 38 | 39 | // SPACE OPTIMIZATION 40 | 41 | class Solution{ 42 | public: 43 | int findMaxSum(int *arr, int n) { 44 | int prev1=arr[0]; 45 | int prev2=0; 46 | for(int i=1;i1)pick+=prev2; 48 | int notpick=0+prev1; 49 | int curr=max(pick,notpick); 50 | prev2=prev1; 51 | prev1=curr; 52 | } 53 | return prev1; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Graphs/min-cost-to-connect-all-points.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://leetcode.com/problems/min-cost-to-connect-all-points/ 3 | 4 | class Solution { 5 | public: 6 | int minCostConnectPoints(vector>& points) { 7 | int n=points.size(); 8 | vector>>adj(n); 9 | for(int i=0;ist; 23 | priority_queue,vector>,greater>>mt; 24 | mt.push(make_pair(0,0)); 25 | while(st.size() 2 | #include 3 | using namespace std; 4 | void merge(vector& arr, int l,int m,int r){ 5 | int n1=m-l+1,n2=r-m; 6 | int left[n1],right[n2]; 7 | for(int i=0;i& arr, int l,int r) { 41 | if(l>size; 52 | vectorvec; 53 | for (int i=0;i>p; 56 | vec.push_back(p); 57 | 58 | } 59 | merge_sort(vec,0, size-1); 60 | for (int i=0;i st; 9 | int cnt=0; 10 | TreeNode* curr=root; 11 | while(true){ 12 | if(curr!=NULL){ 13 | st.push(curr); 14 | curr=curr->left; 15 | } 16 | else{ 17 | if(st.empty()==true)break; 18 | curr =st.top(); 19 | st.pop(); 20 | cnt++; 21 | if(cnt==k){ 22 | return curr->val; 23 | } 24 | curr=curr->right; 25 | } 26 | 27 | } 28 | return -1; 29 | } 30 | }; 31 | 32 | // recursive 33 | 34 | class Solution { 35 | public: 36 | int count = 0; 37 | int res = -1; 38 | void helper( TreeNode* root, int k){ 39 | if( root != NULL){ 40 | if( res != -1) return; 41 | helper( root->left,k); 42 | count++; 43 | if( count == k){ 44 | res = root->val; 45 | return; 46 | } 47 | 48 | helper(root->right,k); 49 | } 50 | } 51 | int kthSmallest(TreeNode* root, int k) { 52 | 53 | helper(root,k); 54 | return res; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /LinkedList/LeetCode-234-Palindrome-Linked-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverseList(ListNode* head) { 4 | ListNode* cnt =head; 5 | ListNode* prev=nullptr; 6 | while(head){ 7 | head=head->next; 8 | cnt->next=prev; 9 | prev=cnt; 10 | cnt=head; 11 | } 12 | return prev; 13 | } 14 | ListNode* middleNode(ListNode* head) { 15 | if(head==NULL || head->next==NULL) return head; 16 | ListNode* slow=head; 17 | ListNode* fast=head; 18 | while(fast->next!=NULL && fast->next->next!=NULL){ 19 | slow = slow->next; 20 | fast = fast->next->next; 21 | } 22 | return slow; 23 | } 24 | bool isPalindrome(ListNode* head) { 25 | ListNode* mid=middleNode(head); 26 | ListNode* nhead=mid->next; 27 | mid->next = nullptr; 28 | nhead=reverseList(nhead); 29 | ListNode* i=head; 30 | ListNode* j=nhead; 31 | bool ans=true; 32 | while(i!=NULL && j!=NULL){ 33 | if(i->val!=j->val){ 34 | ans=false; 35 | break; 36 | } 37 | i=i->next; 38 | j=j->next; 39 | 40 | } 41 | nhead=reverseList(nhead); 42 | mid->next=nhead; 43 | return ans; 44 | 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Adv-Graph-Trees/city-and-campers.cpp: -------------------------------------------------------------------------------- 1 | // link : https://www.hackerearth.com/practice/data-structures/disjoint-data-strutures/basics-of-disjoint-data-structures/practice-problems/algorithm/city-and-campers/ 2 | #include 3 | using namespace std; 4 | #define int long long 5 | #define mod (int) (1e9+7); 6 | const int N=1e5+10; 7 | const int INF=1e18; 8 | int parent[N]; 9 | int sizet[N]; 10 | multisetsizes; 11 | int n,m; 12 | void make(int v){ 13 | parent[v]=v; 14 | sizet[v]=1; 15 | sizes.insert(1); 16 | } 17 | int find(int v){ 18 | if(parent[v]==v)return parent[v]; 19 | return parent[v]=find(parent[v]); 20 | } 21 | void merge(int a,int b){ 22 | sizes.erase(sizes.find(sizet[a])); 23 | sizes.erase(sizes.find(sizet[b])); 24 | sizes.insert(sizet[a]+sizet[b]); 25 | } 26 | void Union(int a,int b){ 27 | a=find(a); 28 | b=find(b); 29 | if(a!=b){ 30 | if(sizet[a]>n>>m; 40 | for(int i=1;i<=n;i++)make(i); 41 | for(int i=0;i>a>>b; 44 | if(!(find(a)==find(b))){ 45 | Union(a,b); 46 | } 47 | if(sizes.size()==1){ 48 | cout<<0< 3 | using namespace std; 4 | 5 | //.......................node is user define datatype , which contain two elements in it.................................... 6 | // 1) integer data (its own data) 7 | // 2) node type pointer, used to store address of next node 8 | struct node{ 9 | int data; 10 | node *next; 11 | }; 12 | 13 | // printList() function is used to print data stores in all nodes 14 | void printList(node *n) 15 | { 16 | while(n!=NULL){ 17 | cout<data<next; 19 | 20 | } 21 | } 22 | 23 | int main(){ 24 | 25 | // defining three pointers of type node, use to point elements of node 26 | node *head=new node(); 27 | node *second=new node(); 28 | node *third=new node(); 29 | 30 | head->data=5; 31 | // next pointer of head node stores addresscof second node 32 | head->next=second; 33 | 34 | second->data=9; 35 | // next pointer of second node stores address of third node 36 | second->next=third; 37 | 38 | third->data=7; 39 | // next pointer of third node stores NULL value in it, because there is no next node 40 | third->next=NULL; 41 | 42 | // calling to print data of all nodes, using only head node 43 | printList(head); 44 | } 45 | -------------------------------------------------------------------------------- /Dynamic-Programming/vacation.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Link : https://atcoder.jp/contests/dp/tasks/dp_c 3 | 4 | // Memo 5 | 6 | int fun(int day,int last,vector> &points, vector> &dp){ 7 | if(day==0){ 8 | int maxi=0; 9 | for(int i=0;i<3;i++){ 10 | if(i!=last){ 11 | maxi=max(maxi,points[0][i]); 12 | } 13 | } 14 | return maxi; 15 | } 16 | if(dp[day][last]!=-1)return dp[day][last]; 17 | int maxim=0; 18 | for(int k=0;k<3;k++){ 19 | if(k!=last){ 20 | int point=points[day][k]+fun(day-1,k,points,dp); 21 | maxim=max(maxim,point); 22 | } 23 | } 24 | return dp[day][last]=maxim; 25 | } 26 | int ninjaTraining(int n, vector> &points) 27 | { 28 | vector>dp(n,vector(4,-1)); 29 | return fun(n-1,3,points,dp); 30 | } 31 | 32 | // Tabulation 33 | 34 | 35 | int ninjaTraining(int n, vector> &points) 36 | { 37 | vector>dp(n,vector(4,0)); 38 | dp[0][0]=max(points[0][1],points[0][2]); 39 | dp[0][1]=max(points[0][0],points[0][2]); 40 | dp[0][2]=max(points[0][1],points[0][0]); 41 | dp[0][3]=max(points[0][1],max(points[0][2],points[0][0])); 42 | 43 | for(int day=1;day 2 | using namespace std; 3 | #define int long long 4 | const int N=1e5+10; 5 | const int INF=1e18; 6 | int n,m; 7 | vectoradj[N]; 8 | bool detectCycle(vector&vis,int v){ 9 | if(vis[v]==2)return true; 10 | vis[v]=2; 11 | for(auto it:adj[v]){ 12 | if(vis[it]!=1){ 13 | if(detectCycle(vis,it)){ 14 | return true; 15 | } 16 | } 17 | } 18 | vis[v]=1; 19 | return false; 20 | } 21 | bool cycleDect(int n){ 22 | vector vis(n+1,0); 23 | for(int i=0;i& visited,vector& res){ 33 | visited[v]=1; 34 | for(auto it:adj[v]){ 35 | if(!visited[it]){ 36 | topoDfs(it,visited, res); 37 | } 38 | } 39 | res.push_back(v); 40 | } 41 | signed main() { 42 | cin>>n>>m; 43 | vector>g[n+1]; 44 | for(int i=0;i>x>>y; 47 | adj[x].push_back(y); 48 | } 49 | bool isCy=cycleDect(n); 50 | if(isCy){ 51 | cout<<"IMPOSSIBLE"< visited(n+5,0); 55 | vectorres; 56 | for(int i=1;i<=n;i++){ 57 | if(!visited[i]){ 58 | topoDfs(i,visited,res); 59 | } 60 | } 61 | reverse(res.begin(),res.end()); 62 | for(auto y:res){ 63 | cout<left==NULL){ 5 | return root->right; 6 | } 7 | else if(root->right==NULL){ 8 | return root->left; 9 | } 10 | TreeNode* righ=root->right; 11 | TreeNode* last=findl(root->left); 12 | last->right=righ; 13 | return root->left; 14 | } 15 | TreeNode* findl(TreeNode* root){ 16 | while(root->right){ 17 | root=root->right; 18 | } 19 | return root; 20 | } 21 | TreeNode* deleteNode(TreeNode* root, int key) { 22 | if(root==NULL)return NULL; 23 | if(root->val==key) return helper(root); 24 | TreeNode* curr=root; 25 | while(root!=NULL){ 26 | if(root->val>key){ 27 | if(root->left && root->left->val==key){ 28 | root->left=helper(root->left); 29 | break; 30 | } 31 | else{ 32 | root=root->left; 33 | } 34 | } 35 | else{ 36 | if(root->right && root->right->val==key){ 37 | root->right=helper(root->right); 38 | break; 39 | } 40 | else{ 41 | root=root->right; 42 | } 43 | } 44 | } 45 | return curr; 46 | } 47 | }; 48 | --------------------------------------------------------------------------------