├── 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<left)+countNodes(root->right); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Binary Trees/6. Max depth BT.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(TreeNode* root) { 4 | if(!root)return 0; 5 | int l = maxDepth(root->left); 6 | int r = maxDepth(root->right); 7 | return 1 + max(l,r); 8 | } 9 | -------------------------------------------------------------------------------- /Matrix/Easy ques/Readme.md: -------------------------------------------------------------------------------- 1 | # Approach 2 |
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 2 | using namespace std; 3 | int maxSubarraySum(int arr[], int n){ 4 | int i, sum = 0, ans = 0; 5 | for(i = 0; i < n; i++){ 6 | sum = max(arr[i], sum + arr[i]); 7 | ans = max(sum, ans); 8 | } 9 | return ans; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Array/Easy Ques/Cyclic_rotate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | k = k % nums.size(); 5 | reverse(nums.begin(), nums.end()); 6 | reverse(nums.begin(), nums.begin()+k); 7 | reverse(nums.begin()+k, nums.end()); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Bit Manipulation/14. Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int n) { 4 | vectorans(n+1); 5 | ans[0] = 0; 6 | for(int i = 1; i <= n; i++){ 7 | ans[i] = ans[i / 2] + i % 2; 8 | } 9 | return ans; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Binary Trees/4. Same tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSameTree(TreeNode* p, TreeNode* q) { 4 | if(!p && !q)return true; 5 | if(!p || !q)return false; 6 | if(p->val != q->val)return false; 7 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 8 | } 9 | -------------------------------------------------------------------------------- /Trie/README.md: -------------------------------------------------------------------------------- 1 | # All Trie Implementation 2 | How to insert into trie and search implementation Contains Children (for storing char values in nodes) and leaf(checking for end of the string by bool) 3 | 4 | 1.Insert and Search 5 | -------------------------------------------------------------------------------- /Binary Trees/18. Flatten BT to LL.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* r = NULL; 4 | void flatten(TreeNode* root) { 5 | if(!root)return; 6 | flatten(root->right); 7 | flatten(root->left); 8 | root->right = r; 9 | root->left = NULL; 10 | r = root; 11 | } 12 | -------------------------------------------------------------------------------- /Bit Manipulation/11. single number 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int one=0,two=0; 5 | for(auto x:nums) 6 | { 7 | one=(one^x)&(~two); 8 | two=(two^x)&(~one); 9 | } 10 | return one; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic_programming/38. Number of ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | long long int arrangeTiles(int N){ 4 | // code here 5 | vectordp(N+1, 1); 6 | for(int i = 4; i <= N; i++){ 7 | dp[i] = dp[i-1] + dp[i-4]; 8 | } 9 | return dp[N]; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Greedy/1. Jump.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int reach=0,i; 5 | for(i=0;ireach)return false; 7 | else reach=max(reach,i+nums[i]); 8 | } 9 | return reach>=nums.size()-1?:true;false; 10 | } 11 | -------------------------------------------------------------------------------- /Mathematical/19. Next greater num.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nextGreaterElement(int n) { 4 | string s=to_string(n); 5 | if(next_permutation(s.begin(),s.end())){ 6 | if(stoll(s)>pow(2,31)-1)return -1; 7 | return stoi(s); 8 | } 9 | return -1; 10 | } 11 | -------------------------------------------------------------------------------- /Linked list/31. Swapping nodes LL.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* swapNodes(ListNode* head, int k) { 4 | ListNode* i=head,*j=head,*t; 5 | while(--k&&i->next)i=i->next; 6 | t=i; 7 | while(i->next){i=i->next; j=j->next;} 8 | swap(t->val,j->val); 9 | return head; 10 | } 11 | -------------------------------------------------------------------------------- /Mathematical/32. Sum of 2 integers without + and -.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getSum(int a, int b) { 4 | uint carry = a & b; 5 | while(carry) 6 | { 7 | a ^= b; 8 | b = carry << 1; 9 | carry = a & b; 10 | } 11 | return a|b; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Binary Trees/36. Check BST.cpp: -------------------------------------------------------------------------------- 1 | Node* prev=NULL; 2 | bool checkBST(Node* root) { 3 | if(!root)return true; 4 | bool f = checkBST(root->left); 5 | if(!f)return false; 6 | if(prev != NULL && prev->data >= root->data)return false; 7 | prev = root; 8 | f = checkBST(root->right); 9 | if(!f)return false; 10 | return true; 11 | } 12 | -------------------------------------------------------------------------------- /Greedy/18. Smallest string with given numeric value.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getSmallestString(int n, int k) { 4 | string ans(n, 'a'); 5 | k -= n; 6 | while(k > 0){ 7 | ans[--n] += min(25,k); 8 | k -= min(25,k); 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Binary Trees/56. Finding Profession.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | char profession(int level, int pos){ 4 | // code here 5 | bool flip = false; 6 | while(pos != 1){ 7 | if(pos % 2 == 0)flip = !flip; 8 | pos = (pos+1)/2; 9 | } 10 | return flip? 'd': 'e'; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Binary Trees/10. Min depth BT.cpp: -------------------------------------------------------------------------------- 1 | int f(TreeNode* root){ 2 | if(!root)return INT_MAX; 3 | if(!root->left&&!root->right)return 1; 4 | return 1+min(f(root->left),f(root->right)); 5 | } 6 | class Solution { 7 | public: 8 | int minDepth(TreeNode* root) { 9 | if(!root)return 0; 10 | return f(root); 11 | } 12 | -------------------------------------------------------------------------------- /Mathematical/1. finding nth root of M in nlog m.cpp: -------------------------------------------------------------------------------- 1 | int NthRoot(int n, int m) 2 | { 3 | // Code here. 4 | int l=1,h=m; 5 | while(l<=h) 6 | { 7 | int mid=(l+h)/2; 8 | if(pow(mid,n)==m)return mid; 9 | else if(pow(mid,n)>m)h=mid-1; 10 | else l=mid+1; 11 | } 12 | return -1; 13 | } 14 | -------------------------------------------------------------------------------- /Mathematical/31. Water and Jug Problem.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { 4 | if(targetCapacity == 0)return 1; 5 | if(jug1Capacity + jug2Capacity >= targetCapacity and targetCapacity % __gcd(jug1Capacity,jug2Capacity) == 0)return 1; 6 | return 0; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Linked list/26. Delete Nth node from last.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | ListNode* i=head,*j=head; 5 | while(n--)j=j->next; 6 | if(!j)return head->next; 7 | while(j->next){i=i->next; j=j->next;} 8 | i->next=i->next->next; 9 | return head; 10 | } 11 | -------------------------------------------------------------------------------- /Mathematical/35. Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int ans = 0; 5 | for(int i = 0; i < nums.size(); i++) 6 | { 7 | ans ^= nums[i]; 8 | ans ^= i; 9 | } 10 | ans ^= nums.size(); 11 | return ans; 12 | 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Stack/16. count reversals.cpp: -------------------------------------------------------------------------------- 1 | int countRev (string s) 2 | { 3 | // your code here 4 | int close = 0,open = 0; 5 | if(s.size() % 2)return -1; 6 | for(auto x: s) 7 | { 8 | if(x == '{')open++; 9 | else if(open && x == '}')open--; 10 | else close++; 11 | } 12 | return ceil((open+1)/2)+ceil((close+1)/2); 13 | } 14 | -------------------------------------------------------------------------------- /String/Direct_logic_based/README.md: -------------------------------------------------------------------------------- 1 | # Direct Logic Based Approach 2 |
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 | vectordp(n+1,0); 4 | dp[1] = k; 5 | dp[2] = k*k; 6 | for(int i = 3; i <= n; i++) 7 | { 8 | dp[i]= ((k-1) * (dp[i-1] + dp[i-2]))%1000000007; 9 | } 10 | return dp[n]; 11 | } 12 | -------------------------------------------------------------------------------- /Greedy/11. Wiggle Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int wiggleMaxLength(vector& nums) { 4 | int pos = 1, neg = 1; 5 | for(int i = 1; i < nums.size(); i++) 6 | { 7 | if(nums[i] > nums[i-1])pos = neg + 1; 8 | else if(nums[i] < nums[i-1])neg = pos + 1; 9 | } 10 | return max(pos,neg); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Mathematical/38. Maximum sum LCM.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static long maxSumLCM(int n) { 3 | // code here 4 | long ans = 0; 5 | for(int i = 1; i*i <= n; i++){ 6 | if(n % i == 0){ 7 | ans += i; 8 | if(i != n/i)ans += (n / i); 9 | } 10 | } 11 | return ans; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /String/Pattern_based/18. Vowels of all substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countVowels(string word) { 4 | long long int ans = 0; 5 | for(int i = 0; i < word.size(); i++) 6 | { 7 | if(string("aeiou").find(word[i]) != string::npos) 8 | ans += (i+1) * (word.size()-i); 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic_programming/27. Handshake.cpp: -------------------------------------------------------------------------------- 1 | int count(int N){ 2 | // code here 3 | vectordp(N+1,0); 4 | dp[0] = 1; 5 | for(int i = 2; i <= N; i += 2) 6 | { 7 | for(int j = 2; j <= i; j += 2) 8 | { 9 | dp[i] += dp[i-j] * dp[j - 2]; 10 | } 11 | } 12 | return dp[N]; 13 | } 14 | -------------------------------------------------------------------------------- /Searching Sorting/Easy ques/Smaller_on_left.cpp: -------------------------------------------------------------------------------- 1 | vector Smallestonleft(int arr[], int n) 2 | { 3 | // Complete the function 4 | sets; 5 | s.insert(-1); 6 | vectorans(n); 7 | for(int i = 0; i < n; i++){ 8 | s.insert(arr[i]); 9 | auto x = s.find(arr[i]); 10 | x--; 11 | ans[i] = *x; 12 | } 13 | return ans; 14 | } 15 | -------------------------------------------------------------------------------- /Binary Trees/9. Balanced BT.cpp: -------------------------------------------------------------------------------- 1 | int ht(TreeNode* root){ 2 | if(!root)return 0; 3 | else return 1+max(ht(root->left),ht(root->right)); 4 | } 5 | class Solution { 6 | public: 7 | bool isBalanced(TreeNode* root) { 8 | if(!root)return true; 9 | return isBalanced(root->left)&&isBalanced(root->right)&&(abs(ht(root->left)-ht(root->right))<=1); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Mathematical/36. Rearrange geeks and his classmates.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void prank(long long a[], int n){ 4 | // code here 5 | for(int i = 0; i < n; i++) 6 | { 7 | a[i] = n * (a[a[i]] % n) + a[i] % n; 8 | } 9 | for(int i = 0; i < n; i++) 10 | { 11 | a[i] = a[i] / n; 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Binary Trees/25. LCA BST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | while(root){ 5 | if(root->val < p->val && root->val < q->val)root = root->right; 6 | else if(root->val > p->val && root->val > q->val)root = root->left; 7 | else break; 8 | } 9 | return root; 10 | } 11 | -------------------------------------------------------------------------------- /Greedy/2. Jump II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | // code here 5 | int i,reach=0,current=0,jmps=0; 6 | for(i=0;i& nums, int k) { 4 | unordered_map m; 5 | for(auto x: nums)m[x]++; 6 | int ans = 0; 7 | for(auto x: m) 8 | { 9 | if(k == 0 && x.second > 1)ans++; 10 | else if(k > 0 && m.count(x.first+k))ans++; 11 | } 12 | return ans; 13 | } 14 | -------------------------------------------------------------------------------- /Binary Trees/26. Unique BST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long int find(int n,int k){ 4 | if(k>n-k)k = n-k; 5 | long long int ans=1; 6 | for(int i=0;ival != q->val)return false; 5 | return check(p->left, q->right) && check(p->right,q->left); 6 | } 7 | class Solution { 8 | public: 9 | bool isSymmetric(TreeNode* root) { 10 | TreeNode* p=root,*q=root; 11 | return check(p->left,q->right); 12 | } 13 | -------------------------------------------------------------------------------- /Prefix_Suffix/1. product of array itself.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | int l, r, n = nums.size(), i; 5 | l = nums[0]; 6 | r = nums[n-1]; 7 | vectorans(n, 1); 8 | for(i = 1; i < n; i++){ans[i] = l; l *= nums[i];} 9 | for(i = n-2; i >= 0; i--){ans[i] *= r; r *= nums[i];} 10 | return ans; 11 | } 12 | -------------------------------------------------------------------------------- /String/Substring Concept/README.md: -------------------------------------------------------------------------------- 1 | # Substring Concept Problems 2 | 3 | ## Core Concept 4 | 5 | **Problem URL**: [https://leetcode.com/problems/longest-substring-without-repeating-characters/](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 6 | 7 | **Core Concept**: Sliding window with character position tracking 8 | 9 | **Approach**: Use sliding window with array to track last positions of characters 10 | -------------------------------------------------------------------------------- /Binary Trees/32. kth smallest BST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans = 0, n; 4 | void preorder(TreeNode* root){ 5 | if(root){ 6 | preorder(root->left); 7 | if(--n == 0 && ans == 0)ans=root->val; 8 | preorder(root->right); 9 | } 10 | } 11 | int kthSmallest(TreeNode* root, int k) { 12 | n = k; 13 | preorder(root);; 14 | return ans; 15 | } 16 | -------------------------------------------------------------------------------- /Linked list/33. Count triplets in SLL.cpp: -------------------------------------------------------------------------------- 1 | int countTriplets(struct Node* head, int x) 2 | { 3 | // code here. 4 | unordered_mapm; 5 | int count=0; 6 | for(auto i=head;i;i=i->next) 7 | { 8 | for(auto j=i->next;j;j=j->next) 9 | { 10 | if(m[max(0,x-i->data-j->data)])count++; 11 | } 12 | m[i->data]=1; 13 | } 14 | return count; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Dynamic_programming/6_min_cost_climbing_stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | int n = cost.size(); 5 | vectorv(n); 6 | for(int i = 0; i < cost.size(); i++){ 7 | if(i == 0 || i == 1)v[i]=cost[i]; 8 | else v[i] = cost[i] + min(v[i-1], v[i-2]); 9 | } 10 | return min(v[n-1],v[n-2]); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Mathematical/21. Sum of query 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector querySum(int n, int arr[], int q, int queries[]) 4 | { 5 | // code here 6 | vectorv; 7 | int i,j,k; 8 | for(i=0;i= 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;inext)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 | vectorv(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_mapm; 6 | for(i=0;is1; 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 | vectoradj[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 | vectorprev(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 | vectorv; 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 | mapm; 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_mapm; 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_mapm; 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 | queueq; 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 | vectordp(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 | vectordp(10002, 0); 5 | vectorfreq(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_mapm; 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 | vectorprev=grayCode(n-1); 6 | vectorcurrent; 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 | vectordist(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 | vectorv; 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 | vectordp(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 | vectorv(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 | Stackst = 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_mapm; 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 | vectorans; 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 | vectorv(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 | vectorv(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_setm; 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 | vectorv(26,0); 5 | vectorans; 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->datadata)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 | vectordifference; 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 | vectormp(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_mapm; 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 | vectordp(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 | vectorv(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 | #include 2 | 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_mapm; 7 | vectorv; 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 | vectorv(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 | vectorm1(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 | vectorl(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 | vectorv; 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 | vectorv; 5 | if(!root)return v; 6 | queueq; 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 | vectorv; 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 | vectorans; 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 | vectorv(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 | vectorv(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_sets; 6 | unordered_mapm; 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 | vectorv; 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_mapm; 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_mapm; 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_mapm; 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 | vectorv; 5 | if(!root)return v; 6 | queueq; 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 | vectorv(n); 7 | string ans,tmp; 8 | int count = 0; 9 | for(int i=0;im; 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 | vectordp; 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;itmp,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 | vectorans; 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 | vectorcurr_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 | vectorsuffix_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(vectoradj[], 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, vectoradj[]){ 17 | // Code here 18 | vectorcolor(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, vectoradj[], 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, vectoradj[]) 15 | { 16 | // Code here 17 | for(int i = 0; i < V; i++){ 18 | int count = 0; 19 | vectorvisited(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 | vectorsfx(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 | pairsum1 = fun(root->left); 6 | pairsum2 = fun(root->right); 7 | pairans; 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 | vectortmp; 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 | queueq; 7 | q.push(root); 8 | while(!q.empty()) 9 | { 10 | int n = q.size(); 11 | vectorv; 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 | vectorvisited(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&nums) 5 | { 6 | // Code here 7 | vectortmp(nums.begin(), nums.end()); 8 | sort(tmp.begin(), tmp.end()); 9 | unordered_map>m; 10 | for(int i = 0; i < nums.size(); i++){ 11 | m[tmp[i]].first = nums[i]; 12 | m[tmp[i]].second = i; 13 | } 14 | int swaps = 0; 15 | for(int i = 0; i < nums.size(); i++){ 16 | while(nums[i] != tmp[i]){ 17 | swaps++; 18 | swap(nums[i], nums[m[nums[i]].second]); 19 | } 20 | } 21 | return swaps; 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Binary Trees/38. Bottom view of BT.cpp: -------------------------------------------------------------------------------- 1 | lass Solution { 2 | public: 3 | vector bottomView(Node *root) { 4 | // Your Code Here 5 | vectorans; 6 | queue>q; 7 | int i; 8 | mapm; 9 | q.push({root,0}); 10 | while(!q.empty()) 11 | { 12 | Node* x=q.front().first; 13 | int p = q.front().second; 14 | q.pop(); 15 | if(x->left)q.push({x->left,p-1}); 16 | if(x->right)q.push({x->right,p+1}); 17 | m[p] = x->data; //taking the bottom most value in vertical condition 18 | } 19 | 20 | for(auto x:m)ans.push_back(x.second); 21 | return ans; 22 | } 23 | -------------------------------------------------------------------------------- /Linked list/22. Sort 012.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to sort a linked list of 0s, 1s and 2s. 5 | Node* segregate(Node *head) { 6 | 7 | // Add code here 8 | Node* t=head; 9 | int c0=0,c1=0,c2=0; 10 | while(t) 11 | { 12 | if(t->data==0)c0++; 13 | else if(t->data==1)c1++; 14 | else c2++; 15 | t=t->next; 16 | } 17 | t=head; 18 | while(t) 19 | { 20 | while(c0!=0){t->data=0; t=t->next; c0--;} 21 | while(c1!=0){t->data=1; t=t->next; c1--;} 22 | while(c2!=0){t->data=2; t=t->next; c2--;} 23 | } 24 | return head; 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Graph/12. Detect cycle in a undirected graph.cpp: -------------------------------------------------------------------------------- 1 | bool check(int src, int parent, vector&visited, vectoradj[]){ 2 | visited[src] = 1; 3 | for(auto x: adj[src]){ 4 | if(!visited[x]){ 5 | if(check(x, src, visited, adj))return true; 6 | } 7 | else if(x != parent)return true; //this line 8 | } 9 | return false; 10 | } 11 | bool isCycle(int V, vector adj[]) { 12 | // Code here 13 | vectorvisited(V, 0); 14 | for(int i = 0; i < V; i++){ 15 | if(!visited[i]){ 16 | if(check(i, -1, visited, adj))return true; 17 | } 18 | } 19 | return false; 20 | 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /Linked list/36. swap kth nodes from ends.cpp: -------------------------------------------------------------------------------- 1 | Node *swapkthnode(Node* head, int num, int K) 2 | { 3 | // Your Code here 4 | Node *dummy = new Node(0); 5 | dummy->next = head; 6 | if(!head || K > num || K == num - K + 1)return head; //base case 7 | int first = min(K, num - K + 1); 8 | int second = num - first + 1; 9 | Node *a = dummy; 10 | for(int i = 0; i < first-1; i++){ 11 | a = a->next; 12 | } 13 | Node *b = a; 14 | for(int i = 0; i < second - first; i++){ 15 | b = b->next; 16 | } 17 | Node *tmp = a->next; 18 | a->next = b->next; 19 | b->next = tmp; 20 | tmp = a->next->next; 21 | a->next->next = b->next->next; 22 | b->next->next = tmp; 23 | return dummy->next; 24 | } 25 | -------------------------------------------------------------------------------- /Matrix/11. Find Rectangle with corner as 1.cpp: -------------------------------------------------------------------------------- 1 | int fun(vector>matrix, int i, int j) 2 | { 3 | int m = matrix[0].size(); 4 | int count = 0; 5 | for(int k = 0; k < m; k++) 6 | { 7 | if(matrix[i][k] and matrix[j][k])count++; 8 | } 9 | return count >= 2; 10 | } 11 | bool ValidCorner(const vector >& matrix) 12 | { 13 | // Your code goes here 14 | int n = matrix.size(), m = matrix[0].size(); 15 | for(int i = 0; i < n; i++) 16 | { 17 | for(int j = i+1; j < n; j++) 18 | { 19 | if(fun(matrix,i,j))return true; 20 | } 21 | } 22 | return false; 23 | -------------------------------------------------------------------------------- /Sliding Window/3. Sliding window max.cpp: -------------------------------------------------------------------------------- 1 | ////vvv.imp concept usage 2 | 3 | class Solution { 4 | public: 5 | vector maxSlidingWindow(vector& nums, int k) { 6 | int i = 0,j,m,l = 0; 7 | vectorv; 8 | dequeq; 9 | for(i = 0; i < k; i++){ 10 | while(!q.empty() && q.back() < nums[i])q.pop_back(); 11 | q.push_back(nums[i]); 12 | } 13 | v.push_back(q.front()); 14 | for(i = 1; i <= nums.size()-k; i++){ 15 | if(q.front() == nums[i-1])q.pop_front(); 16 | while(!q.empty() && q.back() < nums[i+k-1])q.pop_back(); 17 | q.push_back(nums[i+k-1]); 18 | v.push_back(q.front()); 19 | } 20 | return v; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Dynamic_programming/9. frnds paring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution 6 | { 7 | public: 8 | int countFriendsPairings(int n) 9 | { 10 | // code here 11 | vectordp(n+1); 12 | dp[0]=0; 13 | dp[1]=1; 14 | dp[2]=2; 15 | for(int i = 3; i <= n; i++)dp[i] = (dp[i-1] + dp[i-2] * (i - 1)) % 1000000007; 16 | return dp[n]; 17 | 18 | } 19 | }; 20 | 21 | 22 | // { Driver Code Starts. 23 | int main() 24 | { 25 | int t; 26 | cin>>t; 27 | while(t--) 28 | { 29 | int n; 30 | cin>>n; 31 | Solution ob; 32 | cout < dijkstra(int V, vector> adj[], int S) 2 | { 3 | // Code here 4 | queueq; 5 | vector>tmp(V); 6 | vectordist(V, INT_MAX); 7 | dist[S] = 0; 8 | q.push(S); 9 | while(!q.empty()){ 10 | int curr = q.front(); 11 | q.pop(); 12 | for(auto x: adj[curr]){ 13 | int neighbour = x[0]; 14 | int len = x[1]; 15 | if(dist[neighbour] > dist[curr] + len){ 16 | dist[neighbour] = dist[curr] + len; 17 | q.push(neighbour); 18 | } 19 | } 20 | } 21 | return dist; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Priority Queue/11. Construct Target array with mutliple sums.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossible(vector& target) { 4 | priority_queuepq; 5 | long long int sum = 0; 6 | for(int i = 0; i < target.size(); i++){ 7 | sum += target[i]; 8 | pq.push(target[i]); 9 | } 10 | while(pq.top() != 1){ 11 | sum -= pq.top(); 12 | if(sum == 0 || pq.top() <= sum)return false; 13 | int old = pq.top() % sum; //we will delete all copies of that sum 14 | if(old == 0 and sum != 1)return false; //only for n = 2 case 15 | pq.pop(); 16 | pq.push(old); 17 | sum += old; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Trie/1. insert and search.cpp: -------------------------------------------------------------------------------- 1 | void insert(struct TrieNode *root, string key) 2 | { 3 | // code here 4 | struct TrieNode* tmp=root; 5 | for(int i=0;ichildren[index])tmp->children[index]=getNode(); 9 | tmp=tmp->children[index]; 10 | } 11 | tmp->isLeaf=true; 12 | } 13 | 14 | //Function to use TRIE data structure and search the given string. 15 | bool search(struct TrieNode *root, string key) 16 | { 17 | // code here 18 | struct TrieNode* tmp=root; 19 | for(int i=0;ichildren[index])return false; 23 | tmp=tmp->children[index]; 24 | } 25 | return tmp->isLeaf; 26 | -------------------------------------------------------------------------------- /Array/19. Buying selling share atmost twice.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int price[] = { 2, 30, 15, 10, 8, 25, 80 }; 7 | int n = 7; 8 | 9 | // adding array 10 | int profit = 0; 11 | 12 | // Initializing variable 13 | // valley-peak approach 14 | /* 15 | 80 16 | / 17 | 30 / 18 | / \ 25 19 | / 15 / 20 | / \ / 21 | 2 10 / 22 | \ / 23 | 8 24 | */ 25 | for (int i = 1; i < n; i++) 26 | { 27 | 28 | // traversing through array from (i+1)th 29 | // position 30 | int sub = price[i] - price[i - 1]; 31 | if (sub > 0) 32 | profit += sub; 33 | } 34 | 35 | cout << "Maximum Profit=" << profit; 36 | return 0; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /String/39. Word pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string s) { 4 | unordered_mapm; 5 | unordered_setst; 6 | int i, j; 7 | for(i = 0, j = 0; i < pattern.size(); i++, j++){ 8 | string tmp; 9 | if(j >= s.size())return false; 10 | while(j < s.size() and s[j] != ' ')tmp += s[j++]; 11 | if(m.find(pattern[i]) == m.end()){ 12 | if(st.find(tmp) != st.end())return false; 13 | m[pattern[i]] = tmp; 14 | st.insert(tmp); 15 | } 16 | else if(m[pattern[i]] != tmp)return false; 17 | } 18 | if(j < s.size())return false; 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Priority Queue/10. Lucy neighbours.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | static bool cmp(pairp1,pairp2) 4 | { 5 | if(p1.second == p2.second)return p1.first < p2.first; 6 | return p1.second < p2.second; 7 | } 8 | vector Kclosest(vectorarr, int n, int x, int k) 9 | { 10 | // Your code goes here 11 | vector>v; 12 | vectorans; 13 | for(auto y: arr) 14 | { 15 | v.push_back({y, abs(x-y)}); 16 | } 17 | sort(v.begin(), v.end(), cmp); 18 | for(auto x: v) 19 | { 20 | if(ans.size() != k)ans.push_back(x.first); 21 | } 22 | sort(ans.begin(), ans.end()); 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Searching Sorting/27. Smallest Absolute difference.cpp: -------------------------------------------------------------------------------- 1 | nt count(int a[], int n, int mid){ 2 | int ans = 0; 3 | for(int i = 0; i < n; i++){ 4 | ans += upper_bound(a+i, a+n, a[i]+mid) - (a+i+1); 5 | } 6 | return ans; 7 | } 8 | int kthDiff(int a[], int n, int k) 9 | { 10 | sort(a, a+n); 11 | int low = a[1] - a[0]; 12 | //Finding min element 13 | for(int i = 1; i <= n-2; i++) 14 | { 15 | low = min(low, a[i+1] - a[i]); 16 | } 17 | int high = a[n-1] - a[0]; 18 | while(low < high){ 19 | int mid = (low+high)/2; 20 | if(count(a, n, mid) < k) 21 | { 22 | low = mid+1; 23 | } 24 | else 25 | { 26 | high = mid; 27 | } 28 | } 29 | return low; 30 | } 31 | -------------------------------------------------------------------------------- /Graph/15. Topological sort.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | //Function to return list containing vertices in Topological order. 3 | stacks; 4 | void dfs(vectoradj[], vector&visited, int src){ 5 | visited[src] = 1; 6 | for(auto x: adj[src]){ 7 | if(!visited[x]){ 8 | dfs(adj, visited, x); 9 | } 10 | } 11 | s.push(src); 12 | } 13 | vector topoSort(int V, vector adj[]) 14 | { 15 | // code here 16 | vectorvisited(V, 0); 17 | vectorans; 18 | for(int i = 0; i < V; i++){ 19 | if(!visited[i]){ 20 | dfs(adj, visited, i); 21 | } 22 | } 23 | while(!s.empty()){ 24 | ans.push_back(s.top()); 25 | s.pop(); 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Graph/7. Count the paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int count = 0; 4 | void dfs(int s, vector&visited, vectoradj[], int d){ 5 | if(s == d){ 6 | count++; 7 | return; 8 | } 9 | visited[s] = 1; 10 | for(auto x: adj[s]){ 11 | if(!visited[x]){ 12 | dfs(x, visited, adj, d); 13 | } 14 | } 15 | visited[s] = 0; 16 | } 17 | int possible_paths(vector>edges, int n, int s, int d){ 18 | // Code here 19 | vectoradj[n]; 20 | for(int i = 0; i < edges.size(); i++){ 21 | adj[edges[i][0]].push_back(edges[i][1]); 22 | } 23 | vectorvisited(n, 0); 24 | dfs(s, visited, adj, d); 25 | return count; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Samsung R & D/7. Sum at level k.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 3 | (0(5(6()())(4()(9()())))(7(1()())(3()()))) 4 | 1 5 | (0(5(6()())(4()(9()())))(7(1()())(3()()))) 6 | 2 7 | (0(5(6()())(4()(9()())))(7(1()())(3()()))) 8 | 3 9 | 10 | Answers 11 | 12 14 9 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | int ans, t, k; 17 | void fun(string s, int k){ 18 | int level = -1; 19 | int i = 0; 20 | while(s[i] != '\0'){ 21 | if(s[i] == '(')level++; 22 | else if(s[i] == ')')level--; 23 | else if(level == k)ans += (s[i] - '0'); 24 | i++; 25 | } 26 | } 27 | int main(){ 28 | cin>>t; 29 | for(int test_case = 1; test_case <= t; test_case++){ 30 | string s; 31 | cin>>k>>s; 32 | ans = 0; 33 | fun(s, k); 34 | cout<<'#'<<" "< 2 | using namespace std; 3 | class Solution{ 4 | public: 5 | vector find3Numbers(vector arr, int N) { 6 | // Your code here 7 | int i,j,k,l[N],r[N]; 8 | l[0] = arr[0]; 9 | for(i = 1; i < N; i++)l[i] = min(arr[i], l[i-1]); 10 | r[N-1] = arr[N-1]; 11 | for(i = N-2; i >= 0; i--)r[i] = max(arr[i], r[i+1]); 12 | vectorv; 13 | for(i = 1; i < N-1; i++){ 14 | if(l[i-1] < arr[i] && arr[i] < r[i+1]){ 15 | v.push_back(l[i-1]); 16 | v.push_back(arr[i]); 17 | v.push_back(r[i+1]); 18 | return v; 19 | } 20 | } 21 | return v; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/30. Zigzag in BT.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> zigzagLevelOrder(TreeNode* root) { 4 | vector>v; 5 | if(!root)return v; 6 | queueq; 7 | q.push(root); 8 | int i = 0; 9 | while(!q.empty()){ 10 | int n = q.size(); 11 | vectors; 12 | while(n--){ 13 | TreeNode *t=q.front(); 14 | q.pop(); 15 | s.push_back(t->val); 16 | if(t->left)q.push(t->left); 17 | if(t->right)q.push(t->right); 18 | } 19 | if(i & 1)reverse(s.begin(), s.end()); 20 | v.push_back(s); 21 | i++; 22 | } 23 | return v; 24 | } 25 | -------------------------------------------------------------------------------- /Dynamic_programming/10_1. House robber 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int path(vectornums){ 3 | int n=nums.size(); 4 | int dp[n+1]; 5 | dp[0]=0; 6 | dp[1]=nums[0]; 7 | for(int i = 2; i <= n; i++)dp[i] = max(dp[i-2] + nums[i-1], dp[i-1]); //nums[i-1] here 8 | return dp[n]; 9 | } 10 | public: 11 | int rob(vector& nums) { 12 | int i,j,k,n=nums.size(); 13 | if(n == 0)return 0; 14 | if(n == 1)return nums[0]; 15 | if(n == 2)return max(nums[0],nums[1]); 16 | int a = path(vector(nums.begin(),nums.end()-1)); //exclude last element when we choose 1st 17 | int b = path(vector(nums.begin()+1,nums.end())); //exclude 1st element when we choose last 18 | return max(a,b); 19 | } 20 | -------------------------------------------------------------------------------- /Greedy/10. Police and Thieves.cpp: -------------------------------------------------------------------------------- 1 | int catchThieves(char arr[], int n, int k) 2 | { 3 | // Code here 4 | int count = 0; 5 | vectorv1,v2; 6 | for(int i = 0;i < n ; i++) 7 | { 8 | if(arr[i] == 'P')v1.push_back(i); 9 | } 10 | for(int i = 0;i < n ; i++) 11 | { 12 | if(arr[i] == 'T')v2.push_back(i); 13 | } 14 | int i = 0, j = 0; 15 | while(i < v1.size() && j < v2.size()) 16 | { 17 | if(abs(v1[i] -v2[j]) <= k) 18 | { 19 | count++; 20 | i++; 21 | j++; 22 | } 23 | else if(v1[i] < v2[j])i++; 24 | else j++; 25 | } 26 | return count; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Priority Queue/2. Array of Doubled pairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canReorderDoubled(int[] arr) { 3 | Arrays.sort(arr); 4 | Queue q = new LinkedList<>(); 5 | for(int num: arr){ 6 | if(num < 0){ 7 | if(!q.isEmpty() && q.peek() == 2*num){ 8 | int tmp = q.poll(); 9 | } 10 | else q.add(num); 11 | } 12 | } 13 | if(q.size() > 0)return false; 14 | for(int num: arr){ 15 | if(num > 0){ 16 | if(!q.isEmpty() && q.peek() == num){ 17 | int c = q.poll(); 18 | } 19 | else q.add(num * 2); 20 | } 21 | } 22 | return q.size() == 0; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Dynamic_programming/Grid/README.md: -------------------------------------------------------------------------------- 1 | # Approach 2 |
 3 |   Cheery pickup                      cheery pickup 2
 4 |    key points:
 5 |    going from top to bottom or bottom to top is same
 6 |    consider bottom starting simultaneously
 7 |    r1 + c1 = r2 + c2 
 8 |    cases
 9 |    1. Both are at same point pick up one
10 |    2. Both are at different points choose both
11 |    3. choose next all possible(2*2) move and take max add to the previous pickup. Meanwhile in 2nd model its 3*3
12 |    4. store the values in 3D dp(by column changing pattern)
13 | 
14 | -------------------------------------------------------------------------------- /Mathematical/13. Check binary representation is palindrome or not.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution{ 6 | public: 7 | int isPallindrome(long long int N){ 8 | // code here 9 | bitset<32>b(N); 10 | int i,j; 11 | string s; 12 | for(i=32;i>=0;i--)if(b[i]==1){j=i; break;} 13 | for(i=j;i>=0;i--)s+=b[i]+'0'; 14 | if(s==string(s.rbegin(),s.rend()))return 1; 15 | else return 0; 16 | } 17 | }; 18 | 19 | // { Driver Code Starts. 20 | int main() 21 | { 22 | int t; 23 | cin>>t; 24 | while(t--) 25 | { 26 | long long int N; 27 | cin>>N; 28 | Solution ob; 29 | cout << ob.isPallindrome(N) << endl; 30 | } 31 | return 0; 32 | -------------------------------------------------------------------------------- /Mathematical/18. Magic number.cpp: -------------------------------------------------------------------------------- 1 | //Initial template for c++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | //User function Template for C++ 8 | 9 | class Solution{ 10 | public: 11 | long long int nthMagicNo(int n) { 12 | //complete the function here 13 | bitset<32>b(n); 14 | long long int i,j=0; 15 | for(i=0;i<32;i++){ 16 | j+=pow(5,i+1)*b[i]; j%=(1000000007);} 17 | 18 | return j; 19 | } 20 | }; 21 | 22 | // { Driver Code Starts. 23 | 24 | int main() 25 | { 26 | int t; 27 | cin>>t; 28 | while(t--) 29 | { 30 | int n; 31 | cin >> n; 32 | Solution ob; 33 | cout << ob.nthMagicNo(n) << endl; 34 | 35 | } 36 | return 0; 37 | -------------------------------------------------------------------------------- /Stack/17. Simplify Path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) { 4 | string ans; 5 | stacks; 6 | for(int i = 0; i < path.size(); i++){ 7 | if(path[i] == '/')continue; 8 | string tmp; 9 | while(i < path.size() and path[i] != '/'){ 10 | tmp += path[i++]; 11 | } 12 | if(tmp == ".")continue; 13 | else if(tmp == ".."){ 14 | if(s.size() > 0)s.pop(); 15 | } 16 | else{ 17 | s.push(tmp); 18 | } 19 | } 20 | while(s.size()){ 21 | ans = '/' + s.top() + ans; 22 | s.pop(); 23 | } 24 | if(ans.size() == 0)return "/"; 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Binary Trees/57. Check given tree is Complete Binary tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | bool isCompleteBT(Node* root){ 4 | //code here 5 | if(!root)return true; 6 | queueq; 7 | q.push(root); 8 | bool check = false; 9 | while(!q.empty()){ 10 | Node* tmp = q.front(); 11 | q.pop(); 12 | if(tmp->left){ 13 | if(!check)q.push(tmp->left); 14 | else return false; 15 | } 16 | else check = true; 17 | if(tmp->right){ 18 | if(!check)q.push(tmp->right); 19 | else return false; 20 | } 21 | else check = true; 22 | } 23 | return true; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Searching Sorting/25.Split array largest sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int splitArray(vector& nums, int k) { 4 | int high = 0, low = INT_MIN, ans; 5 | for(int i = 0; i < nums.size(); i++){ 6 | low = max(low, nums[i]); 7 | high += nums[i]; 8 | } 9 | while(low <= high){ 10 | int mid = (low+high)/2; 11 | int count = 1, tmp_sum = 0; 12 | for(int i = 0; i < nums.size(); i++){ 13 | tmp_sum += nums[i]; 14 | if(tmp_sum > mid){ 15 | count++; 16 | tmp_sum = nums[i]; 17 | } 18 | } 19 | if(count <= k){high = mid-1, ans = mid;} 20 | else low = mid+1; 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Dynamic_programming/21. LCS of three strings.cpp: -------------------------------------------------------------------------------- 1 | int LCSof3 (string A, string B, string C, int n1, int n2, int n3) 2 | { 3 | // your code here 4 | int dp[n1+1][n2+1][n3+1]; 5 | memset(dp,0,sizeof(dp)); 6 | for(int i = 1; i <= n1; i++) 7 | { 8 | for(int j = 1; j <= n2; j++) 9 | { 10 | for(int k = 1; k <= n3; k++) 11 | { 12 | if(A[i-1] == B[j-1] && B[j-1] == C[k-1]) 13 | { 14 | dp[i][j][k] = 1 + dp[i-1][j-1][k-1]; 15 | } 16 | else 17 | { 18 | dp[i][j][k] = max(dp[i-1][j][k], max(dp[i][j-1][k], dp[i][j][k-1])); 19 | } 20 | 21 | } 22 | } 23 | } 24 | return dp[n1][n2][n3]; 25 | } 26 | -------------------------------------------------------------------------------- /Dynamic_programming/11. Gold Mine Problem.cpp: -------------------------------------------------------------------------------- 1 | int maxGold(int n, int m, vector> M) 2 | { 3 | // code here 4 | vector>dp(n,vector(m,0)); 5 | for(int col = m-1; col >= 0; col--) 6 | { 7 | for(int row = 0; row < n; row++) 8 | { 9 | int right = (col == m-1)? 0: dp[row][col+1]; 10 | int right_up = (col == m-1 || row == 0)? 0: dp[row-1][col+1]; 11 | int right_down = (col == m-1 || row == n-1)? 0: dp[row+1][col+1]; 12 | dp[row][col] = M[row][col] + max(right, max(right_up,right_down)); 13 | } 14 | } 15 | int ans = dp[0][0]; 16 | for(int i = 1; i < n; i++) 17 | { 18 | ans = max(ans, dp[i][0]); 19 | } 20 | return ans; 21 | } 22 | -------------------------------------------------------------------------------- /Binary Trees/42. Check given tree is heap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isHeap(struct Node* tree) { 4 | // code here 5 | queueq; 6 | q.push(tree); 7 | bool check=false; 8 | while(!q.empty()) 9 | { 10 | Node* x=q.front(); 11 | q.pop(); 12 | if(x->left) 13 | { 14 | if(check || x->left->data >= x->data)return 0; //if left null and right not then it is not heap 15 | q.push(x->left); 16 | } 17 | else check = true; 18 | if(x->right) 19 | { 20 | if(check || x->right->data >= x->data)return 0; 21 | q.push(x->right); 22 | } 23 | else check=true; 24 | } 25 | return true; 26 | 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Searching Sorting/Easy ques/count_triplet_with_given_range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int count(int Arr[],int N,int x) 4 | { 5 | sort(Arr, Arr+N); 6 | int count = 0; 7 | for(int i = 0; i < N-2; i++) 8 | { 9 | int j = i+1; 10 | int h = N-1; 11 | while(j < h) 12 | { 13 | int sum = Arr[i]+Arr[j]+Arr[h]; 14 | if(sum > x)h--; 15 | else{ 16 | count += (h-j); 17 | j++; 18 | } 19 | } 20 | 21 | } 22 | return count; 23 | } 24 | int countTriplets(int Arr[], int N, int L, int R) { 25 | // code here 26 | int ans=count(Arr,N,R)-count(Arr,N,L-1); 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/42. Check given tree is heap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isHeap(struct Node* tree) { 4 | // code here 5 | queueq; 6 | q.push(tree); 7 | bool check = false; 8 | while(!q.empty()) 9 | { 10 | Node* x = q.front(); 11 | q.pop(); 12 | if(x->left) 13 | { 14 | if(check || x->left->data >= x->data)return 0; //if left null and right not then it is not heap 15 | q.push(x->left); 16 | } 17 | else check=true; 18 | if(x->right) 19 | { 20 | if(check || x->right->data >= x->data)return 0; 21 | q.push(x->right); 22 | } 23 | else check=true; 24 | } 25 | return true; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Binary Trees/43. find mode in BST.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* prev=NULL; 2 | int count = 1,max_f = INT_MIN; 3 | vectorv; 4 | void inorder(TreeNode* root) 5 | { 6 | if(root) 7 | { 8 | inorder(root->left); 9 | if(prev && prev->val==root->val)count++; 10 | else 11 | { 12 | count=1; 13 | prev = root; 14 | } 15 | if(max_f < count){ 16 | v.clear(); 17 | v.push_back(root->val); 18 | max_f = count; 19 | } 20 | else if(max_f == count)v.push_back(root->val); 21 | 22 | 23 | inorder(root->right); 24 | } 25 | } 26 | vector findMode(TreeNode* root) { 27 | inorder(root); 28 | return v; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Bit Manipulation/3. Count no of bits A to B.cpp: -------------------------------------------------------------------------------- 1 | //Initial Template for C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | // Function to find number of bits needed to be flipped to convert A to B 13 | int countBitsFlip(int a, int b){ 14 | 15 | // Your logic here 16 | int x=a^b; 17 | bitset<32>k(x); 18 | return k.count(); 19 | 20 | } 21 | }; 22 | 23 | // { Driver Code Starts. 24 | 25 | // Driver Code 26 | int main() 27 | { 28 | int t; 29 | cin>>t;// input the testcases 30 | while(t--) //while testcases exist 31 | { 32 | int a,b; 33 | cin>>a>>b; //input a and b 34 | 35 | Solution ob; 36 | cout<>dp(N+1,vector(sum+1,0)); 9 | for(int i = 0; i <= N; i++)dp[i][0] = 1; 10 | for(int i = 1; i <= N; i++) 11 | { 12 | for(int j = 1; j <= sum; j++) 13 | { 14 | if(j - arr[i-1] >= 0) 15 | { 16 | dp[i][j] = dp[i-1][j-arr[i-1]] || dp[i-1][j]; 17 | } 18 | else 19 | { 20 | dp[i][j] = dp[i-1][j]; 21 | } 22 | } 23 | } 24 | return dp[N][sum]; 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Binary Trees/51. Leaves to DLL.cpp: -------------------------------------------------------------------------------- 1 | Node* preorder(Node* root, Node*& head, Node*& prev) 2 | { 3 | if(!root)return NULL; 4 | if(!root->left && !root->right) 5 | { 6 | if(!head) 7 | { 8 | head = prev = root; 9 | } 10 | else 11 | { 12 | prev->right = root; 13 | root->left = prev; 14 | prev = root; 15 | } 16 | return NULL; 17 | } 18 | root->left = preorder(root->left, head, prev); 19 | root->right = preorder(root->right, head, prev); 20 | return root; 21 | 22 | } 23 | Node * convertToDLL(Node *root){ 24 | // add code here. 25 | if(!root)return NULL; 26 | Node* head = NULL; 27 | Node* prev = NULL; 28 | preorder(root,head,prev); 29 | return head; 30 | } 31 | -------------------------------------------------------------------------------- /Graph/11. Detect cycle in a directed graph.cpp: -------------------------------------------------------------------------------- 1 | bool check(int src, vector&visited, vector&dfsvisited, vectoradj[]){ 2 | visited[src] = 1; 3 | dfsvisited[src] = 1; 4 | for(auto x: adj[src]){ 5 | if(!visited[x]){ 6 | if(check(x, visited, dfsvisited, adj))return true; 7 | } 8 | else if(dfsvisited[x])return true; 9 | } 10 | dfsvisited[src] = 0; 11 | return false; 12 | } 13 | bool isCyclic(int V, vector adj[]) { 14 | // code here 15 | vectorvisited(V, 0); 16 | vectordfsvisited(V, 0); 17 | for(int i = 0; i < V; i++){ 18 | if(!visited[i]){ 19 | if(check(i, visited, dfsvisited, adj))return true; 20 | } 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Greedy/16. Can Place Flowers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPlaceFlowers(vector& flowerbed, int n) { 4 | int count = 0; 5 | for (int i = 0; i < flowerbed.size(); i++) { 6 | // Check if the current plot is empty. 7 | if (flowerbed[i] == 0) { 8 | // Check if the left and right plots are empty. 9 | bool emptyLeftPlot = (i == 0) || (flowerbed[i - 1] == 0); 10 | bool emptyRightPlot = (i == flowerbed.size() - 1) || (flowerbed[i + 1] == 0); 11 | 12 | // If both plots are empty, we can plant a flower here. 13 | if (emptyLeftPlot && emptyRightPlot) { 14 | flowerbed[i] = 1; 15 | count++; 16 | } 17 | } 18 | } 19 | return count >= n; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Matrix/14. Filp columns for max no.of equal rows.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string fun(vector&v){ 4 | string ans; 5 | for(int i = 0; i < v.size(); i++){ 6 | ans += (v[i] + '0'); 7 | } 8 | return ans; 9 | } 10 | int maxEqualRowsAfterFlips(vector>& matrix) { 11 | unordered_mapm; 12 | int ans = 0; 13 | for(int i = 0; i < matrix.size(); i++){ 14 | string tmp = fun(matrix[i]); 15 | m[tmp]++; 16 | for(int j = 0; j < matrix[i].size(); j++){ 17 | matrix[i][j] = matrix[i][j] == 0? 1: 0; 18 | } 19 | tmp = fun(matrix[i]); 20 | m[tmp]++; 21 | } 22 | for(auto x: m){ 23 | ans = max(ans, x.second); 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Dynamic_programming/1. coin problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution 6 | { 7 | public: 8 | long long int count( int S[], int m, int n ) 9 | { 10 | 11 | //code here. 12 | long long int dp[n+1] = {0}; 13 | dp[0] = 1; 14 | int i,j; 15 | for(i = 0;i < m;i ++){ 16 | for(j = S[i];j <= n; j++){ 17 | dp[j] += dp[j-S[i]]; 18 | } 19 | } 20 | return dp[n]; 21 | } 22 | }; 23 | 24 | // { Driver Code Starts. 25 | int main() 26 | { 27 | int t; 28 | cin>>t; 29 | while(t--) 30 | { 31 | int n,m; 32 | cin>>n>>m; 33 | int arr[m]; 34 | for(int i=0;i>arr[i]; 36 | Solution ob; 37 | cout< 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | 9 | class Solution{ 10 | public: 11 | int nCr(int n, int r){ 12 | // code here 13 | vector>dp(n+1,vector(r+1,0)); 14 | int i,j,k; 15 | for(i=1;i<=n;i++){ 16 | for(j=0;j<=r;j++){ 17 | if(j==0||i==j)dp[i][j]=1; 18 | else dp[i][j]=(dp[i-1][j-1]+dp[i-1][j])%(1000000007); 19 | } 20 | } 21 | return dp[n][r]; 22 | } 23 | }; 24 | 25 | // { Driver Code Starts. 26 | 27 | int main(){ 28 | int t; 29 | cin>>t; 30 | while(t--){ 31 | int n, r; 32 | cin>>n>>r; 33 | 34 | Solution ob; 35 | cout<val != root2->val)return false; 8 | return check(root1->left,root2->left) && check(root1->right,root2->right); 9 | } 10 | bool isSubtree(TreeNode* root, TreeNode* subRoot) { 11 | if(!root && !subRoot)return true; 12 | if(!root || !subRoot)return false; 13 | if(root->val == subRoot->val) //if node values of both trees matches verify same or not 14 | { 15 | if(check(root,subRoot))return true; 16 | } 17 | return (isSubtree(root->left,subRoot)||isSubtree(root->right,subRoot)) //verify each node recursivel 18 | } 19 | -------------------------------------------------------------------------------- /Graph/26. Prerequisites tasks.cpp: -------------------------------------------------------------------------------- 1 | bool isPossible(int N, vector >& prerequisites) { 2 | // Code here 3 | vectoradj[N]; 4 | vectorindeg(N, 0); 5 | for(auto x: prerequisites){ 6 | adj[x.second].push_back(x.first); 7 | indeg[x.first]++; 8 | } 9 | queueq; 10 | int size = 0; 11 | for(int i = 0; i < N; i++){ 12 | if(indeg[i] == 0){ 13 | q.push(i); 14 | size++; 15 | } 16 | } 17 | if(size == 0)return 0; 18 | while(!q.empty()){ 19 | int curr = q.front(); 20 | q.pop(); 21 | for(auto x: adj[curr]){ 22 | indeg[x]--; 23 | if(indeg[x] == 0){ 24 | q.push(x); 25 | size++; 26 | } 27 | } 28 | } 29 | return size == N? 1: 0; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Matrix/9. kth smallest in matrix.cpp: -------------------------------------------------------------------------------- 1 | //Time Complexity : O( N* log(N) * log(N)) 2 | class Solution { 3 | public: 4 | int kthSmallest(vector>& matrix, int k) { 5 | int n=matrix.size(); 6 | int min_element=matrix[0][0]; 7 | int max_element=matrix[n-1][n-1]; 8 | /*when we arrange all elements in order 9 | 10 | min mid max 11 | 1 5 9 10 11 12 13 13 15 12 | */ 13 | while(min_element<=max_element) 14 | { 15 | int mid=(min_element+max_element)/2; 16 | int count=0; 17 | for(int i=0;i>dp(x+1,vector(y+1,0)); 14 | for(int i = 1; i <= x; i++) 15 | { 16 | for(int j = 1; j <= y; j++) 17 | { 18 | if(s1[i-1] == s2[j-1]) 19 | { 20 | dp[i][j] = 1 + dp[i-1][j-1]; 21 | } 22 | else 23 | { 24 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 25 | } 26 | } 27 | } 28 | return dp[x][y]; 29 | } 30 | -------------------------------------------------------------------------------- /Graph/10. Find whether path exist.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find whether a path exists from the source to destination. 5 | bool dfs(int i, int j, vector>&grid){ 6 | if(i < 0 || i >= grid.size() || j < 0 || j >= grid.size() || grid[i][j] == 0)return false; 7 | if(grid[i][j] == 1)return true; 8 | grid[i][j] = 0; 9 | return dfs(i+1, j, grid) || dfs(i-1, j, grid) || dfs(i, j+1, grid) || dfs(i, j-1, grid); 10 | } 11 | bool is_Possible(vector>& grid) 12 | { 13 | //code here 14 | int n = grid.size(); 15 | for(int i = 0; i < n; i++){ 16 | for(int j = 0; j < n; j++){ 17 | if(grid[i][j] == 2){ 18 | if(dfs(i, j, grid))return true; 19 | } 20 | } 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Prefix_Suffix/README.md: -------------------------------------------------------------------------------- 1 | # Logic Problem Concepts: 2 |
 3 |   Car pooling: Need to update
 4 | 
5 | # Subarray Concepts 6 |
 7 |   Continuous subarray size atleast 2: Need to update
 8 |   Max len of continous subarray
 9 | 
10 | # NOTE: 11 |
12 |   1. For continous sub-array questions if we need to find the length of particular problem or anything, make use of map for efficient approach, incase of len use index usage 
13 | 
14 | 15 | -------------------------------------------------------------------------------- /Mathematical/7. Container most water.cpp: -------------------------------------------------------------------------------- 1 | //Initial template for C++ 2 | #include 3 | using namespace std; 4 | int maxArea(int A[], int len); 5 | 6 | // } Driver Code Ends 7 | //User function template for C++ 8 | #include 9 | long long maxArea(long long A[], int len) 10 | { 11 | // Your code goes here 12 | int l=0,h=len-1; 13 | long long int ans=0; 14 | while(l>t; 30 | while(t--) 31 | { 32 | int n; 33 | cin>>n; 34 | long long arr[n]; 35 | for(int i=0;i>arr[i]; 37 | cout<& tokens) { 4 | stacks; 5 | for(int i = 0; i < tokens.size(); i++) 6 | { 7 | string str = tokens[i]; 8 | if(str != "+" && str != "-" && str != "*" && str != "/")s.push(stoi(str)); 9 | else 10 | { 11 | int c,ans = 0; 12 | if(!s.empty()){ 13 | c = s.top(); 14 | s.pop(); 15 | if(str == "+")ans=c+s.top(); 16 | else if(str == "-")ans=s.top()-c; 17 | else if(str == "*")ans=c*s.top(); 18 | else if(str == "/")ans=s.top()/c; 19 | s.pop(); 20 | s.push(ans); 21 | } 22 | } 23 | } 24 | return s.top(); 25 | } 26 | -------------------------------------------------------------------------------- /Bit Manipulation/10. Powerset.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | 6 | void subsets(string s,int l,int r,vector&v,string s1=""){ 7 | if(l>r){string s2=string(s1.rbegin(),s1.rend()); if(s2.size())v.push_back(s2); return ;} 8 | subsets(s,l+1,r,v,s[l]+s1); 9 | subsets(s,l+1,r,v,s1); 10 | } 11 | class Solution{ 12 | public: 13 | vector AllPossibleStrings(string s){ 14 | // Code here 15 | vectorv; 16 | subsets(s,0,s.size()-1,v); 17 | sort(v.begin(),v.end()); 18 | return v; 19 | } 20 | }; 21 | 22 | // { Driver Code Starts. 23 | int main(){ 24 | int tc; 25 | cin >> tc; 26 | while(tc--){ 27 | string s; 28 | cin >> s; 29 | Solution ob; 30 | vector res = ob.AllPossibleStrings(s); 31 | for(auto i : res) 32 | cout << i <<" "; 33 | cout << "\n"; 34 | 35 | } 36 | return 0; 37 | -------------------------------------------------------------------------------- /Linked list/35. Sort List.cpp: -------------------------------------------------------------------------------- 1 | ListNode* merge(ListNode *left, ListNode *right) { 2 | ListNode *cur = nullptr; 3 | if(!left) return right; 4 | if(!right) return left; 5 | if(left->val < right->val) { 6 | cur = left; 7 | cur->next = merge(left->next, right); 8 | } else { 9 | cur = right; 10 | cur->next = merge(left, right->next); 11 | } 12 | return cur; 13 | } 14 | ListNode* sortList(ListNode* head) { 15 | if(!head || !head->next) return head; 16 | // split the list into two parts 17 | ListNode *slow = head, *fast = head->next; 18 | while(fast && fast->next) { 19 | slow = slow->next; 20 | fast = fast->next->next; 21 | } 22 | ListNode *second = slow->next; 23 | slow->next = NULL; 24 | // sort the two parts 25 | ListNode *l1 = sortList(head); 26 | ListNode *l2 = sortList(second); 27 | // merge the two parts 28 | return merge(l1, l2); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Sliding Window/6. count the no of subarrays in given range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long count(vector&a,long long x) 4 | { 5 | long long start = 0,sum = 0,ct = 0; 6 | for(int end = 0; end < a.size(); end++) 7 | { 8 | sum += a[end]; 9 | while(start <= end && sum > x) 10 | { 11 | sum -= a[start]; 12 | start++; 13 | } 14 | 15 | ct += (end-start+1); 16 | } 17 | return ct; 18 | } 19 | long long countSubarray(int N,vector A,long long L,long long R) { 20 | // code here 21 | long long l_count = count(A,L-1); //count no.of subarrays having sum less than L in O(n) time 22 | long long r_count = count(A,R); //simliarly for R 23 | return r_count - l_count; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic_programming/Grid/Min_falling_path_sum_2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[201][201]; 4 | int fun(int i, int j, vector>&grid){ 5 | /*boundaries*/ 6 | if(i >= grid.size())return 0; 7 | /*already calculated optimizing*/ 8 | if(dp[i][j] != -1)return dp[i][j]; 9 | /*min of all possibilties*/ 10 | int ans = INT_MAX; 11 | for(int k = 0; k < grid.size(); k++){ 12 | if(k != j)ans = min(ans, grid[i][j] + fun(i+1, k, grid)); 13 | } 14 | 15 | return dp[i][j] = ans; 16 | } 17 | int minFallingPathSum(vector>& grid) { 18 | int ans = INT_MAX; 19 | if(grid.size() == 1)return grid[0][0]; 20 | memset(dp, -1, sizeof(dp)); 21 | for(int i = 0; i < grid.size(); i++){ 22 | ans = min(ans, fun(0, i, grid)); 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Graph/1. Steps by Knight.cpp: -------------------------------------------------------------------------------- 1 | int minStepToReachTarget(vector&KnightPos,vector&TargetPos,int N) 2 | { 3 | // Code here 4 | int X[] = {1, 2, 1, 2, -1, -2, -1, -2}; 5 | int Y[] = {2, 1, -2, -1, 2, 1, -2, -1}; 6 | int dp[N+1][N+1]; 7 | memset(dp, -1, sizeof(dp)); 8 | queue>q; 9 | q.push({KnightPos[0], KnightPos[1]}); 10 | dp[KnightPos[0]][KnightPos[1]] = 0; 11 | while(!q.empty()) 12 | { 13 | int i = q.front().first; 14 | int j = q.front().second; 15 | q.pop(); 16 | for(int k = 0; k < 8; k++) 17 | { 18 | int x = i + X[k]; 19 | int y = j + Y[k]; 20 | if(x < 1 || y < 1 || x > N || y > N || dp[x][y] != -1)continue; 21 | dp[x][y] = dp[i][j] + 1; 22 | q.push({x,y}); 23 | } 24 | } 25 | return dp[TargetPos[0]][TargetPos[1]]; 26 | } 27 | -------------------------------------------------------------------------------- /Linked list/9. Add two nums LL.cpp: -------------------------------------------------------------------------------- 1 | */ 2 | class Solution { 3 | public: 4 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 5 | int carry = 0; 6 | ListNode* ans = NULL, *travel = NULL; 7 | while(l1 || l2 || carry){ 8 | int sum = 0; 9 | if(l1){ 10 | sum += l1->val; 11 | l1 = l1->next; 12 | } 13 | if(l2){ 14 | sum += l2->val; 15 | l2 = l2->next; 16 | } 17 | sum += carry; 18 | carry = sum / 10; 19 | ListNode* tmp = new ListNode(sum % 10); 20 | if(!ans){ 21 | ans = tmp; 22 | travel = tmp; 23 | } 24 | else{ 25 | travel->next = tmp; 26 | travel = travel->next; 27 | } 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Stack/18. Minimum remove to make valid parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minRemoveToMakeValid(string s) { 4 | string ans; 5 | int count = 0; 6 | /*right balancing*/ 7 | for(int i = 0; i < s.size(); i++){ 8 | if(s[i] == '(')count++; 9 | else if(s[i] == ')'){ 10 | if(count == 0)s[i] = '#'; 11 | else count--; 12 | } 13 | } 14 | count = 0; 15 | /*left balancing */ 16 | for(int i = s.size()-1; i >= 0; i--){ 17 | if(s[i] == ')')count++; 18 | else if(s[i] == '('){ 19 | if(count == 0)s[i] = '#'; 20 | else count--; 21 | } 22 | } 23 | 24 | for(int i = 0; i < s.size(); i++){ 25 | if(s[i] != '#')ans.push_back(s[i]); 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Searching Sorting/17. merging overlap intervals.cpp: -------------------------------------------------------------------------------- 1 | //Intervals = {{1,3},{2,4},{6,8},{9,10}} 2 | //Output: {{1, 4}, {6, 8}, {9, 10}} 3 | 4 | 5 | // Intervals = {{6,8},{1,9},{2,4},{4,7}} 6 | // Output: {{1, 9}} 7 | class Solution { 8 | public: 9 | vector> overlappedInterval(vector>& intervals) { 10 | vector>ans; 11 | if(intervals.size() == 0) 12 | return ans; 13 | sort(intervals.begin(), intervals.end()); 14 | int l = intervals[0][0]; 15 | int r = intervals[0][1]; 16 | for(int i = 1; i < intervals.size(); i++){ 17 | if(r >= intervals[i][0])r = max(r, intervals[i][1]); 18 | else{ 19 | ans.push_back({l,r}); 20 | l = intervals[i][0]; 21 | r = intervals[i][1]; 22 | } 23 | } 24 | ans.push_back({l,r}); 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /Mathematical/25. Cows of foo land.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | void multiply(long long int mat[2][2],long long int m[2][2]) 4 | { 5 | long long int a,b,c,d; 6 | a=(mat[0][0]*m[0][0]+mat[0][1]*m[1][0])%1000000007; 7 | b=(mat[0][0]*m[0][1]+mat[0][1]*m[1][1])%1000000007; 8 | c=(mat[1][0]*m[0][0]+mat[1][1]*m[1][0])%1000000007; 9 | d=(mat[1][0]*m[0][1]+mat[1][1]*m[1][1])%1000000007; 10 | mat[0][0]=a; 11 | mat[0][1]=b; 12 | mat[1][0]=c; 13 | mat[1][1]=d; 14 | 15 | } 16 | void mat_power(long long int mat[2][2],long long int n) 17 | { 18 | if(n==1)return; 19 | mat_power(mat,n/2); 20 | multiply(mat,mat); 21 | long long int m[2][2]={{1,1},{1,0}}; 22 | if(n%2!=0)multiply(mat,m); 23 | } 24 | int TotalAnimal(long long int N){ 25 | // Code here 26 | long long int mat[2][2]={{1,1},{1,0}}; 27 | mat_power(mat,N+1); 28 | return mat[0][1]; 29 | } 30 | -------------------------------------------------------------------------------- /Mathematical/29. Fraction to recurring decimal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string fractionToDecimal(int numerator, int denominator) { 4 | string ans; 5 | mapm; 6 | long long nm=numerator,dm=denominator; 7 | if(numerator==denominator)return "1"; 8 | if((nm>0&&dm<0)||(nm<0&&dm>0))ans+='-'; 9 | nm=abs(nm); 10 | dm=abs(dm); 11 | ans+=to_string(nm/dm); 12 | nm%=dm; 13 | if(nm>0)ans+='.'; 14 | while(nm>0) 15 | { 16 | if(m.find(nm)!=m.end()) 17 | { 18 | ans=ans.substr(0,m[nm])+"("+ans.substr(m[nm])+")"; 19 | break; 20 | } 21 | m[nm]=ans.size(); 22 | nm*=10; 23 | ans+=to_string(nm/dm); 24 | nm%=dm; 25 | 26 | } 27 | 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Binary Trees/2. Preorder traversal.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { //Recursive 3 | public: 4 | vectorv; 5 | vector preorderTraversal(TreeNode* root) { 6 | if(root){ 7 | v.push_back(root->val); 8 | preorderTraversal(root->left); 9 | preorderTraversal(root->right); 10 | } 11 | return v; 12 | } 13 | 14 | class Solution{ //Iterative 15 | public: 16 | vector preOrder(Node* root) 17 | { 18 | //code here 19 | stacks; 20 | vectorv; 21 | s.push(root); 22 | while(!s.empty()) 23 | { 24 | Node* x=s.top(); 25 | s.pop(); 26 | v.push_back(x->data); 27 | if(x->right)s.push(x->right); 28 | if(x->left)s.push(x->left); 29 | 30 | } 31 | return v; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Priority Queue/8. Task Scheduler.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int leastInterval(vector& tasks, int n) { 4 | if(n == 0)return tasks.size(); 5 | int ans = 0; 6 | priority_queuepq; 7 | unordered_mapm; 8 | for(auto x: tasks)m[x]++; 9 | for(auto x: m)pq.push(x.second); 10 | while(!pq.empty()) 11 | { 12 | vectortmp; 13 | for(int i = 0; i <= n; i++) 14 | { 15 | if(!pq.empty()) 16 | { 17 | tmp.push_back(pq.top()); 18 | pq.pop(); 19 | } 20 | } 21 | for(auto x: tmp) 22 | { 23 | if(--x > 0)pq.push(x); 24 | } 25 | 26 | ans += (pq.empty()? tmp.size(): n+1); 27 | } 28 | return ans; 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Stack/5. Balanced paranthesis.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | if(s.size() % 2 != 0)return false; //Base case 1 5 | if(s[0] == ')' || s[0] == '}' || s[0] == ']')return false; //Base case 2 6 | stackst; 7 | for(int i = 0; i < s.size(); i++) 8 | { 9 | if(s[i] == '(' || s[i] == '{' || s[i] == '[' )st.push(s[i]); 10 | else 11 | { 12 | if(st.size() > 0) 13 | { 14 | char tmp; 15 | if(s[i] == ')')tmp = '('; 16 | else if(s[i] == '}')tmp = '{'; 17 | else if(s[i] == ']')tmp = '['; 18 | if(tmp != st.top())return false; 19 | st.pop(); 20 | } 21 | else return false; 22 | } 23 | } 24 | return st.size() == 0; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Linked list/2. Reverse LL given size.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | struct node *reverse (struct node *head, int k) 5 | { 6 | // Complete this method 7 | node* curr=head; 8 | node* prev_first=NULL; 9 | bool first_pass=true; 10 | while(curr) 11 | { 12 | int tmp=k; 13 | node* first=curr; 14 | node* prev=NULL; 15 | while(curr&&tmp>0) 16 | { 17 | node* next=curr->next; 18 | curr->next=prev; 19 | prev=curr; 20 | curr=next; 21 | tmp--; 22 | } 23 | if(first_pass) 24 | { 25 | head=prev; 26 | first_pass=false; 27 | } 28 | else 29 | { 30 | prev_first->next=prev; 31 | } 32 | prev_first=first; 33 | } 34 | return head; 35 | } 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /Dynamic_programming/5. Integer Break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // long long int tmp = 1, ans = INT_MIN; 4 | // void fun(int n, int id) 5 | // { 6 | // if(n < 0)return; 7 | // else if(n == 0) 8 | // { 9 | // ans = max(ans,tmp); 10 | // } 11 | // for(int i = id; i >= 1; i--) 12 | // { 13 | // tmp *= i; 14 | // fun(n - i,i); 15 | // tmp /= i; 16 | // } 17 | 18 | // } 19 | // fun(n,n-1); 20 | 21 | int integerBreak(int n) { 22 | vectordp(n+1,1); 23 | for(int i = 2; i <= n;i++) 24 | { 25 | for(int j = 1; j <= i;j++) 26 | { 27 | if(j != n) 28 | { 29 | dp[i] = max(dp[i], dp[i-j]*j); 30 | } 31 | 32 | } 33 | } 34 | return dp[n]; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Graph/9. Transitive closure of a graph.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public: 4 | void travel(int src, vectoradj[], vector&visited){ 5 | visited[src] = 1; 6 | for(auto x: adj[src]){ 7 | if(!visited[x]){ 8 | travel(x, adj, visited); 9 | } 10 | } 11 | } 12 | vector> transitiveClosure(int N, vector> graph) 13 | { 14 | // code here 15 | vectoradj[N]; 16 | for(int i = 0; i < N; i++){ 17 | for(int j = 0; j < N; j++){ 18 | if(graph[i][j] == 1)adj[i].push_back(j); 19 | } 20 | } 21 | for(int i = 0; i < N; i++){ 22 | vectorvisited(N, 0); 23 | travel(i, adj, visited); 24 | for(int j = 0; j < N; j++){ 25 | if(visited[j])graph[i][j] = 1; 26 | } 27 | } 28 | return graph; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Mathematical/6. Count no of triangles.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of the above approach 2 | #include 3 | using namespace std; 4 | 5 | void CountTriangles(vector A) 6 | { 7 | 8 | int n = A.size(); 9 | 10 | sort(A.begin(), A.end()); 11 | 12 | int count = 0; 13 | 14 | for (int i = n - 1; i >= 1; i--) { 15 | int l = 0, r = i - 1; 16 | while (l < r) { 17 | if (A[l] + A[r] > A[i]) { 18 | 19 | // If it is possible with a[l], a[r] 20 | // and a[i] then it is also possible 21 | // with a[l+1]..a[r-1], a[r] and a[i] 22 | count += r - l; 23 | 24 | // checking for more possible solutions 25 | r--; 26 | } 27 | else 28 | 29 | // if not possible check for 30 | // higher values of arr[l] 31 | l++; 32 | } 33 | } 34 | cout << "No of possible solutions: " << count; 35 | } 36 | int main() 37 | { 38 | 39 | vector A = { 4, 3, 5, 7, 6 }; 40 | 41 | CountTriangles(A); 42 | } 43 | -------------------------------------------------------------------------------- /Binary Trees/1. Inorder traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vectorv; 4 | vector inorderTraversal(TreeNode* root) { 5 | if(root){ 6 | inorderTraversal(root->left); 7 | v.push_back(root->val); 8 | inorderTraversal(root->right); 9 | } 10 | return v; 11 | } 12 | }; 13 | 14 | // iterative solution 15 | class Solution { 16 | public: 17 | vector inOrder(Node* root) 18 | { 19 | //code here 20 | stacks; 21 | vectorv; 22 | Node* curr=root; 23 | while(!s.empty()||curr) 24 | { 25 | if(curr) 26 | { 27 | s.push(curr); 28 | curr=curr->left; 29 | } 30 | else 31 | {curr=s.top(); 32 | v.push_back(curr->data); 33 | s.pop(); 34 | curr=curr->right; 35 | }} 36 | return v; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Mathematical/2. Num of ways to reach Nth way.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | 6 | class Solution 7 | { 8 | public: 9 | //Function to count number of ways to reach the nth stair in which order is imp, otherwise return (1+n/2) 10 | int countWays(int n) 11 | { 12 | // your code here 13 | long long int v[n+1]={0}; 14 | v[0]=1; 15 | v[1]=1; 16 | for(long long int i=2;i<=n;i++)v[i]=(v[i-1]+v[i-2])%1000000007; 17 | return v[n]; 18 | } 19 | }; 20 | 21 | 22 | 23 | // { Driver Code Starts. 24 | int main() 25 | { 26 | //taking total testcases 27 | int t; 28 | cin >> t; 29 | while(t--) 30 | { 31 | //taking stair count 32 | int m; 33 | cin>>m; 34 | Solution ob; 35 | cout<> insert(vector>& intervals, vector& newInterval) { 4 | vector>ans; 5 | int n = intervals.size(),i = 0; 6 | while(i < n && intervals[i][1] < newInterval[0])ans.push_back(intervals[i++]); //directly inserting elements less than newInterval range 7 | 8 | int start = newInterval[0]; 9 | int end = newInterval[1]; 10 | for(i; i < n && intervals[i][0] <= newInterval[1]; i++) //merging overlap intervals into single intervals 11 | { 12 | start = min(start, intervals[i][0]); 13 | end = max(end, intervals[i][1]); 14 | } 15 | ans.push_back({start,end}); 16 | 17 | while(i < n)ans.push_back(intervals[i++]); //directly inserting elements greater than newInterval range 18 | return ans; 19 | } 20 | }; 21 | 22 | 23 | -------------------------------------------------------------------------------- /String/38. Robot bounded in a circle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isRobotBounded(string instructions) { 4 | int i = 0, j = 0; 5 | int dir = 1; 6 | for(auto x: instructions){ 7 | if(x == 'L'){ 8 | if(dir == 1){ 9 | dir = 5; 10 | } 11 | dir--; 12 | } 13 | else if(x == 'R'){ 14 | if(dir == 4){ 15 | dir = 0; 16 | } 17 | dir++; 18 | } 19 | else{ 20 | if(dir == 1)j += 1; 21 | else if(dir == 4)i -= 1; 22 | else if(dir == 3)j -= 1; 23 | else if(dir == 2)i += 1; 24 | } 25 | } 26 | if(dir != 1 || (i == 0 and j == 0))return true; 27 | return false; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Dynamic_programming/12_1. Unique Path 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 4 | int m = obstacleGrid.size(), n = obstacleGrid[0].size(); 5 | if(obstacleGrid[0][0] == 1)return 0; 6 | obstacleGrid[0][0] = 1; 7 | for(int i = 1;i < m;i++) 8 | { 9 | obstacleGrid[i][0] = obstacleGrid[i][0] == 1? 0 :obstacleGrid[i-1][0]; 10 | } 11 | 12 | for(int i = 1; i < n; i++) 13 | { 14 | obstacleGrid[0][i] = obstacleGrid[0][i] == 1? 0: obstacleGrid[0][i-1]; 15 | } 16 | 17 | for(int i = 1; i < m; i++) 18 | { 19 | for(int j = 1; j < n; j++) 20 | { 21 | obstacleGrid[i][j] = obstacleGrid[i][j] == 1? 0: obstacleGrid[i-1][j] + obstacleGrid[i][j-1]; 22 | } 23 | } 24 | return obstacleGrid[m-1][n-1]; 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Mathematical/9. Overlapping rectangles.cpp: -------------------------------------------------------------------------------- 1 | // Initial Template for C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | 9 | class Solution { 10 | public: 11 | int doOverlap(int L1[], int R1[], int L2[], int R2[]) { 12 | // code here 13 | if(L1[0]==R1[0] || L1[1]==R1[1] || L2[0]==R2[0]|| L2[1]==R2[1])return 0; //the line can't have +ve overlap 14 | if(L1[0]>=R2[0] || L2[0]>=R1[0])return 0; //left side 15 | if(L1[1]<=R2[1] || L2[1]<=R1[1])return 0; //above other 16 | return 1; 17 | } 18 | 19 | }; 20 | 21 | // { Driver Code Starts. 22 | 23 | int main() { 24 | int t; 25 | cin >> t; 26 | while (t--) { 27 | int p[2], q[2], r[2], s[2]; 28 | cin >> p[0] >> p[1] >> q[0] >> q[1] >> r[0] >> r[1] >> s[0] >> s[1]; 29 | Solution ob; 30 | int ans = ob.doOverlap(p, q, r, s); 31 | cout << ans << "\n"; 32 | } 33 | -------------------------------------------------------------------------------- /Array/Easy Ques/Common_elements_three_arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution 4 | { 5 | public: 6 | vector commonElements (int A[], int B[], int C[], int n1, int n2, int n3) 7 | { 8 | //code here. 9 | int i,j,k,l=0; 10 | vectorv(n1+n2+n3); 11 | for(i = 0,j = 0; i < n1; i++)if(A[i] != A[j]){ A[++j] = A[i];}n1=j+1; 12 | for(i = 0,j = 0; i < n2; i++)if(B[i] != B[j]){ B[++j] = B[i];}n2=j+1; 13 | for(i = 0,j = 0; i < n3; i++)if(C[i] != C[j]){ C[++j] = C[i];}n3=j+1; 14 | i = 0; j = 0; k = 0; 15 | while(i < n1 && j < n2 && k < n3){ 16 | if(A[i] == B[j] && B[j] == C[k]){v[l++] = A[i]; i++; j++; k++;} 17 | else if(A[i] < B[j])i++; 18 | else if(B[j] < C[k])j++; 19 | else k++; 20 | } 21 | v.resize(l); 22 | return v; 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /Binary Trees/35. Vertical Traversal of tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find the vertical order traversal of Binary Tree. 5 | vector verticalOrder(Node *root) 6 | { 7 | //Your code here 8 | vectorans; 9 | map>m; //idea for storing 10 | queue>q; 11 | q.push({root,0}); //for storing root values for particular vertical lines identification purpose 12 | while(!q.empty()) 13 | { 14 | Node *t=q.front().first; 15 | int d=q.front().second; 16 | q.pop(); 17 | m[d].push_back(t->data); //stores values according to that vertical lines 18 | if(t->left)q.push({t->left,d-1}); 19 | if(t->right)q.push({t->right,d+1}); 20 | } 21 | for(auto x:m) 22 | { 23 | for(auto y:x.second)ans.push_back(y); 24 | } 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /Bit Manipulation/2. Two non repeating.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | class Solution 6 | { 7 | public: 8 | vector singleNumber(vector nums) 9 | { 10 | // Code here. 11 | unordered_mapm; 12 | int i,j,k; 13 | vectorv; 14 | for(i=0;i> T; 25 | while(T--) 26 | { 27 | int n; 28 | cin >> n; 29 | vector v(2 * n + 2); 30 | for(int i = 0; i < 2 * n + 2; i++) 31 | cin >> v[i]; 32 | Solution ob; 33 | vector ans = ob.singleNumber(v); 34 | for(auto i: ans) 35 | cout << i << " "; 36 | cout << "\n"; 37 | } 38 | return 0; 39 | -------------------------------------------------------------------------------- /Dynamic_programming/4. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int numSquares(int n) { 5 | 6 | vectorv(n+1,INT_MAX); 7 | v[0] = 0; 8 | for(int i = 1; i <= n ; i++) 9 | { 10 | for(int j = 1; j <= sqrt(i); j++) 11 | { 12 | v[i] = min(v[i] , v[i - j * j] + 1); 13 | } 14 | } 15 | return v[n]; 16 | } 17 | }; 18 | 19 | 20 | //Min No.of coins 21 | int minCoins(int coins[], int M, int V) 22 | { 23 | // Your code goes here 24 | //calculate(coins,M,V); 25 | vectordp(V+1,1e9); 26 | dp[0] = 0; 27 | for(int i = 1;i <= V; i++) 28 | { 29 | for(int j = 0; j < M; j++) 30 | { 31 | if(i >= coins[j]) 32 | { 33 | dp[i] = min(dp[i], 1+dp[i-coins[j]]); 34 | } 35 | } 36 | } 37 | return dp[V] == 1e9? -1: dp[V]; 38 | } 39 | 40 | }; 41 | -------------------------------------------------------------------------------- /Graph/22. course schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector findOrder(int n, int m, vector> prerequisites) 5 | { 6 | //code here 7 | vectorgraph[n]; 8 | vectorindeg(n), ans; 9 | for(int i = 0; i < m; i++){ 10 | graph[prerequisites[i][1]].push_back(prerequisites[i][0]); 11 | indeg[prerequisites[i][0]]++; 12 | } 13 | queueq; 14 | for(int i = 0; i < n; i++){ 15 | if(indeg[i] == 0)q.push(i); 16 | } 17 | if(q.size() == 0)return ans; //base case 18 | while(!q.empty()){ 19 | int curr = q.front(); 20 | q.pop(); 21 | ans.push_back(curr); 22 | for(auto x: graph[curr]){ 23 | indeg[x]--; 24 | if(indeg[x] == 0)q.push(x); 25 | } 26 | } 27 | if(ans.size() == n)return ans; 28 | return { }; 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Mathematical/15. No of 1s in smallest repunit.cpp: -------------------------------------------------------------------------------- 1 | // Initial Template for C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | 9 | class Solution{ 10 | public: 11 | int repUnit(int N){ 12 | // code here 13 | int count = 1; 14 | 15 | // initialize rem with 1 16 | int rem = 1; 17 | 18 | // run loop until rem becomes zero 19 | while (rem != 0) { 20 | 21 | // rem*10 + 1 here represents 22 | // the repunit modulo n 23 | rem = (rem * 10 + 1) % N; 24 | count++; 25 | } 26 | 27 | // when remainder becomes 0 28 | // return count 29 | return count;} 30 | }; 31 | 32 | // { Driver Code Starts. 33 | 34 | int main(){ 35 | int t; 36 | cin>>t; 37 | while(t--){ 38 | int N; 39 | cin>>N; 40 | 41 | Solution ob; 42 | cout<next; 10 | curr->next=prev; 11 | prev=curr; 12 | curr=next; 13 | } 14 | return prev; 15 | } 16 | Node *compute(Node *head) 17 | { 18 | // your code goes here 19 | head=reverse(head); 20 | Node* h=head; 21 | Node* curr=h,*tmp=h->next; 22 | while(tmp) 23 | { 24 | if(curr->data>tmp->data){ 25 | Node* d=tmp; 26 | tmp=tmp->next; 27 | curr->next=tmp; 28 | free(d); 29 | } 30 | else{ 31 | curr=curr->next; 32 | tmp=tmp->next; 33 | } 34 | } 35 | return reverse(head); 36 | } 37 | 38 | }; 39 | -------------------------------------------------------------------------------- /Graph/29. Path with max probability.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { 4 | vector>adj[n]; 5 | vectorvisited(10000, 0); 6 | for(int i = 0; i < edges.size(); i++){ 7 | adj[edges[i][0]].push_back({edges[i][1], succProb[i]}); 8 | adj[edges[i][1]].push_back({edges[i][0], succProb[i]}); 9 | } 10 | vectorp(n ,0.0); 11 | p[start] = 1.0; 12 | queueq; 13 | q.push(start); 14 | while(!q.empty()){ 15 | int curr = q.front(); 16 | q.pop(); 17 | for(auto x: adj[curr]){ 18 | if(p[x.first] < p[curr] * x.second){ 19 | q.push(x.first); 20 | p[x.first] = p[curr]*x.second; 21 | } 22 | } 23 | } 24 | return p[end]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Samsung R & D/SWC_3RDJULY.txt: -------------------------------------------------------------------------------- 1 | Mr. Sam. Sung Choi has to do a marathon of D distance. He has a max health H. 2 | He can run in 5 different paces. Paces are given as how much minutes and seconds and health 3 | does it require to complete 1km in this pace. 4 | e.g: pace 1: 6 19 16 (mm ss health) 5 | means, if mr. Choi runs in pace 1, it takes 6 mins 19 secs to cover 1km and it costs 6 | a health of 16 units from the total health. 7 | Find the min time required to finish the race. 8 | print the ans in this format: #T mm ss (e.g: #1 137 20) 9 | 10 | Input format: 11 | no of tc: T 12 | distance of marathon: D 13 | Total Health: H 14 | 5 lines each if 3 space separated integers decnoting paces. 15 | 16 | constraints: 17 | 3 <= D <= 40 18 | 10 <= H <= 100 19 | 3 <= minutes <= 6 20 | 0 <= second <= 59 21 | 22 | testcases: 23 | 2 24 | 10 50 25 | 6 19 6 26 | 6 29 5 27 | 6 39 4 28 | 6 49 3 29 | 6 59 2 30 | 600 40 31 | 3 11 20 32 | 3 18 16 33 | 3 36 14 34 | 3 41 13 35 | 3 53 12 =>answer : 137min 11sec for 2nd TC 36 | -------------------------------------------------------------------------------- /Binary Trees/54. Maximum width of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int widthOfBinaryTree(TreeNode* root) { 4 | int width = 0; 5 | queue>q; 6 | q.push({root, 0}); 7 | while(!q.empty()){ 8 | int n = q.size(); 9 | int max_index = INT_MIN, min_index = INT_MAX; 10 | while(n--){ 11 | TreeNode* tmp = q.front().first; 12 | int dist = q.front().second; 13 | q.pop(); 14 | max_index = max(max_index, dist); 15 | min_index = min(min_index, dist); 16 | if(tmp->left){ 17 | q.push({tmp->left, (long long)2 * dist + 1}); 18 | } 19 | if(tmp->right){ 20 | q.push({tmp->right, (long long)2 * dist + 2}); 21 | } 22 | } 23 | width = max(width, max_index - min_index + 1); 24 | } 25 | return width; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Binary Trees/Level order Models/46. Kth distance from root.cpp: -------------------------------------------------------------------------------- 1 | //bfs 2 | vector Kdistance(struct Node *root, int k) 3 | { 4 | // Your code here 5 | queueq; 6 | q.push(root); 7 | vectorv; 8 | int dist = 0; 9 | while(!q.empty()) 10 | { 11 | int size = q.size(); 12 | while(size--) 13 | { 14 | Node* x = q.front(); 15 | q.pop(); 16 | if(x->left)q.push(x->left); 17 | if(x->right)q.push(x->right); 18 | if(dist == k)v.push_back(x->data); 19 | } 20 | dist++; 21 | } 22 | return v; 23 | 24 | } 25 | 26 | //dfs 27 | int distance(vector v,Node* root,int k){ 28 | if(root==NULL){ 29 | return 0; 30 | } 31 | if(k == 0){ 32 | v.push_back(root->data); 33 | } 34 | distance(v,root->left,k-1); 35 | distance(v,root->right,k-1); 36 | } 37 | vector Kdistance(struct Node *root, int k) 38 | { 39 | vector v; 40 | distance(v,root,k); 41 | return v; 42 | } 43 | --------------------------------------------------------------------------------