├── Architecture_flow └── README.md ├── Binary Trees ├── Level order Models │ ├── Readme.md │ ├── 22. Find bottom left tree value.cpp │ ├── 23. Find largest value in each row.cpp │ ├── 19. Populating next right pointer in each node.cpp │ ├── 7. BT level order.cpp │ ├── 30. Zigzag in BT.cpp │ ├── 42. Check given tree is heap.cpp │ └── 46. Kth distance from root.cpp ├── 21. Count number of nodes.cpp ├── 6. Max depth BT.cpp ├── 4. Same tree.cpp ├── 18. Flatten BT to LL.cpp ├── 36. Check BST.cpp ├── 56. Finding Profession.cpp ├── 10. Min depth BT.cpp ├── 9. Balanced BT.cpp ├── 25. LCA BST.cpp ├── 26. Unique BST.cpp ├── 5. Symmetric tree.cpp ├── 32. kth smallest BST.cpp ├── 15. Diameter of BT.cpp ├── 16. BT Tilt.cpp ├── 33. LCA BT.cpp ├── Paths Models │ ├── 24. Sum root to leaf numbers.cpp │ ├── 11. Path sum.cpp │ ├── 13. BT paths.cpp │ └── 12. Path sum 2.cpp ├── 29. Convert sorted array to BST.cpp ├── 45. Expression tree.cpp ├── 48. Add All greater values given node in BST.cpp ├── 50. Count Number of Subtrees having given sum.cpp ├── 17. Sum of left leaves.cpp ├── 37. Top view of BT.cpp ├── 44. PostOrder from Inorder and Preorder.cpp ├── 53. Sum of Nodes with even valued grand parent.cpp ├── 14. Invert BT.cpp ├── 39. Print BST in given range.cpp ├── 41. Construct tree from Preorder.cpp ├── 40. Sum Tree.cpp ├── 47. Find Pair with given target in BST.cpp ├── 55. Check Mirror in N-array tree.cpp ├── 20. Right side view of BT.cpp ├── 28. BT from postorder inorder.cpp ├── 27. BT from preorder inorder.cpp ├── 49. Maximum sum of Non-adjacent Nodes.cpp ├── 38. Bottom view of BT.cpp ├── 57. Check given tree is Complete Binary tree.cpp ├── 42. Check given tree is heap.cpp ├── 43. find mode in BST.cpp ├── 51. Leaves to DLL.cpp ├── 34. Subtree of another tree.cpp ├── 2. Preorder traversal.cpp ├── 1. Inorder traversal.cpp ├── 35. Vertical Traversal of tree.cpp └── 54. Maximum width of Binary Tree.cpp ├── Greedy ├── images │ └── gas.png ├── 1. Jump.cpp ├── 18. Smallest string with given numeric value.cpp ├── 11. Wiggle Subsequence.cpp ├── 2. Jump II.cpp ├── 3. largest num.cpp ├── 5. longest palindrome.cpp ├── 21. Patching array.cpp ├── 13. Maximum Length Chain.cpp ├── 8. Pair with specific difference.cpp ├── 12. Queue Reconstruction by Height.cpp ├── 15. Super Washing Machines.cpp ├── 17. Partition labels.cpp ├── 19. Two City Scheduling.cpp ├── 9. Gas Station.cpp ├── 14. Max sum of increasing order.cpp ├── 20. Activity selection.cpp ├── 4. min no of coins.c ├── 6. N meeting in 1 room.cpp ├── 10. Police and Thieves.cpp └── 16. Can Place Flowers.cpp ├── Array ├── images │ ├── images.png │ └── download.png ├── Easy Ques │ ├── kadanes_algo.cpp │ ├── Cyclic_rotate.cpp │ ├── Sort_012.cpp │ ├── Sorted_subsequence_of_size_of_three.cpp │ └── Common_elements_three_arrays.cpp ├── 50. k-difference pairs.cpp ├── 66. First Missing positive.cpp ├── Sum_ques │ ├── Four_sum.cpp │ ├── 37. Max sum path.cpp │ └── Triplet_sum.cpp ├── 17. longest consecutive sequence.cpp ├── SubArray_ques │ ├── 65. longest subarray with sum divisible by k.cpp │ ├── 16. Max product subarray.cpp │ └── 33. Subarray with equal 0s and 1s.cpp ├── 22. Trapping rainwater.cpp ├── 61. Sequential Digits.cpp ├── 63. Non-decreasing array.cpp └── 19. Buying selling share atmost twice.cpp ├── Stack ├── images │ └── stock.png ├── 16. count reversals.cpp ├── 12. Sort stack.cpp ├── 2. Stack Permutations.java ├── 10. Insert at end of stack.cpp ├── 17. Simplify Path.cpp ├── 1. Evaluate RPN expression.cpp ├── 18. Minimum remove to make valid parentheses.cpp └── 5. Balanced paranthesis.cpp ├── BackTracking ├── images │ └── digits.png ├── 8. Help the odd man out.cpp ├── 6. Array Partition.cpp ├── 7. Permuation with spaces.cpp ├── Combination models │ ├── 2_4. Combination sum 4.cpp │ ├── 2_3. Combination sum 3.cpp │ └── 2. Combinations.cpp ├── 3. generate parenthesis.cpp ├── 9. Largest number in k swaps.cpp └── 4. Palindrome Partitioning.cpp ├── Linked list ├── images │ └── Reverse.gif ├── 31. Swapping nodes LL.cpp ├── 26. Delete Nth node from last.cpp ├── 33. Count triplets in SLL.cpp ├── 13. Check cirular or not.cpp ├── 27. Rotate list.cpp ├── 34. Insertion Sort for SLL.cpp ├── 12. Middle of LL.cpp ├── 10. Intersection of 2 sorted LL.cpp ├── 28. Remove duplicates from sortedlist 2.cpp ├── 29. Linkedlist cycle 2.cpp ├── 22. Sort 012.cpp ├── 36. swap kth nodes from ends.cpp ├── 35. Sort List.cpp ├── 9. Add two nums LL.cpp ├── 2. Reverse LL given size.cpp └── 23. Delnode greater value on right.cpp ├── Priority Queue ├── images │ └── task.png ├── 1.Find the Original Array from Doubled array.java ├── 11. Construct Target array with mutliple sums.cpp ├── 10. Lucy neighbours.cpp ├── 2. Array of Doubled pairs.java └── 8. Task Scheduler.cpp ├── Mathematical ├── images │ ├── fibonacci.png │ └── rectanglesOverlap.png ├── 19. Next greater num.cpp ├── 32. Sum of 2 integers without + and -.cpp ├── 1. finding nth root of M in nlog m.cpp ├── 31. Water and Jug Problem.cpp ├── 35. Missing Number.cpp ├── 38. Maximum sum LCM.java ├── 36. Rearrange geeks and his classmates.cpp ├── 21. Sum of query 2.cpp ├── 34. Minimum moves to reach target score.cpp ├── 4. Check it is in x^y.cpp ├── 27. nPk.cpp ├── 23. Smallest Positive Integer that cannot be represented as Sum.cpp ├── 22. Factorial values of array.cpp ├── 30. Count Number with Unique Digits.cpp ├── 20. Count sum of consecutives.cpp ├── 33. Pair of Songs with duration divisible by 60.cpp ├── 16. Final destination.cpp ├── 22_1. Factorial of largenum.cpp ├── 11. Repetative Addition of digits.cpp ├── 39. Max points in a line.cpp ├── 10. Finding last most even position.cpp ├── 37. Grouping of numbers.java ├── 14. Check binary is multiple of 3.cpp ├── 8. faithful num.cpp ├── 28.Last digit of a pow b.cpp ├── 13. Check binary representation is palindrome or not.cpp ├── 18. Magic number.cpp ├── 26. nCk.cpp ├── 7. Container most water.cpp ├── 25. Cows of foo land.cpp ├── 29. Fraction to recurring decimal.cpp ├── 6. Count no of triangles.cpp ├── 2. Num of ways to reach Nth way.cpp ├── 9. Overlapping rectangles.cpp └── 15. No of 1s in smallest repunit.cpp ├── Dynamic_programming ├── images │ ├── grid1.jpg │ └── robot2.jpg ├── 38. Number of ways.cpp ├── 15. Painting the fence.cpp ├── 27. Handshake.cpp ├── 6_min_cost_climbing_stairs.cpp ├── 31. Count all pick ups and delivery options.cpp ├── 10. House robber.cpp ├── 12. Unique path.cpp ├── 33. count sorted vowels string.cpp ├── 24. Longest Subsequence-1.cpp ├── 30. Delete and Earn.cpp ├── 20. Longest Increasing Subsequence.cpp ├── 22. Maximum Increasing Subsequence.cpp ├── 37. Triangle.cpp ├── 29. Champagne Tower.cpp ├── 7_min_path_sum.cpp ├── 19. Longest Repeated Subsequence.cpp ├── 11_1. Broken blocks.cpp ├── 32. Form Palindrome.cpp ├── 36. Russian Dolls envelopes.cpp ├── 28. Delete operations for 2 string.cpp ├── 9. frnds paring.cpp ├── 10_1. House robber 2.cpp ├── Grid │ ├── README.md │ └── Min_falling_path_sum_2.cpp ├── 21. LCS of three strings.cpp ├── 11. Gold Mine Problem.cpp ├── 8. subset equal partition.cpp ├── 1. coin problem.cpp ├── 17. Longest Common Subsequence.cpp ├── 5. Integer Break.cpp ├── 12_1. Unique Path 2.cpp └── 4. Perfect Squares.cpp ├── String ├── images │ └── 31_Next_Permutation.gif ├── Direct_logic_based │ ├── README.md │ └── 2. Repeated string match.cpp ├── Pattern_based │ └── 18. Vowels of all substrings.cpp ├── Substring Concept │ ├── README.md │ └── 3. Max difference of zeros and 1s.cpp ├── 34. Exactly one swap.cpp ├── Implementation_based │ ├── 29.Permutation in String.cpp │ └── 17. concatenation of zigzag strings in a row.cpp ├── 37. Minimum characters to be added at front to make it palindrome.java ├── 25. Next Highest Palindrome.cpp ├── 35. Transform string.cpp ├── 39. Word pattern.cpp └── 38. Robot bounded in a circle.cpp ├── Bit Manipulation ├── Gray Code │ ├── 12. Gray Code.py │ └── 12. Gray Code.cpp ├── 14. Counting Bits.cpp ├── 11. single number 2.cpp ├── 9. Swap all even and odd bits.cpp ├── 12. Single Number 3.cpp ├── 1. Num of 1's.cpp ├── 6. Position of 1st set bit.cpp ├── 3. Count no of bits A to B.cpp ├── 10. Powerset.cpp └── 2. Two non repeating.cpp ├── Samsung R & D ├── SwC-Pro-main │ ├── millitary_base_nodes_test_case.jpg │ └── millitary_base_nodes.cpp ├── README.md ├── 7. Sum at level k.cpp └── SWC_3RDJULY.txt ├── Matrix ├── Easy ques │ ├── Readme.md │ └── 2. Search in row and column sorted .cpp ├── 4. kth smallest in matrix multiplication.cpp ├── 13. Compute Matrix.cpp ├── 7. Rotate 90.cpp ├── 11. Find Rectangle with corner as 1.cpp ├── 14. Filp columns for max no.of equal rows.cpp └── 9. kth smallest in matrix.cpp ├── Trie ├── README.md └── 1. insert and search.cpp ├── Searching Sorting ├── Easy ques │ ├── Smaller_on_left.cpp │ ├── merge_two_sorted_array_const_space.cpp │ ├── Majority_element.cpp │ ├── Repeat_and_missing.cpp │ ├── Pair_with_given_difference.cpp │ ├── Farthest number.cpp │ ├── count_triplets_less_than_sum.cpp │ └── count_triplet_with_given_range.cpp ├── 30. Minimum number in sorted array.cpp ├── 24. H-index.cpp ├── 15. atleast trailing zeros.cpp ├── 26. Koko Eating Bananas.cpp ├── 29. Min Swaps to sort.cpp ├── 27. Smallest Absolute difference.cpp ├── 25.Split array largest sum.cpp ├── 17. merging overlap intervals.cpp └── 18. Merging overlap intervals 2.cpp ├── Prefix_Suffix ├── 1. product of array itself.cpp ├── 3. max length continous subarr with equal 0 1.cpp ├── 2. continous subarr size atleast 2 multiple of k.cpp ├── 5. Car Pooling.cpp ├── Conceptual Ques │ └── 4. Best Sight Seeing Pair.cpp └── README.md ├── Graph ├── 2. Find the town judge.cpp ├── 5. Biconnected Graph.cpp ├── 8. Eulerian Path in Undirected path.cpp ├── 24. Negative weight cycle.cpp ├── 3. DFS of Graph.cpp ├── 16. Bipartite graph.cpp ├── 6. Mother Vertex.cpp ├── 19. Minimum Spanning tree.cpp ├── 12. Detect cycle in a undirected graph.cpp ├── 17. Implementing Dijkstra Algorithm.cpp ├── 15. Topological sort.cpp ├── 7. Count the paths.cpp ├── 11. Detect cycle in a directed graph.cpp ├── 26. Prerequisites tasks.cpp ├── 10. Find whether path exist.cpp ├── 1. Steps by Knight.cpp ├── 9. Transitive closure of a graph.cpp ├── 22. course schedule.cpp └── 29. Path with max probability.cpp ├── Sliding Window ├── 7. Subarray Product less than K.cpp ├── 9. Max points you can obtain from cards.cpp ├── 4. Count anagrams.cpp ├── 5. count distnict elements in each window.cpp ├── 8. Smallest window containing 012.cpp ├── 10. Equivalent sub arrays.cpp ├── 3. Sliding window max.cpp └── 6. count the no of subarrays in given range.cpp └── Heap └── 1. Merge two binary max heap.cpp /Architecture_flow/README.md: -------------------------------------------------------------------------------- 1 | # Architecture flow 2 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/Readme.md: -------------------------------------------------------------------------------- 1 | # Approach 2 |
3 |4 | -------------------------------------------------------------------------------- /Greedy/images/gas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Greedy/images/gas.png -------------------------------------------------------------------------------- /Array/images/images.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Array/images/images.png -------------------------------------------------------------------------------- /Stack/images/stock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Stack/images/stock.png -------------------------------------------------------------------------------- /Array/images/download.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Array/images/download.png -------------------------------------------------------------------------------- /BackTracking/images/digits.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/BackTracking/images/digits.png -------------------------------------------------------------------------------- /Linked list/images/Reverse.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Linked list/images/Reverse.gif -------------------------------------------------------------------------------- /Priority Queue/images/task.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Priority Queue/images/task.png -------------------------------------------------------------------------------- /Mathematical/images/fibonacci.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Mathematical/images/fibonacci.png -------------------------------------------------------------------------------- /Dynamic_programming/images/grid1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Dynamic_programming/images/grid1.jpg -------------------------------------------------------------------------------- /Dynamic_programming/images/robot2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Dynamic_programming/images/robot2.jpg -------------------------------------------------------------------------------- /String/images/31_Next_Permutation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/String/images/31_Next_Permutation.gif -------------------------------------------------------------------------------- /Mathematical/images/rectanglesOverlap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/teja963/Advanced-DSA-and-CS-Theory/HEAD/Mathematical/images/rectanglesOverlap.png -------------------------------------------------------------------------------- /Bit Manipulation/Gray Code/12. Gray Code.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def grayCode(self, n: int) -> List[int]: 3 | curr= [i^i>>1 for i in range(1<
3 | Search in row and column sorted in O(M+N): First search in last col and go to row 4 |5 | -------------------------------------------------------------------------------- /Array/Easy Ques/kadanes_algo.cpp: -------------------------------------------------------------------------------- 1 | #include
3 | Maximum diff of zeros and ones 4 | 1 1 0 0 0 0 1 0 0 0 1. -----> -1 -1 1 1 1 1 -1 1 1 1 -1. --->Max sum subaray(kadane's) 5 | |_ _ _ _ _ _ _ | 6 |-------------------------------------------------------------------------------- /Dynamic_programming/15. Painting the fence.cpp: -------------------------------------------------------------------------------- 1 | long long countWays(int n, int k){ 2 | // code here 3 | vector
= 0 && j < m){ 7 | if(arr1[i] >= arr2[j]){ swap(arr1[i], arr2[j]); i--; j++;} 8 | else break; 9 | } 10 | sort(arr1, arr1 + n); 11 | sort(arr2, arr2 + m); 12 | } 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /Binary Trees/15. Diameter of BT.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans=0; 4 | int ht(TreeNode* root) 5 | { 6 | if(!root)return 0; 7 | int l=ht(root->left); 8 | int r=ht(root->right); 9 | ans=max(ans,l+r); 10 | return 1+max(l,r); 11 | } 12 | int diameterOfBinaryTree(TreeNode* root) { 13 | if(!root)return 0; 14 | ht(root); 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Binary Trees/16. BT Tilt.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans=0; 4 | int solve(TreeNode* root) 5 | { 6 | if(!root)return 0; 7 | int l = solve(root->left); 8 | int r = solve(root->right); 9 | ans += abs(l-r); 10 | return l + r + root->val; 11 | } 12 | int findTilt(TreeNode* root) { 13 | if(!root)return 0; 14 | solve(root); 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Dynamic_programming/31. Count all pick ups and delivery options.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOrders(int n) { 4 | long long int ans = 1; 5 | for(int i = 1; i <= n; i++){ 6 | ans *= i; 7 | ans %= 1000000007; 8 | ans *= (2 * i - 1); 9 | ans %= 1000000007; 10 | } 11 | return ans % 1000000007; 12 | 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Greedy/3. largest num.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool cmp(int a,int b){ 4 | string s1=to_string(a); 5 | string s2=to_string(b); 6 | return s1+s2>s2+s1; 7 | } 8 | string largestNumber(vector& nums) { 9 | string s; 10 | sort(nums.begin(),nums.end(),cmp); 11 | for(int i=0;i next)return 0; 5 | ListNode* slow=head,*fast=head->next; 6 | while(1){ 7 | if(!fast||!fast->next||!fast->next->next)return 0; 8 | if(slow==fast)return 1; 9 | slow=slow->next; 10 | fast=fast->next->next; 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Linked list/27. Rotate list.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* rotateRight(ListNode* head, int k) { 4 | if(!head)return head; 5 | ListNode* tmp=head; 6 | int size = 1; 7 | while(tmp->next){tmp = tmp->next; size++;} 8 | k = size - k % size; 9 | tmp->next = head; 10 | while(k--)tmp = tmp->next; 11 | head = tmp->next; 12 | tmp->next = NULL; 13 | return head;} 14 | -------------------------------------------------------------------------------- /Graph/2. Find the town judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector >& trust) { 4 | vector v(n+1,0); 5 | for(int i = 0; i < trust.size(); i++) 6 | { 7 | v[trust[i][0]]--; 8 | v[trust[i][1]]++; 9 | } 10 | for(int i = 1; i <= n; i++) 11 | { 12 | if(v[i] == n-1)return i; 13 | } 14 | return -1; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Array/Easy Ques/Sort_012.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector & nums) { 4 | if(nums.size() == 0 || nums.size() == 1)return; 5 | int l = 0,m = 0,h = nums.size()-1; 6 | while(m <= h){ 7 | if(nums[m] == 0)swap(nums[l++], nums[m++]); 8 | else if(nums[m] == 1)m++; 9 | else { 10 | swap(nums[m], nums[h--]); 11 | } 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Matrix/4. kth smallest in matrix multiplication.cpp: -------------------------------------------------------------------------------- 1 | int KthSmallest(int m, int n, int k) { 2 | //Write your code here 3 | int l = 1,h = m*n; 4 | while(l <= h) 5 | { 6 | int mid = (l+h)/2; 7 | int count = 0; 8 | for(int i = 1; i <= m; i++)count += min(mid/i, n); 9 | if(count < k)l = mid+1; 10 | else h = mid-1; 11 | } 12 | return l; 13 | 14 | 15 | -------------------------------------------------------------------------------- /Binary Trees/33. LCA BT.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | if(!root || root == p || root == q)return root; //base case root as empty and single node 5 | TreeNode* l=lowestCommonAncestor(root->left,p,q); 6 | TreeNode* r=lowestCommonAncestor(root->right,p,q); 7 | if(l && r)return root; //if both nodes are not empty 8 | else return l? l: r; 9 | } 10 | -------------------------------------------------------------------------------- /Greedy/5. longest palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPalindrome(string s) { 4 | int i,c=0,mi=0; 5 | unordered_map m; 6 | for(i=0;i s1; 5 | while(!s.empty()) 6 | { 7 | int x = s.top(); 8 | s.pop(); 9 | while(!s1.empty() && s1.top() < x) 10 | { 11 | s.push(s1.top()); 12 | s1.pop(); 13 | } 14 | s1.push(x); 15 | } 16 | while(!s1.empty()) 17 | { 18 | s.push(s1.top()); 19 | s1.pop(); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Binary Trees/Paths Models/24. Sum root to leaf numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans=0; 4 | void sum(TreeNode* root,string s){ 5 | if(!root)return; 6 | s += to_string(root->val); 7 | if(!root->left && !root->right)ans += stoi(s); 8 | sum(root->left,s); 9 | sum(root->right,s); 10 | } 11 | int sumNumbers(TreeNode* root) { 12 | sum(root,""); 13 | return ans; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Greedy/21. Patching array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPatches(vector & nums, int n) { 4 | long long int sum = 0, i = 0, count = 0; 5 | while(sum < n){ 6 | if(i < nums.size() && nums[i] <= sum+1){ 7 | sum += nums[i++]; 8 | } 9 | else{ 10 | count++; 11 | sum += sum + 1; 12 | } 13 | } 14 | return count; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Binary Trees/29. Convert sorted array to BST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* build(vector &v,int l,int h){ 4 | if(l > h)return NULL; 5 | int m = (l+h)/2; 6 | TreeNode* root = new TreeNode(v[m]); 7 | root->left = build(v, l, m-1); 8 | root->right = build(v, m+1, h); 9 | return root; 10 | } 11 | TreeNode* sortedArrayToBST(vector & nums) { 12 | return build(nums, 0, nums.size()-1); 13 | } 14 | -------------------------------------------------------------------------------- /Binary Trees/45. Expression tree.cpp: -------------------------------------------------------------------------------- 1 | int fun(node* root) 2 | { 3 | if(root) 4 | { 5 | int l = fun(root->left); 6 | int r = fun(root->right); 7 | if(!root->left && !root->right)return stoi(root->data); 8 | if(root->data == "+")return l+r; 9 | if(root->data == "-")return l-r; 10 | if(root->data == "*")return l*r; 11 | if(root->data == "/")return l/r; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Binary Trees/48. Add All greater values given node in BST.cpp: -------------------------------------------------------------------------------- 1 | void inorder_modify(Node* root,int &sum) 2 | { 3 | if(!root)return; 4 | inorder_modify(root->right,sum); 5 | root->data = root->data + sum; 6 | sum = root->data; 7 | inorder_modify(root->left,sum); 8 | } 9 | Node* modify(Node *root) 10 | { 11 | // Your code here 12 | if(!root)return root; 13 | int sum = 0; 14 | inorder_modify(root,sum); 15 | return root; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Dynamic_programming/10. House robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector & nums) { 4 | int i,j,k,n = nums.size(); 5 | if(n == 0)return 0; 6 | if(n == 1)return nums[0]; 7 | if(n == 2)return max(nums[0], nums[1]); 8 | int dp[n]; 9 | dp[0] = nums[0]; 10 | dp[1] = max(nums[0], nums[1]); 11 | for(i = 2; i < n; i++)dp[i] = max(dp[i-2] + nums[i], dp[i-1]); 12 | return dp[n-1]; 13 | } 14 | -------------------------------------------------------------------------------- /Searching Sorting/Easy ques/Majority_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int majorityElement(int a[], int size) 4 | { 5 | int i, c = 1, m = 0; 6 | if(size == 1)return a[0]; 7 | else{ 8 | for(i = 1; i < size; i++){ 9 | if(a[m] == a[i])c++; 10 | else c--; 11 | if(c == 0){m = i; c=1;} 12 | } 13 | c = count(a, a+size, a[m]); 14 | if(c > size/2)return a[m]; 15 | else return -1; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Binary Trees/50. Count Number of Subtrees having given sum.cpp: -------------------------------------------------------------------------------- 1 | int traverse(Node* root,int &count,int X) 2 | { 3 | if(!root)return 0; 4 | int l = traverse(root->left,count,X); 5 | int r = traverse(root->right,count,X); 6 | if(l + r + root->data == X)count++; 7 | return l + r + root->data; 8 | 9 | } 10 | int countSubtreesWithSumX(Node* root, int X) 11 | { 12 | // Code here 13 | int count=0; 14 | traverse(root,count,X); 15 | return count; 16 | } 17 | -------------------------------------------------------------------------------- /Bit Manipulation/9. Swap all even and odd bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to swap odd and even bits. 5 | unsigned int swapBits(unsigned int n) 6 | { 7 | // Your code here 8 | unsigned int e=n&0xAAAAAAAA; //get all even bits 9 | unsigned int o=n&0x55555555; //get all odd bits 10 | e>>=1; //right shift 11 | o<<=1; //left shift 12 | return e|o; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Graph/5. Biconnected Graph.cpp: -------------------------------------------------------------------------------- 1 | int biGraph(int arr[], int n, int e) { 2 | // code here 3 | vector adj[n]; 4 | if(n == 1 || (n == 2 and e == 1))return 1; 5 | for(int i = 0; i < 2*e; i += 2){ 6 | adj[arr[i]].push_back(arr[i+1]); 7 | adj[arr[i+1]].push_back(arr[i]); 8 | } 9 | for(auto x: adj){ 10 | if(x.size() < 2)return 0; 11 | } 12 | return 1; 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Graph/8. Eulerian Path in Undirected path.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int eulerPath(int N, vector > graph){ 4 | // code here 5 | int odd_vertices = 0; 6 | for(int i = 0; i < N; i++){ 7 | int count = 0; 8 | for(int j = 0; j < N; j++){ 9 | if(graph[i][j])count++; 10 | } 11 | if(count & 1)odd_vertices++; 12 | } 13 | return odd_vertices == 2; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Searching Sorting/30. Minimum number in sorted array.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find the minimum element in sorted and rotated array. 5 | int minNumber(int arr[], int low, int high) 6 | { 7 | // Your code here 8 | while(low < high){ 9 | int mid = (low + high)/2; 10 | if(arr[mid] > arr[high])low = mid+1; 11 | else high = mid; 12 | } 13 | return arr[low]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Binary Trees/Paths Models/11. Path sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool ans = false; 4 | void psum(TreeNode* root,int k,int s) 5 | { 6 | if(!root)return; 7 | s += root->val; 8 | if(!root->left && !root->right)if(s == k)ans = true; 9 | psum(root->left, k, s); 10 | psum(root->right, k, s); 11 | 12 | } 13 | bool hasPathSum(TreeNode* root, int targetSum) { 14 | psum(root, targetSum, 0); 15 | return ans;} 16 | -------------------------------------------------------------------------------- /Dynamic_programming/12. Unique path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | int dp[m][n]; 5 | for(int i = 0; i < m; i++)dp[i][0] = 1; 6 | for(int i = 0; i < n; i++)dp[0][i] = 1; 7 | for(int i = 1; i < m; i++) 8 | { 9 | for(int j = 1; j < n; j++) 10 | { 11 | dp[i][j] = dp[i-1][j] + dp[i][j-1]; 12 | } 13 | } 14 | return dp[m-1][n-1]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic_programming/33. count sorted vowels string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countVowelStrings(int n) { 4 | vector prev(5, 1), curr(5, 1); 5 | for(int i = 1; i < n; i++){ 6 | for(int j = 0; j < 4; j++){ 7 | curr[j+1] = prev[j+1] + curr[j]; 8 | } 9 | prev = curr; 10 | } 11 | int ans = 0; 12 | ans = accumulate(curr.begin(), curr.end(), 0); 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Greedy/13. Maximum Length Chain.cpp: -------------------------------------------------------------------------------- 1 | /*You are required to complete this method*/ 2 | bool cmp(val a, val b) 3 | { 4 | return a.second < b.second; 5 | } 6 | int maxChainLen(struct val p[],int n) 7 | { 8 | //Your code here 9 | sort(p,p+n,cmp); 10 | int ans = 1; 11 | auto x = p[0]; 12 | for(int i = 1; i < n; i++) 13 | { 14 | if(x.second < p[i].first) 15 | { 16 | ans++; 17 | x = p[i]; 18 | } 19 | } 20 | return ans; 21 | -------------------------------------------------------------------------------- /Binary Trees/Paths Models/13. BT paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector v; 4 | void sum(TreeNode* root,string s){ 5 | if(!root)return; 6 | s += to_string(root->val); 7 | if(!root->left && !root->right)v.push_back(s); 8 | else s += "->"; 9 | sum(root->left,s); 10 | sum(root->right,s); 11 | } 12 | 13 | vector binaryTreePaths(TreeNode* root) { 14 | sum(root,""); 15 | return v; 16 | } 17 | -------------------------------------------------------------------------------- /Array/66. First Missing positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector & nums) { 4 | for(int i = 0; i < nums.size(); i++){ 5 | while(nums[i] > 0 and nums[i] <= nums.size() and nums[nums[i] - 1] != nums[i]){ 6 | swap(nums[i], nums[nums[i] - 1]); 7 | } 8 | } 9 | for(int i = 0; i < nums.size(); i++){ 10 | if(nums[i] != i+1)return i+1; 11 | } 12 | return nums.size()+1; 13 | 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Binary Trees/17. Sum of left leaves.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans=0; 4 | void check(TreeNode* root) 5 | { 6 | if(!root)return; 7 | if(root->left){ 8 | if(!root->left->left&&!root->left->right)ans+=root->left->val; 9 | else check(root->left); 10 | } 11 | if(root->right)check(root->right); 12 | 13 | } 14 | int sumOfLeftLeaves(TreeNode* root) { 15 | check(root); 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Greedy/8. Pair with specific difference.cpp: -------------------------------------------------------------------------------- 1 | lass Solution{ 2 | public: 3 | int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) 4 | { 5 | // Your code goes here 6 | sort(arr,arr+N); 7 | int s=0; 8 | for(int i=N-1;i>0;i--) 9 | { 10 | if(arr[i]-arr[i-1] >& matrix, int target) { 4 | int m = matrix.size(); 5 | int n = matrix[0].size()-1,i = 0; 6 | while(i < m &&n >= 0) 7 | { 8 | int element = matrix[i][n]; 9 | if(element == target)return true; 10 | else if(element < target)i++; 11 | else n--; 12 | } 13 | return false; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Sliding Window/7. Subarray Product less than K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSubarrayProductLessThanK(vector & nums, int k) { 4 | if(k <= 1)return 0; 5 | int left = 0, right, ans = 0; 6 | long long prod = 1; 7 | for(right = 0; right < nums.size(); right++) 8 | { 9 | prod *= nums[right]; 10 | while(left <= right && prod >= k)prod /= nums[left++]; 11 | ans += (right - left + 1); 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Binary Trees/37. Top view of BT.cpp: -------------------------------------------------------------------------------- 1 | 2 | void topView(Node * root) { 3 | map m; 4 | queue >q; 5 | q.push({root,0}); 6 | while(!q.empty()) 7 | { 8 | Node* x = q.front().first; 9 | int p = q.front().second; 10 | q.pop(); 11 | if(x->left)q.push({x->left,p-1}); 12 | if(x->right)q.push({x->right,p+1}); 13 | m.insert({p,x}); 14 | } 15 | for(auto x:m)cout< data<<" "; 16 | -------------------------------------------------------------------------------- /Binary Trees/44. PostOrder from Inorder and Preorder.cpp: -------------------------------------------------------------------------------- 1 | unordered_map m; 2 | void post(int in[], int pre[], int l, int h, int &index) 3 | { 4 | if(l > h)return; 5 | int p = m[pre[index++]]; 6 | post(in, pre, l, p-1, index); 7 | post(in, pre, p+1, h, index); 8 | cout< val; 8 | fun(root->left, root->val, parent); 9 | fun(root->right, root->val, parent); 10 | } 11 | int sumEvenGrandparent(TreeNode* root) { 12 | ans = 0; 13 | fun(root); 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Prefix_Suffix/3. max length continous subarr with equal 0 1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxLength(vector & nums) { 4 | int i, j = 0, k = 0, n = nums.size(); 5 | unordered_map m; 6 | for(i = 0; i < n; i++){ 7 | if(nums[i] == 0)nums[i] = -1; 8 | k += nums[i]; 9 | if(k == 0)j = i+1; 10 | if(m.find(k) != m.end())j = max(j, i-m[k]); 11 | else m[k] = i; 12 | } 13 | return j; 14 | } 15 | -------------------------------------------------------------------------------- /BackTracking/8. Help the odd man out.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector shiftPile(int N, int n){ 4 | // code here 5 | vector > v; 6 | help(1,3,2,v , N); 7 | return v[n-1]; 8 | } 9 | void help(int src, int dest , int helper ,vector > &v ,int n ){ 10 | if(n == 0) return; 11 | help(src , helper , dest , v , n-1 ); 12 | v.push_back({src , dest}); 13 | help( helper , dest , src , v , n-1 ); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Binary Trees/14. Invert BT.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* invertTree(TreeNode* root) { 4 | if(!root)return root; 5 | queue q; 6 | q.push(root); 7 | while(!q.empty()) 8 | { 9 | TreeNode* temp=q.front(); 10 | q.pop(); 11 | if(temp->left)q.push(temp->left); 12 | if(temp->right)q.push(temp->right); 13 | swap (temp->left,temp->right); 14 | } 15 | return root; 16 | } 17 | -------------------------------------------------------------------------------- /Dynamic_programming/24. Longest Subsequence-1.cpp: -------------------------------------------------------------------------------- 1 | int longestSubsequence(int N, int A[]) 2 | { 3 | // code here 4 | vector dp(N,1); 5 | for(int i = 1; i < N; i++) 6 | { 7 | for(int j = 0; j < i; j++) 8 | { 9 | if(abs(A[i] - A[j]) == 1) 10 | { 11 | dp[i] = max(dp[i], dp[j] + 1); 12 | } 13 | } 14 | } 15 | return *max_element(dp.begin(), dp.end()); 16 | } 17 | -------------------------------------------------------------------------------- /Dynamic_programming/30. Delete and Earn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int deleteAndEarn(vector & nums) { 4 | vector dp(10002, 0); 5 | vector freq(10002, 0); 6 | for(int i = 0; i < nums.size(); i++){ 7 | freq[nums[i]]++; 8 | } 9 | dp[0] = freq[0]; 10 | dp[1] = freq[1]; 11 | for(int i = 2; i < 10002; i++){ 12 | dp[i] = max(dp[i-1], dp[i-2] + i * freq[i]); 13 | } 14 | return dp[10001]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Prefix_Suffix/2. continous subarr size atleast 2 multiple of k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSubarraySum(vector & nums, int k) { 4 | unordered_map m; 5 | int i,j,s = 0,c = 0; 6 | m[0] = -1; 7 | for(i = 0; i < nums.size(); i++){ 8 | s += nums[i]; 9 | s %= k; 10 | if(m.find(s) != m.end()){ 11 | if(i-m[s] >= 2)return true;} 12 | else m[s]=i; 13 | } 14 | return false; 15 | } 16 | -------------------------------------------------------------------------------- /Sliding Window/9. Max points you can obtain from cards.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxScore(vector & cardPoints, int k) { 4 | long long int tmp = 0, ans = 0, n = cardPoints.size(); 5 | for(int i = 0; i < k; i++)tmp += cardPoints[i]; 6 | ans = max(ans, tmp); 7 | for(int i = k-1; i >= 0; i--){ 8 | tmp -= cardPoints[i]; 9 | tmp += cardPoints[n-k+i]; 10 | ans = max(ans, tmp); 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Bit Manipulation/Gray Code/12. Gray Code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector grayCode(int n) { 4 | if(n==1)return {0,1}; 5 | vector prev=grayCode(n-1); 6 | vector current; 7 | for(int i=0;i =0;i--) 12 | { 13 | current.push_back(1<<(n-1)|prev[i]); 14 | } 15 | return current; 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Graph/24. Negative weight cycle.cpp: -------------------------------------------------------------------------------- 1 | int isNegativeWeightCycle(int n, vector >edges){ 2 | // Code here 3 | vector dist(n, 1000000); 4 | dist[0] = 0; 5 | for(int i = 1; i < n; i++){ 6 | for(auto x: edges){ 7 | if(dist[x[1]] > dist[x[0]] + x[2]){ 8 | dist[x[1]] = dist[x[0]] + x[2]; 9 | } 10 | } 11 | } 12 | for(auto x: edges){ 13 | if(dist[x[1]] > dist[x[0]] + x[2])return 1; 14 | } 15 | return 0; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Mathematical/34. Minimum moves to reach target score.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMoves(int target, int maxDoubles) { 4 | int moves = 0; 5 | while(target != 1) 6 | { 7 | if(maxDoubles == 0)break; 8 | if(target % 2 == 0 and maxDoubles) 9 | { 10 | target /= 2; 11 | maxDoubles--; 12 | } 13 | else target--; 14 | moves++; 15 | } 16 | return target - 1 + moves; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Dynamic_programming/20. Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | int longestSubsequence(int n, int a[]) 2 | { 3 | // your code here 4 | int dp[n]; 5 | dp[0] = 1; 6 | for(int i = 1; i < n; i++) 7 | { 8 | dp[i] = 1; 9 | for(int j = 0; j < i; j++) 10 | { 11 | if(a[j] < a[i]) 12 | { 13 | dp[i] = max(dp[i], dp[j] + 1); 14 | } 15 | } 16 | } 17 | return *max_element(dp,dp + n); 18 | } 19 | -------------------------------------------------------------------------------- /Binary Trees/39. Print BST in given range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector v; 4 | void inorder(Node* root, int low, int high) 5 | { 6 | if(root) 7 | { 8 | inorder(root->left,low,high); 9 | if(root->data >= low && root->data <= high)v.push_back(root->data); 10 | inorder(root->right,low,high); 11 | } 12 | } 13 | vector printNearNodes(Node *root, int low, int high) { 14 | //code here 15 | inorder(root,low,high); 16 | return v; 17 | } 18 | -------------------------------------------------------------------------------- /Dynamic_programming/22. Maximum Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | int maxSumIS(int arr[], int n) 2 | { 3 | // Your code goes here 4 | vector dp(n); 5 | for(int i = 0; i < n; i++)dp[i] = arr[i]; 6 | for(int i = 1; i < n; i++) 7 | { 8 | for(int j = 0; j < i; j++) 9 | { 10 | if(arr[j] < arr[i]) 11 | { 12 | dp[i] = max(dp[i], dp[j] + arr[i]); 13 | } 14 | } 15 | } 16 | return *max_element(dp.begin(), dp.end()); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic_programming/37. Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector >& triangle) { 4 | int n = triangle.size(); 5 | vector v(n); 6 | for(int i = 0; i < triangle[n-1].size(); i++){ 7 | v[i] = triangle[n-1][i]; 8 | } 9 | for(int i = n-2; i >= 0; i--){ 10 | for(int j = 0; j < triangle[i].size(); j++){ 11 | v[j] = triangle[i][j] + min(v[j], v[j+1]); 12 | } 13 | } 14 | return v[0]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Linked list/34. Insertion Sort for SLL.cpp: -------------------------------------------------------------------------------- 1 | Node* insertionSort(struct Node* head_ref) 2 | { 3 | //code here 4 | Node* curr = head_ref; 5 | Node* head = new Node(-1); 6 | while(curr){ 7 | Node* tmp = head; 8 | while(tmp->next and tmp->next->data < curr->data)tmp = tmp->next; 9 | Node* next = curr->next; 10 | curr->next = tmp->next; 11 | tmp->next = curr; 12 | curr = next; 13 | } 14 | return head->next; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /Stack/2. Stack Permutations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int isStackPermutation(int n, int[] ip, int[] op) { 3 | Stack st = new Stack (); 4 | int j = 0; 5 | for(int i = 0; i < n; i++){ 6 | st.push(ip[i]); 7 | if(st.peek() == op[j]){ 8 | while(st.size() > 0 && st.peek() == op[j]){ 9 | st.pop(); 10 | j++; 11 | } 12 | } 13 | } 14 | return st.empty()?1:0; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Array/Sum_ques/Four_sum.cpp: -------------------------------------------------------------------------------- 1 | bool find4Numbers(int A[], int n, int X) 2 | { 3 | sort(A,A+n); 4 | for(int i = 0; i < n-3; i++) 5 | { 6 | for(int j = i+1; j < n-2; j++) 7 | { 8 | int k = j+1; 9 | int l = n-1; 10 | while(k < l) 11 | { 12 | int s = A[i] + A[j] + A[k] + A[l]; 13 | if(s == X)return true; 14 | else if(s > X)l--; 15 | else k++; 16 | } 17 | } 18 | } 19 | return false; 20 | } 21 | -------------------------------------------------------------------------------- /Greedy/12. Queue Reconstruction by Height.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool cmp(vector &v1, vector &v2) 4 | { 5 | if(v1[0] == v2[0])return v1[1] < v2[1]; 6 | return v1[0] > v2[0]; 7 | } 8 | vector > reconstructQueue(vector >& people) { 9 | vector >ans; 10 | sort(people.begin(), people.end(), cmp); 11 | for(auto x: people) 12 | { 13 | ans.insert(ans.begin() + x[1], x); 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Mathematical/4. Check it is in x^y.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to check if a number 2 | // can be expressed as a^b. 3 | #include 4 | using namespace std; 5 | 6 | bool isPower(int a) 7 | { 8 | if (a == 1) 9 | return true; 10 | 11 | for (int i = 2; i * i <= a; i++) { 12 | double val = log(a) / log(i); 13 | if ((val - (int)val) < 0.00000001) 14 | return true; 15 | } 16 | 17 | return false; 18 | } 19 | 20 | // Driver code 21 | int main() 22 | { 23 | int n = 16; 24 | cout << (isPower(n) ? "Yes" : "No"); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /BackTracking/6. Array Partition.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | bool fun(int start, vector &A, int K, int M){ 4 | if(start >= A.size())return true; 5 | for(int i = start + K - 1; i < A.size(); i++){ 6 | if(A[i] - A[start] > M)return false; 7 | if(fun(i + 1, A, K, M))return true; 8 | } 9 | return false; 10 | } 11 | bool partitionArray(int N, int K, int M, vector &A){ 12 | // code here 13 | sort(A.begin(), A.end()); 14 | return fun(0, A, K, M); 15 | } 16 | -------------------------------------------------------------------------------- /Binary Trees/41. Construct tree from Preorder.cpp: -------------------------------------------------------------------------------- 1 | struct Node* construct(int pre[],int &l,int h,char preLN[]) 2 | { 3 | if(l>h)return NULL; 4 | Node* root = new Node(pre[l]); 5 | if(preLN[l++]=='N') 6 | { 7 | root->left=construct(pre,l,h,preLN); 8 | root->right=construct(pre,l,h,preLN); 9 | } 10 | return root; 11 | 12 | } 13 | struct Node *constructTree(int n, int pre[], char preLN[]) 14 | { 15 | // Code here 16 | int l = 0; 17 | return construct(pre, l, n-1, preLN); 18 | } 19 | -------------------------------------------------------------------------------- /Priority Queue/1.Find the Original Array from Doubled array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findOriginalArray(int[] changed) { 3 | int[] ans = new int[changed.length/2]; 4 | Queue q = new LinkedList<>(); 5 | Arrays.sort(changed); 6 | int i = 0; 7 | for(int num: changed){ 8 | if(!q.isEmpty() && q.peek() == num){ 9 | ans[i++] = q.poll()/2; 10 | } 11 | else q.add(num*2); 12 | } 13 | return q.size() > 0? new int[]{}: ans; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Searching Sorting/Easy ques/Repeat_and_missing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | int *findTwoElement(int *arr, int n) { 6 | // code here 7 | int i,j; 8 | int *a; 9 | for(i = 0; i < n; i++){ 10 | if(arr[abs(arr[i])-1] > 0)arr[abs(arr[i])-1] =- arr[abs(arr[i])-1]; 11 | else j = abs(arr[i]); 12 | } 13 | a[0] = j; 14 | for(i = 0; i < n; i++)if(arr[i] > 0)j = i+1; 15 | a[1] = j; 16 | return a; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Array/17. longest consecutive sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector & nums) { 4 | unordered_map m; 5 | for(auto x: nums)m[x] = 1; 6 | int ans = 0; 7 | for(auto x: m){ 8 | if(m.find(x.first - 1) != m.end())continue; //for skipping back iteration and starting from fresh element 9 | int count = 1; 10 | while(m.find(x.first + count) != m.end())count++; 11 | ans = max(ans, count); 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Greedy/15. Super Washing Machines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMinMoves(vector & machines) { 4 | int sum = accumulate(machines.begin(), machines.end(), 0); 5 | if(sum % machines.size())return -1; //Base case 6 | 7 | int avg = sum / machines.size(), ans = 0, prefix = 0; 8 | for(auto x: machines) 9 | { 10 | sum = max( x - avg, abs(prefix)); 11 | ans = max(ans, sum); 12 | prefix += x-avg; 13 | } 14 | return ans; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Mathematical/27. nPk.cpp: -------------------------------------------------------------------------------- 1 | // A O(n) time and O(1) extra 2 | // space solution to calculate 3 | // the Permutation Coefficient 4 | #include 5 | using namespace std; 6 | 7 | int PermutationCoeff(int n, int k) 8 | { 9 | int P = 1; 10 | 11 | // Compute n*(n-1)*(n-2)....(n-k+1) 12 | for (int i = 0; i < k; i++) 13 | P *= (n-i) ; 14 | 15 | return P; 16 | } 17 | 18 | // Driver Code 19 | int main() 20 | { 21 | int n = 10, k = 2; 22 | cout << "Value of P(" << n << ", " << k 23 | << ") is " << PermutationCoeff(n, k); 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /BackTracking/7. Permuation with spaces.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | vector ans; 3 | void fun(vector &v, int l ,int h, string tmp){ 4 | if(l + 1 > h){ 5 | tmp += v[l]; 6 | ans.push_back(tmp); 7 | return; 8 | } 9 | fun(v, l+1, h, tmp + v[l] + " "); 10 | fun(v, l+1, h, tmp + v[l]); 11 | } 12 | vector permutation(string S){ 13 | // Code Here 14 | vector v(S.begin(), S.end()); 15 | fun(v, 0, S.size()-1, ""); 16 | return ans; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Binary Trees/40. Sum Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int ans = 1; 5 | int fun(Node* root){ 6 | if(!root)return 0; 7 | int l = fun(root->left); 8 | int r = fun(root->right); 9 | if(root->left and root->right and root->data != l + r){ 10 | ans = 0; 11 | } 12 | return l + r + root->data; 13 | 14 | } 15 | bool isSumTree(Node* root) 16 | { 17 | // Your code here 18 | if(!root)return true; 19 | fun(root); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Bit Manipulation/12. Single Number 3.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector & nums) { 4 | long int tmp = 0; 5 | vector v(2); 6 | for(auto x:nums)tmp ^= x; 7 | long int last = tmp & -tmp; //for getting last digit 8 | for(auto x:nums) 9 | { 10 | if(last & x) 11 | { 12 | v[0] ^= x; 13 | } 14 | else 15 | { 16 | v[1] ^= x; 17 | } 18 | } 19 | return v; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Linked list/12. Middle of LL.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* middleNode(ListNode* head) { 4 | ListNode* h = new ListNode(0),*ans = h; 5 | ListNode* slow = head,*fast = head; 6 | while(fast && fast->next) 7 | { 8 | slow=slow->next; 9 | fast=fast->next->next; 10 | } 11 | while(slow) 12 | { 13 | ans->next=new ListNode(slow->val); 14 | ans=ans->next; 15 | slow=slow->next; 16 | } 17 | return h->next; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Matrix/13. Compute Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector > computeBeforeMatrix(int N, int M, vector > after){ 4 | // Code here 5 | for(int i = N-1; i >= 1; i--){ 6 | for(int j = M-1; j >= 1; j--){ 7 | after[i][j] -= (after[i-1][j] + after[i][j-1] - after[i-1][j-1]); 8 | } 9 | } 10 | for(int i = N-1; i >= 1; i--)after[i][0] -= after[i-1][0]; 11 | for(int i = M-1; i >= 1; i--)after[0][i] -= after[0][i-1]; 12 | return after; 13 | 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Matrix/7. Rotate 90.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector >& matrix) { 4 | int n=matrix.size(),i,j,t=0; 5 | for(i=0;i &m) 2 | { 3 | if(!root)return false; 4 | if(inorder(root->left,target,m))return true; 5 | if(m.find(target-root->data) != m.end())return true; 6 | else m.insert(root->data); 7 | return inorder(root->right,target,m); 8 | } 9 | int isPairPresent(struct Node *root, int target) 10 | { 11 | //add code here. 12 | unordered_set m; 13 | return inorder(root,target,m); 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Greedy/17. Partition labels.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector partitionLabels(string s) { 4 | vector v(26,0); 5 | vector ans; 6 | for(int i = 0; i < s.size(); i++){ 7 | v[s[i] - 'a'] = i; 8 | } 9 | int maxi = 0, prev = -1; 10 | for(int i = 0; i < s.size(); i++){ 11 | maxi = max(maxi, v[s[i] - 'a']); 12 | if(maxi == i){ 13 | ans.push_back(maxi-prev); 14 | prev = maxi; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Linked list/10. Intersection of 2 sorted LL.cpp: -------------------------------------------------------------------------------- 1 | Node* findIntersection(Node* head1, Node* head2) 2 | { 3 | // Your Code Here 4 | Node *head=new Node(0); 5 | Node *ans=head; 6 | while(head1&&head2) 7 | { 8 | if(head1->data==head2->data){ 9 | ans->next=new Node(head2->data); 10 | ans=ans->next; 11 | head1=head1->next; 12 | head2=head2->next; 13 | } 14 | else if(head1->data data)head1=head1->next; 15 | else head2=head2->next; 16 | } 17 | return head->next; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Greedy/19. Two City Scheduling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int twoCitySchedCost(vector >& costs) { 4 | int min_cost = 0; 5 | vector difference; 6 | for(int i = 0; i < costs.size(); i++){ 7 | min_cost += costs[i][0]; 8 | difference.push_back(costs[i][1] - costs[i][0]); 9 | } 10 | sort(difference.begin(), difference.end()); 11 | for(int i = 0; i < costs.size() / 2; i++){ 12 | min_cost += difference[i]; 13 | } 14 | 15 | return min_cost; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Greedy/9. Gas Station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int canCompleteCircuit(vector & gas, vector & cost) { 5 | int sum_gas = 0,sum_cost = 0,sum = 0,ans = 0; 6 | for(int i = 0; i < gas.size(); i++) 7 | { 8 | sum_gas += gas[i]; 9 | sum_cost += cost[i]; 10 | sum += gas[i]-cost[i]; 11 | if(sum < 0) 12 | { 13 | ans = i+1; 14 | sum = 0; 15 | } 16 | } 17 | return sum_gas < ssum_cost?-1:ans; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Searching Sorting/24. H-index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector & citations) { 4 | sort(citations.begin(),citations.end()); 5 | int n = citations.size(); 6 | int h = citations.size(),l = 0; 7 | while(l <= h) 8 | { 9 | int m =(l+h)/2; 10 | int index = n - (lower_bound(citations.begin(),citations.end(),m)- citations.begin()); 11 | if(index == m)return m; 12 | else if(index < m)h = m - 1; 13 | else l = m + 1; 14 | } 15 | return h; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Sliding Window/4. Count anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int search(string pat, string txt) { 4 | // code here 5 | int m = txt.size(),n = pat.size(); 6 | vector mp(26, 0),mt(26, 0); 7 | for(int i = 0; i < n; i++) 8 | { 9 | mt[txt[i]-'a']++; 10 | mp[pat[i]-'a']++; 11 | } 12 | int c = 0; 13 | if(mt == mp)c++; 14 | for(int i = n; i < m; i++) 15 | { 16 | mt[txt[i]-'a']++; 17 | mt[txt[i-n]-'a']--; 18 | if(mt == mp)c++; 19 | } 20 | return c; 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /Bit Manipulation/1. Num of 1's.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution { 6 | public: 7 | int setBits(int N) { 8 | // Write Your Code here 9 | bitset<32>b(N); 10 | return b.count(); 11 | } 12 | }; 13 | 14 | // { Driver Code Starts. 15 | int main() { 16 | int t; 17 | cin >> t; 18 | while (t--) { 19 | int N; 20 | cin >> N; 21 | 22 | Solution ob; 23 | int cnt = ob.setBits(N); 24 | cout << cnt << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Greedy/14. Max sum of increasing order.cpp: -------------------------------------------------------------------------------- 1 | int maximumSum( int n,int m, vector > &a) { 2 | 3 | // Complete the function 4 | int mini, ans = 0, maxi = INT_MAX; 5 | for(int i = n-1; i >=0; i--) 6 | { 7 | mini = INT_MIN; 8 | for(int j = 0; j < m; j++) 9 | { 10 | if(a[i][j] > mini and a[i][j] < maxi) 11 | { 12 | mini = a[i][j]; 13 | } 14 | } 15 | if(mini == INT_MIN)return 0; 16 | ans += mini; 17 | maxi = mini; 18 | } 19 | return ans; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Array/SubArray_ques/65. longest subarray with sum divisible by k.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int longSubarrWthSumDivByK(int arr[], int n, int k) 4 | { 5 | // Complete the function 6 | unordered_map m; 7 | int ans = 0, sum = 0; 8 | m[0] = -1; //first element 9 | for(int i = 0; i < n; i++){ 10 | sum += arr[i]; 11 | int tmp = ((sum%k)+k)%k; //if sum is negative; 12 | if(tmp == 0)ans++; 13 | if(m.find(tmp) != m.end())ans = max(ans, i - m[tmp]); 14 | else m[tmp] = i; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BackTracking/Combination models/2_4. Combination sum 4.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int combinationSum4(vector & nums, int target) { 4 | int m = target; 5 | int n = nums.size(); 6 | vector dp(m+1,0); 7 | dp[0] = 1; 8 | for(int i = 1; i <= m; i++) 9 | { 10 | for(int j = 0; j < n; j++) 11 | { 12 | if(i >= nums[j]) 13 | { 14 | dp[i] += dp[i-nums[j]]; 15 | } 16 | } 17 | } 18 | return dp[m]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Mathematical/23. Smallest Positive Integer that cannot be represented as Sum.cpp: -------------------------------------------------------------------------------- 1 | //arr={1,1,1) ans=4 2 | //arr={1,3,4,6,7} ans=2 3 | 4 | class Solution 5 | { 6 | public: 7 | long long smallestpositive(vector array, int n) 8 | { 9 | // code here 10 | sort(array.begin(),array.end()); 11 | long long ans=1; 12 | //if array[i]>ans then it won't possible bcz it is increasing 13 | for(int i=0;i >adj1, adj2; 7 | for(int i = 0; i < 2*e; i += 2){ 8 | adj1[A[i]].push_back(A[i+1]); 9 | adj2[B[i]].insert(adj2[B[i]].begin(), B[i+1]); 10 | } 11 | 12 | if(adj1.size() != adj2.size())return 0; 13 | for(auto x: adj1){ 14 | if(x.second != adj2[x.first])return 0; 15 | } 16 | return 1; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Mathematical/22. Factorial values of array.cpp: -------------------------------------------------------------------------------- 1 | //A[] = {0, 1, 2, 3, 4} 2 | // 1 1 2 6 24 3 | 4 | // A[] = {5, 6, 3} 5 | // 120 720 6 6 | class Solution{ 7 | public: 8 | vector factorial(vector a, int n) { 9 | int size=*max_element(a.begin(),a.end()); 10 | vector v(size+1,1); 11 | int i,j,k; 12 | for(i=2;i<=size;i++)v[i]=(i*v[i-1])%1000000007; 13 | for(i=0;i 3 | DFS: If we know the starting point or don't know which point we need to choose 4 | Use dfs for checking all possibilities, such that recursion tree height as base 5 | Use struct for storing multiple components 6 | Keep track of visited node or point 7 | 8 | 9 | 10 | BFS: When source and destination given known or use bfs 11 | use normal queue for equal importance for each step 12 | otherwise use priority queue for un-equal steps based on wgt or cost 13 | Use struct for storing multiple components 14 |15 | -------------------------------------------------------------------------------- /Searching Sorting/15. atleast trailing zeros.cpp: -------------------------------------------------------------------------------- 1 | #include2 | using namespace std; 3 | bool check(int m,int n){ 4 | int c = 0, p = m; 5 | while(p > 0){c += p/5; p /= 5;} 6 | return c >= n; 7 | } 8 | class Solution 9 | { 10 | public: 11 | int findNum(int n) 12 | { 13 | //complete the function here 14 | if(n == 1)return 5; 15 | int l = 0,h = 5*n; 16 | while(l < h){ 17 | int m = (l+h)/2; 18 | if(check(m,n))h = m; 19 | else l = m+1; 20 | } 21 | return l; 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /Sliding Window/5. count distnict elements in each window.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector countDistinct (int A[], int n, int k) 4 | { 5 | //code here. 6 | unordered_map m; 7 | vector v; 8 | if(k > n)return v; 9 | for(int i = 0; i < k; i++)m[A[i]]++; 10 | v.push_back(m.size()); 11 | for(int i = 1; i <= n-k; i++) 12 | { 13 | m[A[i-1]]--; 14 | if(m[A[i-1]] == 0)m.erase(A[i-1]); 15 | m[A[i+k-1]]++; 16 | v.push_back(m.size()); 17 | } 18 | return v; 19 | } 20 | -------------------------------------------------------------------------------- /String/34. Exactly one swap.cpp: -------------------------------------------------------------------------------- 1 | long long countStrings(string S) 2 | { 3 | // code here 4 | long long int ans = 0; 5 | bool duplicate = false; 6 | vector v(26,0); 7 | for(int i = 0; i < S.size(); i++){ 8 | v[S[i] - 'a']++; 9 | if(v[S[i] - 'a'] >= 2)duplicate = true; 10 | } 11 | for(int i = 0; i < S.size(); i++){ 12 | v[S[i] - 'a']--; //for avoiding duplicates 13 | ans += (S.size() - i - 1 - v[S[i] - 'a']); //counting distnict 14 | } 15 | return duplicate? ans + 1: ans; 16 | } 17 | -------------------------------------------------------------------------------- /String/Implementation_based/29.Permutation in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | if(s1.size() > s2.size())return false; 5 | vector m1(26, 0),m2(26, 0); 6 | int n = s1.size(); 7 | for(int i = 0; i < n; i++) 8 | { 9 | m1[s1[i]-'a']++; 10 | m2[s2[i]-'a']++; 11 | } 12 | for(int i = n; i < s2.size(); i++) 13 | { 14 | if(m1 == m2)return true; 15 | m2[s2[i]-'a']++; 16 | m2[s2[i-n]-'a']--; 17 | } 18 | return m1 == m2; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Array/Sum_ques/37. Max sum path.cpp: -------------------------------------------------------------------------------- 1 | int i = 0, j = 0; 2 | long result = 0, s1 = 0, s2 = 0; 3 | while(i < l1 && j < l2) 4 | { 5 | if(A[i] < B[j])s1 += A[i++]; 6 | else if(A[i] > B[j])s2 += B[j++]; 7 | else 8 | { 9 | result += max(s1,s2); 10 | s1 = 0, s2 = 0; 11 | while(i < l1 && j < l2 && A[i] == B[j]) 12 | { 13 | result = result + A[i++]; 14 | j++; 15 | } 16 | } 17 | } 18 | while(i < l1)s1 += A[i++]; 19 | while(j < l2)s2 += B[j++]; 20 | result += max(s1,s2); 21 | -------------------------------------------------------------------------------- /String/37. Minimum characters to be added at front to make it palindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int minChar(String str) { 3 | //Write your code here 4 | int count = 0; 5 | int low = 0; 6 | int high = str.length()-1; 7 | while(low < high){ 8 | if(str.charAt(low) == str.charAt(high)){ 9 | low++; 10 | high--; 11 | } 12 | else{ 13 | count++; 14 | low = 0; 15 | high = str.length()-1-count; 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Array/22. Trapping rainwater.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | //code 5 | int t,n,i,j,w; 6 | cin>>t; 7 | while(t--){ 8 | w = 0; 9 | cin>>n; 10 | vector l(n),r(n),v(n); 11 | for(i=0;i >v[i]; 12 | left[0] = v[0]; 13 | right[n-1] = v[n-1]; 14 | for(i = 1; i < n; i++)left[i] = max(left[i-1], v[i]); 15 | for(i = n-2; i >= 0; i--)right[i] = max(right[i+1], v[i]); 16 | for(i = 0 ; i < n; i++)w += (min(l[i],r[i])-v[i]); 17 | cout< >ans; 4 | vector v; 5 | void fun(int start, int k, int n) 6 | { 7 | if(v.size() == k && n == 0) 8 | { 9 | ans.push_back(v); 10 | return; 11 | } 12 | for(int i = start; i < 10; i++) 13 | { 14 | v.push_back(i); 15 | fun(i+1, k, n-i); 16 | v.pop_back(); 17 | } 18 | } 19 | vector > combinationSum3(int k, int n) { 20 | fun(1,k,n); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Binary Trees/20. Right side view of BT.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rightSideView(TreeNode* root) { 4 | vector v; 5 | if(!root)return v; 6 | queue q; 7 | q.push(root); 8 | while(!q.empty()){ 9 | int n = q.size(); 10 | TreeNode* t; 11 | while(n--){ 12 | t = q.front(); 13 | q.pop(); 14 | if(t->left)q.push(t->left); 15 | if(t->right)q.push(t->right); 16 | } 17 | v.push_back(t->val); 18 | } 19 | return v; 20 | } 21 | -------------------------------------------------------------------------------- /Mathematical/30. Count Number with Unique Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int counterhelp(int n) 4 | { 5 | int ans = 9; 6 | int choices = 9; 7 | for(int i = 2;i <= n; i++) 8 | { 9 | ans = ans * choices; 10 | choices--; 11 | } 12 | return ans; 13 | } 14 | int countNumbersWithUniqueDigits(int n) { 15 | 16 | if(n == 0)return 1; 17 | int ans = 10; 18 | for(int i = 2; i <= n;i++) 19 | { 20 | ans = ans + counterhelp(i); 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Array/SubArray_ques/16. Max product subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | // Function to find maximum product subarray 6 | long long maxProduct(int *arr, int n) { 7 | // code here 8 | long long int i,ans,mn,mx; 9 | mn = mx = ans = arr[0]; 10 | for(i = 1; i < n; i++){ 11 | if(arr[i] < 0)swap(mn, mx); //this is imp line and nice lagikkk 12 | mx = max (arr[i]*mx, arr[i]); 13 | mn = min (arr[i]*mn, arr[i]); 14 | ans = max(ans, mx); 15 | } 16 | return ans; 17 | } 18 | }; 19 | 20 | -------------------------------------------------------------------------------- /Array/Sum_ques/Triplet_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | bool find3Numbers(int A[], int n, int X) 6 | { 7 | //Your Code Here 8 | int i = 0, j, k; 9 | sort(A, A+n); 10 | while(i < n-2) 11 | { 12 | j = i + 1; 13 | k = n - 1; 14 | while(j < k) 15 | { 16 | if(A[i] + A[j] + A[k] == X)return true; 17 | else if(A[i] + A[j] + A[k] < X)j++; 18 | else k--; 19 | } 20 | i++; 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Dynamic_programming/29. Champagne Tower.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double champagneTower(int poured, int query_row, int query_glass) { 4 | double dp[101][101] = {0.0}; 5 | dp[0][0] = poured; 6 | for(int i = 0; i < 100; i++){ 7 | for(int j = 0; j <= i; j++){ 8 | if(dp[i][j] >= 1){ 9 | dp[i+1][j] += (dp[i][j] - 1) / 2.0; //left 10 | dp[i+1][j+1] += (dp[i][j] - 1) / 2.0; 11 | dp[i][j] = 1; 12 | } 13 | } 14 | } 15 | return dp[query_row][query_glass]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Heap/1. Merge two binary max heap.cpp: -------------------------------------------------------------------------------- 1 | void max_heapify(vector & v) 2 | { 3 | int child = v.size() - 1; 4 | while (child != 0) 5 | { 6 | int parent = (child-1)/2; 7 | if(v[parent] < v[child])swap(v[parent], v[child]); 8 | else break; 9 | child = parent; 10 | } 11 | } 12 | vector mergeHeaps(vector &a, vector &b, int n, int m) { 13 | // your code here 14 | for(auto x:b) 15 | { 16 | a.push_back(x); 17 | max_heapify(a); 18 | } 19 | return a; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/61. Sequential Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sequentialDigits(int low, int high) { 4 | vector v; 5 | string s = "123456789"; 6 | int len = to_string(low).size(); 7 | int size = to_string(high).size(); 8 | while(len <= size) 9 | { 10 | for(int i = 0; i < 10-len; i++) 11 | { 12 | string tmp = s.substr(i,len); 13 | int val = stoi(tmp); 14 | if(val >= low && val <= high)v.push_back(val); 15 | } 16 | len++; 17 | } 18 | return v; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /BackTracking/3. generate parenthesis.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void generate(vector &ans,string tmp,int open,int close) 4 | { 5 | if(open == 0 && close == 0) 6 | { 7 | ans.push_back(tmp); 8 | return; 9 | } 10 | else 11 | { 12 | if(open)generate(ans,tmp+'(',open-1,close+1); 13 | if(close)generate(ans,tmp+')',open,close-1); 14 | } 15 | } 16 | vector generateParenthesis(int n) { 17 | vector ans; 18 | string tmp; 19 | generate(ans,tmp,n,0); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Bit Manipulation/6. Position of 1st set bit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution { 6 | public: 7 | int findPosition(int N) { 8 | // code here 9 | bitset<32>b(N); 10 | if(b.count()==0||b.count()>1)return -1; 11 | else return b._Find_first()+1; 12 | } 13 | }; 14 | 15 | // { Driver Code Starts. 16 | int main() { 17 | int t; 18 | cin >> t; 19 | while (t--) { 20 | int N; 21 | 22 | cin>>N; 23 | 24 | Solution ob; 25 | cout << ob.findPosition(N) << endl; 26 | } 27 | return 0; 28 | -------------------------------------------------------------------------------- /Dynamic_programming/7_min_path_sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPathSum(vector >& grid) { 4 | int row = grid.size(); 5 | int col = grid[0].size(); 6 | for(int i = 1; i < col; i++)grid[0][i] += grid[0][i-1]; //filing 1st row 7 | for(int i = 1; i < row; i++)grid[i][0] += grid[i-1][0]; //filing 1st col 8 | for(int i = 1; i < row; i++) 9 | { 10 | for(int j = 1; j < col; j++) 11 | { 12 | grid[i][j] += min(grid[i-1][j], grid[i][j-1]); 13 | } 14 | } 15 | return grid[row-1][col-1]; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Mathematical/20. Count sum of consecutives.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | N = a + (a+1) + (a+2) + .. + (a+L) 3 | N = (L+1)*a + (L*(L+1))/2 4 | a = (N- L*(L+1)/2)/(L+1) 5 | 6 | We substitute the values of L starting from 1 till L*(L+1)/2 < N 7 | If we get 'a' as a natural number then the solution should be counted. 8 | 9 | */ 10 | class Solution { 11 | public: 12 | int getCount(int N) { 13 | // code here 14 | int c=0,i; 15 | for(i=1;i*(i+1) q; 6 | q.push(root); 7 | int ans; 8 | while(!q.empty()){ 9 | int n = q.size(), k = 0; 10 | while(n--){ 11 | TreeNode* t = q.front(); 12 | q.pop(); 13 | if(k == 0){ans = t->val; k++;} 14 | if(t->left)q.push(t->left); 15 | if(t->right)q.push(t->right); 16 | } 17 | } 18 | return ans; 19 | } 20 | -------------------------------------------------------------------------------- /Sliding Window/8. Smallest window containing 012.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestSubstring(string S) { 4 | // Code here 5 | vector v(3, -1); 6 | int ans = INT_MAX; 7 | for(int i = 0; i < S.size(); i++){ 8 | v[S[i] - '0'] = i; 9 | if(v[0] != -1 and v[1] != -1 and v[2] != -1){ 10 | int last_element = max({v[0], v[1], v[2]}); 11 | int first_element = min({v[0], v[1], v[2]}); 12 | ans = min(ans, last_element - first_element + 1); 13 | } 14 | } 15 | return ans == INT_MAX ? -1: ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/25. Next Highest Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | string nextPalin(string N) { 4 | //complete the function here 5 | int n = N.size(); 6 | if(n <= 3) return "-1"; 7 | string half = N.substr(0,n/2); 8 | if( next_permutation( half.begin() , half.end() ) ) 9 | { 10 | string ans = half; 11 | if(n & 1) 12 | { 13 | ans += N[n/2]; 14 | } 15 | reverse(half.begin() , half.end()); 16 | ans += half; 17 | return ans; 18 | } 19 | return "-1"; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Array/63. Non-decreasing array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPossibility(vector & nums) { 4 | int ans = 0, j = INT_MIN; 5 | for(int i = 0; i < nums.size()-1; i++) 6 | { 7 | if(nums[i] <= nums[i+1]) 8 | { 9 | j = nums[i]; 10 | } 11 | else 12 | { 13 | if(nums[i+1] < j) //This is imp line 14 | { 15 | nums[i+1] = nums[i]; 16 | } 17 | ans++; 18 | if(ans > 1)return false; 19 | } 20 | } 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Mathematical/33. Pair of Songs with duration divisible by 60.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numPairsDivisibleBy60(vector & time) { 4 | vector v(61,0); 5 | int ans = 0; 6 | for(int i = 0; i < time.size(); i++) 7 | { 8 | int rem = time[i] % 60; //rem always lies between 0 to 59 9 | if(rem == 0) 10 | ans += v[0]; //if time[i] is multiple of 60 then its compliment is 0 11 | else 12 | ans += v[60-rem]; //else its compliment is 60 -rem 13 | 14 | v[rem]++; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Sliding Window/10. Equivalent sub arrays.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | int countDistinctSubarray(int arr[], int n) 3 | { 4 | //code here. 5 | unordered_set s; 6 | unordered_map m; 7 | for(int i = 0; i < n; i++)s.insert(arr[i]); 8 | int ans = 0, i = 0, j = 0; 9 | while(j < n){ 10 | m[arr[j]]++; 11 | while(i <= j and m.size() == s.size()){ 12 | ans += n-j; 13 | m[arr[i]]--; 14 | if(m[arr[i]] == 0)m.erase(arr[i]); 15 | i++; 16 | } 17 | j++; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Binary Trees/Paths Models/12. Path sum 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void fun(TreeNode* root,int k,vector &v, vector >&v1) 4 | { 5 | if(!root)return; 6 | k -= root->val; 7 | v.push_back(root->val); 8 | if(!root->left && !root->right && k == 0)v1.push_back(v); 9 | fun(root->left,k,v,v1); 10 | fun(root->right,k,v,v1); 11 | v.pop_back(); 12 | } 13 | vector > pathSum(TreeNode* root, int targetSum) { 14 | vector >v1; 15 | vector v; 16 | if(!root)return v1; 17 | fun(root,targetSum,v,v1); 18 | return v1; 19 | } 20 | -------------------------------------------------------------------------------- /Dynamic_programming/19. Longest Repeated Subsequence.cpp: -------------------------------------------------------------------------------- 1 | int LongestRepeatingSubsequence(string str){ 2 | // Code here 3 | int n = str.size(); 4 | vector >dp(n+1, vector (n+1,0)); 5 | for(int i = 1; i <= n; i++) 6 | { 7 | for(int j = 1; j <= n; j++) 8 | { 9 | if(str[i-1] == str[j-1] && i != j) 10 | { 11 | dp[i][j] = 1 + dp[i-1][j-1]; 12 | } 13 | else 14 | { 15 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 16 | } 17 | } 18 | } 19 | return dp[n][n]; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Greedy/20. Activity selection.cpp: -------------------------------------------------------------------------------- 1 | 2 | int activitySelection(vector start, vector end, int n) 3 | { 4 | // Your code here 5 | vector >v; 6 | for(int i = 0; i < n; i++) 7 | { 8 | v.push_back({end[i], start[i]}); 9 | } 10 | 11 | sort(v.begin(), v.end()); 12 | int count = 1, j = 0, i = 1; 13 | while(i < n) 14 | { 15 | if(v[i].second > v[j].first) 16 | { 17 | count++; 18 | j = i; 19 | } 20 | i++; 21 | } 22 | return count; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Linked list/28. Remove duplicates from sortedlist 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteDuplicates(ListNode* head) { 4 | ListNode* dum=new ListNode(0,head); //it is always better to have a prev node while removing or dng any operations 5 | ListNode* prev=dum; 6 | while(head){ 7 | if(head->next&&head->val==head->next->val){ 8 | while(head->next&&head->val==head->next->val)head=head->next; 9 | prev->next=head->next;} 10 | else prev=prev->next; 11 | head=head->next; 12 | } 13 | 14 | return dum->next; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Mathematical/16. Final destination.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution { 6 | public: 7 | int canReach(long long a, long long b, long long x) { 8 | // code here 9 | int i=x-abs(a)-abs(b); 10 | if(i<0)return 0; 11 | return i%2==0; 12 | 13 | } 14 | }; 15 | 16 | // { Driver Code Starts. 17 | int main() { 18 | int t; 19 | cin >> t; 20 | while (t--) { 21 | long long a,b,x; 22 | 23 | cin>>a>>b>>x; 24 | 25 | Solution ob; 26 | cout << ob.canReach(a,b,x) << endl; 27 | } 28 | return 0; 29 | -------------------------------------------------------------------------------- /Array/SubArray_ques/33. Subarray with equal 0s and 1s.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | //Function to count subarrays with 1s and 0s. 6 | long long int countSubarrWithEqualZeroAndOne(int arr[], int n) 7 | { 8 | //Your code here 9 | long long int c = 0; 10 | int i, j ,s = 0; 11 | unordered_map m; 12 | for(i = 0; i < n; i++){ 13 | if(arr[i] == 0)arr[i] = -1; 14 | s += arr[i]; 15 | if(s == 0)c++; 16 | if(m[s])c += m[s]; 17 | m[s]++; 18 | } 19 | return c; 20 | } 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /Samsung R & D/SwC-Pro-main/millitary_base_nodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | each node of the tree represents a military unit. We are given the no. of soldiers in each unit. 3 | we need to balance the tree such that 4 | all nodes belonging to the same parent node have the same subtree sum 5 | we can only balance by deleting some soldiers from a node 6 | we should remove the minimum no. of soldiers(total) 7 | return the no. of soldiers total after balancing 8 | 9 | constraints: 10 | N<=500 11 | node.val<=100 12 | depth<=100 13 | input form:(for each of the n nodes) 14 | parent index, soldiers in that unit 15 | */ 16 | -------------------------------------------------------------------------------- /Mathematical/22_1. Factorial of largenum.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | int multiply(int x,int *a,int size){ 3 | int c=0,i,p; 4 | for(i=0;i >t; 21 | while(t--){ 22 | size=1; 23 | a[0]=1; 24 | cin>>n; 25 | for(x=2;x<=n;x++)size=multiply(x,a,size); 26 | for(x=size-1;x>=0;x--)cout<>&matrix){ 2 | // Code here 3 | int m = matrix.size(); 4 | int n = matrix[0].size(); 5 | for(int i = m-2; i >= 0; i--){ 6 | for(int j = 0; j < n; j++){ 7 | int down = matrix[i+1][j]; 8 | int right_diag = (j == n-1)? 0: matrix[i+1][j+1]; 9 | int left_diag = (j == 0)? 0: matrix[i+1][j-1]; 10 | if(matrix[i][j] != -1)matrix[i][j] = matrix[i][j] + max({down, left_diag, right_diag, 0}); //this case of adding -1 for all 3 possibilities 11 | } 12 | } 13 | return max(0, *max_element(matrix[0].begin(), matrix[0].end())); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Greedy/4. min no of coins.c: -------------------------------------------------------------------------------- 1 | // C program to find minimum 2 | // number of denominations 3 | #include 4 | #define COINS 9 5 | #define MAX 20 6 | 7 | // All denominations of Indian Currency 8 | int coins[COINS] = { 1, 2, 5, 10, 20, 9 | 50, 100, 200, 2000 }; 10 | 11 | void findMin(int cost) 12 | { 13 | int coinList[MAX] = { 0 }; 14 | int i, k = 0; 15 | 16 | for (i = COINS - 1; i >= 0; i--) { 17 | while (cost >= coins[i]) { 18 | cost -= coins[i]; 19 | // Add coin in the list 20 | coinList[k++] = coins[i]; 21 | } 22 | } 23 | 24 | for (i = 0; i < k; i++) { 25 | // Print 26 | printf("%d ", coinList[i]); 27 | } 28 | return; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Mathematical/11. Repetative Addition of digits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | //User function Template for C++ 6 | class Solution 7 | { 8 | public: 9 | int singleDigit(long long N) 10 | { 11 | // Write Your Code here 12 | if(N%9==0)return 9; 13 | else return N%9; 14 | } 15 | }; 16 | 17 | // { Driver Code Starts. 18 | int main() 19 | { 20 | int t; 21 | cin >> t; 22 | while (t--) 23 | { 24 | long long N; 25 | cin>>N; 26 | Solution ob; 27 | int ans = ob.singleDigit(N); 28 | cout< > n >> X; 5 | X = abs(X); 6 | int in; 7 | unordered_set s; 8 | vector a(n); 9 | for(int i = 0; i < n; i++){ 10 | cin >> a[i]; 11 | s.insert(a[i]); 12 | } 13 | for(int i = 0; i< n; i++){ 14 | 15 | if(s.find(a[i] + X) != s.end()){ 16 | cout << "1\n"; 17 | return; 18 | } 19 | } 20 | cout << "-1\n"; 21 | 22 | } 23 | int main() { 24 | //code 25 | int t; 26 | cin >>t; 27 | while(t--) 28 | solve(); 29 | return 0; 30 | -------------------------------------------------------------------------------- /Stack/10. Insert at end of stack.cpp: -------------------------------------------------------------------------------- 1 | static void insert_at_bottom(char x){ 2 | 3 | if(st.isEmpty()) 4 | st.push(x); 5 | 6 | else{ 7 | /* All items are held in Function Call Stack until we 8 | reach end of the stack. When the stack becomes 9 | empty, the st.size() becomes 0, the 10 | above if part is executed and the item is inserted 11 | at the bottom */ 12 | 13 | char a = st.peek(); 14 | st.pop(); 15 | insert_at_bottom(x); 16 | 17 | //push all the items held in Function Call Stack 18 | //once the item is inserted at the bottom 19 | st.push(a); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /String/35. Transform string.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | int transform (string A, string B) 3 | { 4 | //code here. 5 | if(A.size() != B.size())return -1; 6 | int sum = 0; 7 | for(int i = 0; i < A.size(); i++){ 8 | sum += A[i] - B[i]; 9 | } 10 | if(sum != 0)return -1; 11 | int i = A.size()-1, j = B.size()-1, count = 0; 12 | while(i >= 0 and j >= 0){ 13 | if(A[i] == B[j]){ 14 | i--; 15 | j--; 16 | } 17 | else{ 18 | count++; 19 | i--; 20 | } 21 | } 22 | return count; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Mathematical/39. Max points in a line.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPoints(vector >& points) { 4 | int n = points.size(); 5 | int ans = 1; 6 | for(int i = 0; i < n; i++){ 7 | unordered_map m; 8 | for(int j = 0; j < n; j++){ 9 | if(i != j){ 10 | double inv_slpe = (double)(points[j][0]-points[i][0])/(points[j][1]-points[i][1]); 11 | double slpe = atan(inv_slpe); 12 | m[slpe]++; 13 | ans = max(ans, m[slpe]+1); 14 | } 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Binary Trees/28. BT from postorder inorder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_map m; 4 | int i; 5 | TreeNode* cost(vector &post,int l,int h){ 6 | if(l > h || i < 0)return NULL; 7 | int x = post[--i]; 8 | TreeNode* root=new TreeNode(x); 9 | int p = m[x]; 10 | root->right = cost(post, p+1, h); 11 | root->left = cost(post, l, p-1); 12 | return root; 13 | } 14 | TreeNode* buildTree(vector & inorder, vector & postorder) { 15 | for(i = 0; i < inorder.size(); i++)m[inorder[i]] = i; 16 | TreeNode* root = cost(postorder, 0, inorder.size()-1); 17 | return root; 18 | } 19 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/23. Find largest value in each row.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector largestValues(TreeNode* root) { 4 | vector v; 5 | if(!root)return v; 6 | queue q; 7 | q.push(root); 8 | while(!q.empty()){ 9 | int n = q.size(); 10 | int s = INT_MIN; 11 | while(n--){ 12 | TreeNode* t = q.front(); 13 | q.pop(); 14 | s = max(s, t->val); 15 | if(t->left)q.push(t->left); 16 | if(t->right)q.push(t->right); 17 | } 18 | v.push_back(s); 19 | } 20 | return v; 21 | } 22 | -------------------------------------------------------------------------------- /String/Direct_logic_based/2. Repeated string match.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Input: A = "abcd", B = "cdabcdab" 3 | Output: 3 4 | Explanation: After repeating A three times, 5 | we get "abcdabcdabcd". 6 | 7 | Input: A = "aa", B = "a" 8 | Output: 1 9 | Explanation: B is already a substring of A. 10 | 11 | A="orpjir" 12 | B="jirorpjirorpjirorpjirorpjirorpjirorpjirorpjiror" 13 | Output: 9 14 | 15 | Time Complexity: O(A*B) for checking matchers 16 | Space : O(1) 17 | */ 18 | 19 | int repeatedStringMatch(string A, string B) 20 | { 21 | int c = 1; 22 | string s = A; 23 | while(A.find(B) == string::npos && A.size() <= B.size()+s.size()){ A += s; c++;} 24 | if(A.find(B) != string::npos)return c; 25 | return -1; 26 | } 27 | 28 | -------------------------------------------------------------------------------- /String/Implementation_based/17. concatenation of zigzag strings in a row.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | string convert(string s, int n) { 4 | //code 5 | if(n <= 1)return s; //base condition 6 | vector v(n); 7 | string ans,tmp; 8 | int count = 0; 9 | for(int i=0;i m; 4 | int i = 0; 5 | TreeNode* cost(vector &pre,int l, int h){ 6 | if(l > h)return NULL; 7 | int x = pre[i]; 8 | TreeNode* root = new TreeNode(x); 9 | i++; 10 | int p = m[x]; 11 | root->left = cost(pre, l, p-1); 12 | root->right = cost(pre, p+1, h); 13 | return root; 14 | } 15 | TreeNode* buildTree(vector & preorder, vector & inorder) { 16 | for(int i = 0; i < inorder.size(); i++)m[inorder[i]] = i; 17 | TreeNode* root=cost(preorder,0,inorder.size()-1); 18 | return root; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic_programming/32. Form Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int findMinInsertions(string S){ 4 | // code here 5 | int n = S.size(); 6 | string P = S; 7 | reverse(P.begin(), P.end()); 8 | vector >dp(n+1, vector (n+1, 0)); 9 | for(int i = 1; i <= n; i++){ 10 | for(int j = 1; j <= n; j++){ 11 | if(S[i-1] == P[j-1]){ 12 | dp[i][j] = 1 + dp[i-1][j-1]; 13 | } 14 | else{ 15 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 16 | } 17 | } 18 | } 19 | return n - dp[n][n]; 20 | } 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /Dynamic_programming/36. Russian Dolls envelopes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool cmp(vector &a, vector &b){ 4 | if(a[0] == b[0])return a[1] > b[1]; 5 | return a[0] < b[0]; 6 | } 7 | int maxEnvelopes(vector >& envelopes) { 8 | sort(envelopes.begin(), envelopes.end(), cmp); 9 | vector dp; 10 | for(int i = 0; i < envelopes.size(); i++){ 11 | int height = envelopes[i][1]; 12 | int index = lower_bound(dp.begin(), dp.end() ,height) - dp.begin(); 13 | if(index == dp.size())dp.push_back(height); 14 | dp[index] = height; 15 | } 16 | return dp.size(); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Greedy/6. N meeting in 1 room.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find the maximum number of meetings that can 5 | //be performed in a meeting room. 6 | int maxMeetings(int start[], int end[], int n) 7 | { 8 | // Your code here 9 | vector >v; 10 | for(int i=0;i tmp,numbers; 4 | vector >ans; 5 | void findcombi(int start, int k, int n) 6 | { 7 | if(tmp.size() == k) 8 | { 9 | ans.push_back(tmp); 10 | return ; 11 | } 12 | for(int i = start; i < n; i++) 13 | { 14 | tmp.push_back(numbers[i]); 15 | findcombi(i+1, k, n); 16 | tmp.pop_back(); 17 | } 18 | } 19 | vector > combine(int n, int k) { 20 | for(int i = 0; i < n; i++)numbers.push_back(i+1); 21 | findcombi(0, k, n); 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Graph/3. DFS of Graph.cpp: -------------------------------------------------------------------------------- 1 | // Function to return a list containing the DFS traversal of the graph. 2 | vector ans; 3 | void DFS(int V, bool visited[], vector adj[]) 4 | { 5 | visited[V] = true; 6 | ans.push_back(V); 7 | 8 | for(auto x: adj[V]) 9 | { 10 | if(!visited[x]) 11 | { 12 | DFS(x, visited, adj); 13 | } 14 | } 15 | } 16 | vector dfsOfGraph(int V, vector adj[]) { 17 | // Code here 18 | bool *visited = new bool[V]; 19 | for(int i = 0; i < V; i++)visited[i] = false; 20 | DFS(0, visited, adj); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Mathematical/10. Finding last most even position.cpp: -------------------------------------------------------------------------------- 1 | // Initial Template for C++ 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | // User function Template for C++ 7 | class Solution { 8 | public: 9 | long long int nthPosition(long long int n){ 10 | // code here 11 | int c=0; 12 | while(n>0){n/=2; c++;} 13 | return pow(2,c-1); 14 | 15 | } 16 | }; 17 | 18 | // { Driver Code Starts. 19 | int main() { 20 | int t; 21 | cin >> t; 22 | while (t--) { 23 | long long int n; 24 | cin >> n; 25 | Solution ob; 26 | cout< >& trips, int capacity) { 4 | vector curr_capacity(1001, 0); 5 | int max_destination = INT_MIN; 6 | for(int i = 0; i < trips.size(); i++){ 7 | curr_capacity[trips[i][1]] += trips[i][0]; 8 | curr_capacity[trips[i][2]] -= trips[i][0]; 9 | max_destination = max(max_destination, trips[i][2]); 10 | } 11 | int prefix_sum = 0; 12 | for(int i = 0; i <= max_destination; i++){ 13 | prefix_sum += curr_capacity[i]; 14 | if(prefix_sum > capacity)return false; 15 | } 16 | return true; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Searching Sorting/26. Koko Eating Bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int check(vector &v, int k) 4 | { 5 | int count = 0; 6 | for(auto x: v) 7 | { 8 | count += x / k + (x % k != 0); 9 | } 10 | return count; 11 | } 12 | int minEatingSpeed(vector & piles, int h) { 13 | int low = 1; 14 | int high = *max_element(piles.begin(), piles.end()); 15 | while(low < high) 16 | { 17 | int m = (low + high)/2; 18 | int hrs = check(piles,m); 19 | if(hrs > h)low = m + 1; 20 | else high = m; 21 | } 22 | return high; 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Searching Sorting/Easy ques/Farthest number.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector farNumber(int N,vector Arr){ 4 | //code here 5 | vector suffix_min(N), result; 6 | suffix_min[N-1]; 7 | suffix_min[N-1] = Arr[N-1]; 8 | for(int i = N-2; i >= 0; i--){ 9 | suffix_min[i] = min(suffix_min[i+1], Arr[i]); 10 | } 11 | for(int i = 0; i < N; i++){ 12 | int ans; 13 | auto x = lower_bound(suffix_min.begin()+i+1, suffix_min.end(), Arr[i]) - suffix_min.begin() - 1; 14 | if(x == i)result.push_back(-1); 15 | else result.push_back(x); 16 | } 17 | return result; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Searching Sorting/Easy ques/count_triplets_less_than_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | long long countTriplets(long long arr[], int n, long long sum) 6 | { 7 | // Your code goes here 8 | int i, j, k,c = 0; 9 | sort(arr, arr+n); 10 | for(i = 0; i < n-2; i++){ 11 | j = i+1; 12 | k = n-1; 13 | while(j < k){ 14 | if(arr[i] + arr[j] + arr[k] >= sum)k--; 15 | else{ 16 | c += (k-j); //this part is imp try to make all possible nums soo its like that 17 | j++; 18 | } 19 | } 20 | } 21 | return c; 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /Graph/16. Bipartite graph.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 0 - not colored 3 | 1 - blue 4 | -1 - red 5 | */ 6 | bool validcolor(vector adj[], int src, int c, vector &color){ 7 | if(color[src] != 0){ 8 | return color[src] == c; 9 | } 10 | color[src] = c; 11 | for(auto x: adj[src]){ 12 | if(!validcolor(adj, x, -c, color))return false; 13 | } 14 | return true; 15 | } 16 | bool isBipartite(int V, vector adj[]){ 17 | // Code here 18 | vector color(V, 0); 19 | for(int i = 0; i < V; i++){ 20 | if(color[i] == 0 && !validcolor(adj, i, 1, color))return false; 21 | } 22 | return true; 23 | } 24 | 25 | }; 26 | -------------------------------------------------------------------------------- /Mathematical/37. Grouping of numbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int maxGroupSize(int[] arr, int N, int K) { 3 | // code here 4 | int[] remainder = new int[K]; 5 | for(int i = 0; i < N; i++){ 6 | remainder[arr[i] % K]++; 7 | } 8 | int low = 1, high = K-1, ans = 0; 9 | while(low < high){ 10 | ans += Math.max(remainder[low], remainder[high]); 11 | low++; 12 | high--; 13 | } 14 | if(low == high && remainder[low] > 0)ans++; // i == k - i case both are equal case we need to consider only one 15 | if(remainder[0] > 0)ans++; // if both elements divisible by K case 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Graph/6. Mother Vertex.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find a Mother Vertex in the Graph. 5 | void dfs(int i, vector adj[], int &count, vector &visited){ 6 | visited[i] = 1; 7 | count++; 8 | for(auto x: adj[i]){ 9 | if(!visited[x]){ 10 | dfs(x, adj, count, visited); 11 | } 12 | } 13 | } 14 | int findMotherVertex(int V, vector adj[]) 15 | { 16 | // Code here 17 | for(int i = 0; i < V; i++){ 18 | int count = 0; 19 | vector visited(V,0); 20 | dfs(i, adj, count, visited); 21 | if(count == V)return i; 22 | } 23 | return -1; 24 | } 25 | 26 | }; 27 | -------------------------------------------------------------------------------- /Prefix_Suffix/Conceptual Ques/4. Best Sight Seeing Pair.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxScoreSightseeingPair(vector & values) { 4 | /*first need to arrange the format of formula*/ 5 | int n = values.size(); 6 | vector sfx(n); 7 | /*getting the right part with max value in linear time we need smax_suffix array*/ 8 | sfx[n-1] = values[n-1] - (n-1); 9 | for(int i = n-2; i >= 0; i--){ 10 | sfx[i] = max(values[i]-i, sfx[i+1]); 11 | } 12 | int ans = INT_MIN; 13 | /*Check the values*/ 14 | for(int i = 0; i < n-1; i++){ 15 | ans = max(ans, values[i]+i+sfx[i+1]); 16 | } 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /Binary Trees/49. Maximum sum of Non-adjacent Nodes.cpp: -------------------------------------------------------------------------------- 1 | //Function to return the maximum sum of non-adjacent nodes. 2 | pair fun(Node* root) 3 | { 4 | if(!root)return {0,0}; 5 | pair sum1 = fun(root->left); 6 | pair sum2 = fun(root->right); 7 | pair ans; 8 | ans.first = root->data + sum1.second + sum2.second; //If this root included its childrens are not 9 | ans.second = max(sum1.first, sum1.second) + max(sum2.first, sum2.second); 10 | return ans; 11 | 12 | } 13 | int getMaxSum(Node *root) 14 | { 15 | // Add your code here 16 | auto x = fun(root); 17 | return max(x.first, x.second); 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic_programming/28. Delete operations for 2 string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | vector >dp(word1.size()+1, vector (word2.size() + 1, 0)); 5 | for(int i = 1; i <= word1.size(); i++) 6 | { 7 | for(int j = 1; j <= word2.size(); j++) 8 | { 9 | if(word1[i-1] == word2[j-1]){ 10 | dp[i][j] = 1 + dp[i-1][j-1]; 11 | } 12 | else{ 13 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 14 | } 15 | } 16 | } 17 | return word1.size() + word2.size() - 2*dp[word1.size()][word2.size()]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/19. Populating next right pointer in each node.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* connect(Node* root) { 4 | if(!root)return root; 5 | queue q; 6 | q.push(root); 7 | q.push(NULL); 8 | while(q.front()) 9 | { 10 | int s = q.size()-1; 11 | while(s--) 12 | { 13 | Node *node = q.front(); 14 | q.pop(); 15 | node->next = q.front(); 16 | if(node->left)q.push(node->left); 17 | if(node->right)q.push(node->right); 18 | } 19 | q.pop(); 20 | q.push(NULL); 21 | } 22 | return root; 23 | } 24 | -------------------------------------------------------------------------------- /BackTracking/4. Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector >ans; 4 | vector tmp; 5 | void fun(string s) 6 | { 7 | if(s.size()==0) 8 | { 9 | ans.push_back(tmp); 10 | return ; 11 | } 12 | for(int i=0;i > partition(string s) { 24 | fun(s); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Mathematical/14. Check binary is multiple of 3.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | //User function template for C++ 7 | class Solution{ 8 | public: 9 | 10 | int isDivisible(string s){ 11 | //complete the function here 12 | int i,c1=0,c2=0; 13 | for(i=0;i > t; 24 | while(t--){ 25 | string s; 26 | cin >> s; 27 | Solution ob; 28 | cout << ob.isDivisible(s) << endl; 29 | } 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Mathematical/8. faithful num.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | class Solution { 8 | public: 9 | long long nthFaithfulNum(int N) { 10 | // code here 11 | if(N==1) 12 | return 1; 13 | long long int pow = 1, answer = 0; 14 | 15 | while (N>0) 16 | { 17 | 18 | if (N & 1) 19 | answer += pow; 20 | pow = pow*7; 21 | N >>= 1; 22 | } 23 | return answer; 24 | } 25 | }; 26 | 27 | // { Driver Code Starts. 28 | int main() { 29 | int t; 30 | cin >> t; 31 | while (t--) { 32 | int N; 33 | 34 | cin>>N; 35 | 36 | Solution ob; 37 | cout << ob.nthFaithfulNum(N) << endl; 38 | } 39 | return 0; 40 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/7. BT level order.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > levelOrder(TreeNode* root) { 4 | vector >v1; 5 | if(!root)return v1; 6 | queue q; 7 | q.push(root); 8 | while(!q.empty()) 9 | { 10 | int n = q.size(); 11 | vector v; 12 | while(n--) 13 | { 14 | TreeNode* temp=q.front(); 15 | q.pop(); 16 | v.push_back(temp->val); 17 | if(temp->left)q.push(temp->left); 18 | if(temp->right)q.push(temp->right); 19 | } 20 | v1.push_back(v); 21 | } 22 | return v1; 23 | } 24 | -------------------------------------------------------------------------------- /Graph/19. Minimum Spanning tree.cpp: -------------------------------------------------------------------------------- 1 | #define pp pair 2 | int spanningTree(int V, vector > adj[]) 3 | { 4 | // code here 5 | priority_queue ,greater >pq; //we need to remove max weight so min heap 6 | pq.push({0, 0}); 7 | int ans = 0; 8 | vector visited(V, 0); 9 | while(!pq.empty()){ 10 | auto x = pq.top(); 11 | pq.pop(); 12 | int curr = x.second; 13 | int weight = x.first; 14 | if(visited[curr])continue; 15 | ans += weight; 16 | visited[curr] = 1; 17 | for(auto x: adj[curr])pq.push({x[1], x[0]}); 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Linked list/29. Linkedlist cycle 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *detectCycle(ListNode *head) { 4 | if(!head||!head->next)return 0; 5 | ListNode* slow=head,*fast=head->next; 6 | int k=0; 7 | while(1){ 8 | if(!fast||!fast->next||!fast->next->next)return 0; 9 | if(slow==fast){k=1;break;} 10 | slow=slow->next; 11 | fast=fast->next->next; 12 | } 13 | if(k==1){ 14 | slow=slow->next; 15 | fast=head; 16 | while(slow!=fast){ 17 | slow=slow->next; 18 | fast=fast->next; 19 | } 20 | return slow; 21 | } 22 | return NULL; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Mathematical/28.Last digit of a pow b.cpp: -------------------------------------------------------------------------------- 1 | int getLastDigit(string a, string b) { 2 | // code here 3 | if(b=="0")return 1; 4 | unordered_map >mp; 5 | mp.insert({0, {0,0,0,0}}); 6 | mp.insert({1, {1,1,1,1}}); 7 | mp.insert({2, {2,4,8,6}}); 8 | mp.insert({3, {3,9,7,1}}); 9 | mp.insert({4, {4,6,4,6}}); 10 | mp.insert({5, {5,5,5,5}}); 11 | mp.insert({6, {6,6,6,6}}); 12 | mp.insert({7, {7,9,3,1}}); 13 | mp.insert({8, {8,4,2,6}}); 14 | mp.insert({9, {9,1,9,1}}); 15 | int base=a.back()-'0'; 16 | int power=stoi(b.size()==1?b:b.substr(b.size()-2,b.size()))%4; 17 | return mp[base][(power==0)?3:power-1]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Searching Sorting/29. Min Swaps to sort.cpp: -------------------------------------------------------------------------------- 1 | { 2 | public: 3 | //Function to find the minimum number of swaps required to sort the array. 4 | int minSwaps(vector