├── .gitattributes ├── .vscode └── c_cpp_properties.json ├── Day104_Maximum_Candies_Allocated_to_K_Children.cpp ├── Day104_Split_Array_Largest_Sum.cpp ├── Day105_Maximum_Candies_Allocated_to_K_Children.cpp ├── Day10_Convert_the_Temperature.cpp ├── Day114_Median_of_Two_Sorted_Arrays.cpp ├── Day119_Row_With_Maximum_Ones.cpp ├── Day120_Search_a_2D_Matrix_II.cpp ├── Day121_Find_a_Peak_Element.cpp ├── Day14_Frequency_of_the_Most_Frequent_Element.cpp ├── Day164_Maximum_Depth_of_Binary_Tree.cpp ├── Day165_Balanced_Binary_Tree.cpp ├── Day166_Binary_Tree_Inorder_Traversal.cpp ├── Day166_Binary_Tree_Level_Order_Traversal.cpp ├── Day166_Binary_Tree_Postorder_Traversal.cpp ├── Day166_Binary_Tree_Preorder_Traversal.cpp ├── Day166_Diameter_of_Binary_Tree.cpp ├── Day168_Balanced_Tree_Check.cpp ├── Day168_Binary_Tree_Maximum_Path_Sum.cpp ├── Day168_Binary_Tree_Zigzag_Level_Order_Traversa.cpp ├── Day168_Diameter_of_a_Binary_Tree.cpp ├── Day168_Height_of_Binary_Tree.cpp ├── Day168_Maximum_path_sum_from_any_node.cpp ├── Day168_Same_Tree.cpp ├── Day169_Vertical_Order_Traversal_of_a_Binary_Tree.cpp ├── Day170_Binary_Tree_Right_Side_View.cpp ├── Day170_Symmetric_Tree.cpp ├── Day171_Binary_Tree_Paths.cpp ├── Day173_Lowest_Common_Ancestor_of_a_Binary_Tree.cpp ├── Day177_Maximum_Width_of_Binary_Tree.cpp ├── Day178_Root_Equals_Sum_of_Children.cpp ├── Day179_All_Nodes_Distance_K_in_Binary_Tree.cpp ├── Day179_Amount_of_Time_for_Binary_Tree_to_Be_Infected.cpp ├── Day180_Count_Complete_Tree_Nodes.cpp ├── Day191_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp ├── Day199_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.cpp ├── Day226_Serialize_and_Deserialize_Binary_Tree.cpp ├── Day227_Flatten_Binary_Tree_to_Linked_List.cpp ├── Day227_Search_in_a_Binary_Search_Tree.cpp ├── Day228_Delete_Node_in_a_BST.cpp ├── Day229_Kth_Smallest_Element_in_a_BST.cpp ├── Day229_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp ├── Day229_Validate_Binary_Search_Tree.cpp ├── Day230_Binary_Search_Tree_Iterator.cpp ├── Day230_Construct_Binary_Search_Tree_from_Preorder_Traversal.cpp ├── Day230_Two_Sum_IV_nput_is_a_BST.cpp ├── Day231_Recover_Binary_Search_Tree.cpp ├── Day236_Count_the_Number_of_Complete_Components.cpp ├── Day236_Number_of_Islands.cpp ├── Day236_Number_of_Provinces.cpp ├── Day237_Flood_Fill.cpp ├── Day237_Rotting_Oranges.cpp ├── Day239_01_Matrix.cpp ├── Day239_Map_of_Highest_Peak.cpp ├── Day239_Surrounded_Regions.cpp ├── Day240_Number_of_Enclaves.cpp ├── Day241_Course_Schedule_II.cpp ├── Day241_Is_Graoh_Bipartite_DFS.cpp ├── Day241_Is_Graph_Bipartite.cpp ├── Day243_Find_Eventual_Safe_States.cpp ├── Day260_Course_Schedule_I.cpp ├── Day260_Course_Schedule_II.cpp ├── Day262_Find_Eventual_Safe_States.cpp ├── Day264_Word_Ladder.cpp ├── Day266_Word_Ladder_II.cpp ├── Day268_Shortest_Path_in_Binary_Matrix.cpp ├── Day271_Path_With_Minimum_Effort.cpp ├── Day272_Cheapest_Flights_Within_K_Stops.cpp ├── Day286_Number_of_Ways_to_Arrive_at_Destination.cpp ├── Day287_Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance.cpp ├── Day313_Number of_Operations_to_Make_Network_Connected.cpp ├── Day313_Number_of_Provinces.cpp ├── Day314_Accounts_Merge.cpp ├── Day316_Making_A_Large_Island.cpp ├── Day318_Most_Stones_Removed_with_Same_Row_or_Column.cpp ├── Day322_Critical_Connections_in_a_Network.cpp ├── Day327_Network_Delay_Time.cpp ├── Day35_Check_if_Array_Is_Sorted_and_Rotated.cpp ├── Day35_Remove_Duplicates_from_Sorted_Array.cpp ├── Day35_Rotate_Array.cpp ├── Day36_Move_Zeros.cpp ├── Day40_Max_Consecutive_Ones.cpp ├── Day40_Missing_Number.cpp ├── Day42_Single_Number.cpp ├── Day46_Two_Sum.cpp ├── Day47_Sort_Colours.cpp ├── Day49_Majority_element.cpp ├── Day51_Best_Time_to_Buy_and_Sell_Stock_Solved.cpp ├── Day51_Maximum_Subarray.cpp ├── Day52_Rearrange_Array_Elements_by_Sign.cpp ├── Day53_Longest_Consecutive_Sequence.cpp ├── Day53_Next_Permutation.cpp ├── Day53_Replace_Elements_with_Greatest_Element_on_Right_Side.cpp ├── Day54_Rotate_Image.cpp ├── Day54_Set_Matrix_Zeroes.cpp ├── Day55_Spiral_Matrix.cpp ├── Day55_Subarray_Sum_Equals_K.cpp ├── Day56_Pascal's_Triangle.cpp ├── Day56_Pascal_Triangle.cpp ├── Day57_3Sum.cpp ├── Day57_4_Sum.cpp ├── Day57_Majority_element_2.cpp ├── Day58_Count_the_Number_of_Beautiful_Subarrays.cpp ├── Day58_Merge_Intervals.cpp ├── Day59_Merge_Sorted_Array.cpp ├── Day60_Count_of_Smaller_Numbers_After_Self.cpp ├── Day60_Find_All_Duplicates_in_an_Array.cpp ├── Day60_Find_All_Numbers_Disappeared_in_an_Array.cpp ├── Day60_Find_Missing_and_Repeated_Values.cpp ├── Day60_Find_the_Duplicate_Number.cpp ├── Day60_Maximum_Product_Subarray.cpp ├── Day60_Reverse_Pairs.cpp ├── Day65_Search_a_2D_Matrix.cpp ├── Day66_Binary_Search.cpp ├── Day73_Search_Insert_Position.cpp ├── Day74_Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp ├── Day77_Search_in_Rotated_Sorted_Array.cpp ├── Day79_Search_in_Rotated_Sorted_Array_II.cpp ├── Day83_Find_Minimum_in_Rotated_Sorted_Array.cpp ├── Day86_Single_Element_in_a_Sorted_Array.cpp ├── Day8_Reverse_integer.cpp ├── Day8_palindrome_number.cpp ├── Day90_Find_Peak_Element.cpp ├── Day90_Find_the_Key_of_the_Numbers.cpp ├── Day91_Pow(x, n).cpp ├── Day92_Sqrt(x).cpp ├── Day93_Koko_Eating_Bananas.cpp ├── Day94_Minimum_Number_of_Days_to_Make_m_Bouquets.cpp ├── Day95_Find_the_Smallest_Divisor_Given_a_Threshold.cpp ├── Day96_Capacity_To_Ship_Packages_Within_D_Days.cpp ├── Day97_Kth_Missing_Positive_Number.cpp ├── Day9_Fibbonaci_Number.cpp ├── Day9_Valid_Palindrome.cpp ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Win32", 5 | "includePath": [ 6 | "C:\\MinGW\\include" 7 | ], 8 | "defines": [ 9 | "_DEBUG", 10 | "UNICODE", 11 | "_UNICODE" 12 | ], 13 | "windowsSdkVersion": "10.0.22000.0", 14 | "compilerPath": "C:/MinGW/bin/g++.exe", 15 | "cStandard": "c17", 16 | "cppStandard": "c++17", 17 | "intelliSenseMode": "windows-msvc-x64" 18 | } 19 | ], 20 | "version": 4 21 | } -------------------------------------------------------------------------------- /Day104_Maximum_Candies_Allocated_to_K_Children.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossible(long long mid, vector &candies, long long k) { 4 | int n=candies.size(); 5 | long long cnt=0; 6 | for(int i=0 ; i=k; 8 | } 9 | 10 | int maximumCandies(vector& candies, long long k) { 11 | int n=candies.size(); 12 | sort(begin(candies),end(candies)); 13 | long long totSum=accumulate(begin(candies), end(candies), 0ll); 14 | if(totSum &a, int maxSum) { 4 | int n=a.size(); 5 | int partitions=1; 6 | long long subarraySum=0; 7 | for (int i=0; i &a, int k) { 20 | int low=*max_element(a.begin(), a.end()); 21 | int high=accumulate(a.begin(), a.end(), 0); 22 | //Apply binary search: 23 | while (low<=high) { 24 | int mid=(low+high)/2; 25 | int partitions=countPartitions(a, mid); 26 | if (partitions>k) low=mid+1; 27 | else high=mid-1; 28 | } 29 | return low; 30 | } 31 | }; -------------------------------------------------------------------------------- /Day105_Maximum_Candies_Allocated_to_K_Children.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossible(long long mid, vector &candies, long long k) { 4 | int n=candies.size(); 5 | long long cnt=0; 6 | for(int i=0 ; i=k; 8 | } 9 | 10 | int maximumCandies(vector& candies, long long k) { 11 | int n=candies.size(); 12 | sort(begin(candies),end(candies)); 13 | long long totSum=accumulate(begin(candies), end(candies), 0ll); 14 | if(totSum convertTemperature(double celsius) { 4 | vector ans; 5 | double Kelvin = celsius + 273.15; 6 | double Fahrenheit = (celsius*1.80) + 32.00; 7 | 8 | ans.push_back(Kelvin); 9 | ans.push_back(Fahrenheit); 10 | return ans; 11 | } 12 | }; -------------------------------------------------------------------------------- /Day114_Median_of_Two_Sorted_Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& a, vector& b) { 4 | // size of two given arrays: 5 | int n1=a.size(), n2=b.size(); 6 | int n=n1+n2; 7 | 8 | // required indices: 9 | int ind2=n/2; 10 | int ind1=ind2-1; 11 | int cnt=0; 12 | int ind1el=-1, ind2el=-1; 13 | 14 | //apply the merge step: 15 | int i=0,j=0; 16 | while (i rowAndMaximumOnes(vector>& mat) { 4 | vectoranswer; 5 | answer.push_back(0); 6 | answer.push_back(0); 7 | int cnt=0; 8 | 9 | for (int i=0; i< mat.size(); i++) { 10 | for (int j=0; j>& matrix, int target) { 4 | int n=matrix.size(); 5 | int m=matrix[0].size(); 6 | int row=0, col=m-1; 7 | 8 | //traverse the matrix from (0, m-1): 9 | while (row=0) { 10 | if (matrix[row][col]==target) return true; 11 | else if (matrix[row][col] findPeakGrid(vector>& mat) { 4 | int n=mat.size(); 5 | int m=mat[0].size(); 6 | int low=0, high= m-1; 7 | 8 | while(low<=high){ 9 | int maxRow=0; 10 | int midCol=(low+high)>>1; 11 | for(int row=0; row mat[maxRow][midCol]) maxRow = row; 13 | } 14 | 15 | int currElement= mat[maxRow][midCol]; 16 | int leftElement=midCol == 0 ? -1 : mat[maxRow][midCol-1]; 17 | int rightElement=midCol == m-1 ? -1 : mat[maxRow][midCol+1]; 18 | 19 | if(currElement>leftElement && currElement>rightElement){ 20 | return {maxRow, midCol}; 21 | } 22 | else if(currElement < leftElement){ 23 | high = midCol - 1; 24 | } 25 | else{ 26 | low = midCol + 1; 27 | } 28 | } 29 | return {-1, -1}; 30 | } 31 | }; -------------------------------------------------------------------------------- /Day14_Frequency_of_the_Most_Frequent_Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | #define ll long long 3 | public: 4 | int maxFrequency(vector& nums, int k) { 5 | sort(nums.begin(), nums.end()); 6 | int l = 0, r = 0; 7 | ll total = 0; 8 | int n = nums.size(); 9 | int ans = INT_MIN; 10 | for (r; r < n; r++) { 11 | total += nums[r]; 12 | while ((ll)(r - l + 1) * nums[r] > total + k) 13 | total -= nums[l++]; 14 | ans = max(ans, (r - l + 1)); 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Day164_Maximum_Depth_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxDepth(TreeNode* root) { 15 | if (root==NULL) return 0; 16 | 17 | int lh = maxDepth(root->left); 18 | int rh = maxDepth(root->right); 19 | return max(lh, rh)+1; 20 | } 21 | }; -------------------------------------------------------------------------------- /Day165_Balanced_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isBalanced(TreeNode* root) { 15 | return dfsHeight(root) != -1; 16 | } 17 | int dfsHeight(TreeNode* root){ 18 | if (root==NULL) return 0; 19 | 20 | int leftHeight = dfsHeight(root->left); 21 | if(leftHeight == -1) return -1; 22 | int rightHeight = dfsHeight(root->right); 23 | if(rightHeight == -1) return -1; 24 | 25 | if (abs(leftHeight - rightHeight) > 1) return -1; 26 | return max(leftHeight, rightHeight)+1; 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /Day166_Binary_Tree_Inorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void Traversal(TreeNode* root, vector &result){ 15 | if (root==NULL) return; 16 | Traversal(root->left, result); 17 | result.push_back(root->val); 18 | Traversal(root->right, result); 19 | } 20 | 21 | vector inorderTraversal(TreeNode* root) { 22 | vector result; 23 | Traversal(root, result); 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day166_Binary_Tree_Level_Order_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> levelOrder(TreeNode* root) { 15 | vector> ans; 16 | if(root==NULL) return ans; 17 | 18 | queue q; 19 | q.push(root); 20 | 21 | while(!q.empty()){ 22 | int size = q.size(); 23 | vector level; 24 | for(int i=0; ileft!=NULL) q.push(root->left); 28 | if(root->right!=NULL) q.push(root->right); 29 | level.push_back(root->val); 30 | } 31 | ans.push_back(level); 32 | } 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /Day166_Binary_Tree_Postorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void Traversal(TreeNode* root, vector &result){ 15 | if (root==NULL) return; 16 | Traversal(root->left, result); 17 | Traversal(root->right, result); 18 | result.push_back(root->val); 19 | } 20 | 21 | vector postorderTraversal(TreeNode* root) { 22 | vector result; 23 | Traversal(root, result); 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day166_Binary_Tree_Preorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void Traversal(TreeNode* root, vector &result){ 15 | if (root==NULL) return; 16 | result.push_back(root->val); 17 | Traversal(root->left, result); 18 | Traversal(root->right, result); 19 | } 20 | 21 | vector preorderTraversal(TreeNode* root) { 22 | vector result; 23 | Traversal(root, result); 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day166_Diameter_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | pair solve(TreeNode* root){ 15 | if(root==NULL) return {0,0}; 16 | 17 | pair left=solve(root->left); 18 | pair right=solve(root->right); 19 | 20 | int height = max(left.first, right.first)+1; 21 | int Maxdiameter = max({left.second, right.second, left.first+right.first}); 22 | return {height, Maxdiameter}; 23 | } 24 | int diameterOfBinaryTree(TreeNode* root) { 25 | pair ans = solve(root); 26 | return ans.second; 27 | } 28 | 29 | // int findDiameter(TreeNode* root, int& maxi) { 30 | // if (root == NULL) return 0; 31 | // int lh = findDiameter(root->left, maxi); 32 | // int rh = findDiameter(root->right, maxi); 33 | // maxi = max(maxi, lh + rh); 34 | // return 1 + max(lh, rh); 35 | // } 36 | // int diameterOfBinaryTree(TreeNode* root) { 37 | // int diameter = 0; 38 | // findDiameter(root, diameter); 39 | // return diameter; 40 | // } 41 | }; -------------------------------------------------------------------------------- /Day168_Balanced_Tree_Check.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | // Tree Node 10 | struct Node { 11 | int data; 12 | Node* left; 13 | Node* right; 14 | }; 15 | 16 | // Utility function to create a new Tree Node 17 | Node* newNode(int val) { 18 | Node* temp = new Node; 19 | temp->data = val; 20 | temp->left = NULL; 21 | temp->right = NULL; 22 | 23 | return temp; 24 | } 25 | 26 | 27 | // Function to Build Tree 28 | Node* buildTree(string str) { 29 | // Corner Case 30 | if (str.length() == 0 || str[0] == 'N') return NULL; 31 | 32 | // Creating vector of strings from input 33 | // string after spliting by space 34 | vector ip; 35 | 36 | istringstream iss(str); 37 | for (string str; iss >> str;) ip.push_back(str); 38 | 39 | // Create the root of the tree 40 | Node* root = newNode(stoi(ip[0])); 41 | 42 | // Push the root to the queue 43 | queue queue; 44 | queue.push(root); 45 | 46 | // Starting from the second element 47 | int i = 1; 48 | while (!queue.empty() && i < ip.size()) { 49 | 50 | // Get and remove the front of the queue 51 | Node* currNode = queue.front(); 52 | queue.pop(); 53 | 54 | // Get the current node's value from the string 55 | string currVal = ip[i]; 56 | 57 | // If the left child is not null 58 | if (currVal != "N") { 59 | 60 | // Create the left child for the current node 61 | currNode->left = newNode(stoi(currVal)); 62 | 63 | // Push it to the queue 64 | queue.push(currNode->left); 65 | } 66 | 67 | // For the right child 68 | i++; 69 | if (i >= ip.size()) break; 70 | currVal = ip[i]; 71 | 72 | // If the right child is not null 73 | if (currVal != "N") { 74 | 75 | // Create the right child for the current node 76 | currNode->right = newNode(stoi(currVal)); 77 | 78 | // Push it to the queue 79 | queue.push(currNode->right); 80 | } 81 | i++; 82 | } 83 | 84 | return root; 85 | } 86 | 87 | 88 | // } Driver Code Ends 89 | /* A binary tree node structure 90 | 91 | struct Node 92 | { 93 | int data; 94 | struct Node* left; 95 | struct Node* right; 96 | 97 | Node(int x){ 98 | data = x; 99 | left = right = NULL; 100 | } 101 | }; 102 | */ 103 | 104 | class Solution{ 105 | public: 106 | //Function to check whether a binary tree is balanced or not. 107 | bool isBalanced(Node* root) { 108 | return dfsHeight(root) != -1; 109 | } 110 | int dfsHeight(Node* root){ 111 | if (root==NULL) return 0; 112 | 113 | int leftHeight = dfsHeight(root->left); 114 | if(leftHeight == -1) return -1; 115 | int rightHeight = dfsHeight(root->right); 116 | if(rightHeight == -1) return -1; 117 | 118 | if (abs(leftHeight - rightHeight) > 1) return -1; 119 | return max(leftHeight, rightHeight)+1; 120 | } 121 | }; 122 | 123 | 124 | //{ Driver Code Starts. 125 | 126 | /* Driver program to test size function*/ 127 | 128 | 129 | 130 | int main() { 131 | 132 | 133 | int t; 134 | scanf("%d ", &t); 135 | while (t--) { 136 | string s, ch; 137 | getline(cin, s); 138 | 139 | Node* root = buildTree(s); 140 | Solution ob; 141 | cout << ob.isBalanced(root) << endl; 142 | 143 | cout << "~" << "\n"; 144 | } 145 | return 0; 146 | } 147 | 148 | // } Driver Code Ends -------------------------------------------------------------------------------- /Day168_Binary_Tree_Maximum_Path_Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxpath(TreeNode* root, int& maxi){ 15 | if(root==NULL) return 0; 16 | 17 | int leftsum = max(0, maxpath(root->left, maxi)); 18 | int rightsum = max(0, maxpath(root->right, maxi)); 19 | 20 | maxi = max(maxi, (leftsum + rightsum + root->val)); 21 | return root->val + max(leftsum, rightsum); 22 | } 23 | 24 | // pair solve(TreeNode* root){ 25 | // if(root==NULL) return {INT_MIN, 0}; 26 | 27 | // pair left=solve(root->left); 28 | // pair right=solve(root->right); 29 | 30 | // if(left.second<0) left.second=0; 31 | // if(right.second<0) right.second=0; 32 | 33 | // return {max({left.first, right.first, (left.second+right.second+root->val)}), max(left.second, right.second) + root->val}; 34 | // } 35 | 36 | int maxPathSum(TreeNode* root) { 37 | int maxi = INT_MIN; 38 | maxpath(root, maxi); 39 | return maxi; 40 | // pair ans=solve(root); 41 | // return ans.first; 42 | } 43 | }; -------------------------------------------------------------------------------- /Day168_Binary_Tree_Zigzag_Level_Order_Traversa.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> zigzagLevelOrder(TreeNode* root) { 15 | vector> result; 16 | if(root==NULL) return result; 17 | 18 | queue nodesQueue; 19 | nodesQueue.push(root); 20 | bool leftToRight=true; 21 | 22 | while(!nodesQueue.empty()){ 23 | int size = nodesQueue.size(); 24 | vector row(size); 25 | for(int i=0; ival; 32 | if(node->left) nodesQueue.push(node->left); 33 | if(node->right) nodesQueue.push(node->right); 34 | } 35 | // after this level 36 | leftToRight = !leftToRight; 37 | result.push_back(row); 38 | } 39 | return result; 40 | } 41 | }; -------------------------------------------------------------------------------- /Day168_Diameter_of_a_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | /* A binary tree node has data, pointer to left child 6 | and a pointer to right child */ 7 | struct Node { 8 | int data; 9 | struct Node* left; 10 | struct Node* right; 11 | }; 12 | Node* newNode(int val) { 13 | Node* temp = new Node; 14 | temp->data = val; 15 | temp->left = NULL; 16 | temp->right = NULL; 17 | return temp; 18 | } 19 | Node* buildTree(string str) { 20 | // Corner Case 21 | if (str.length() == 0 || str[0] == 'N') return NULL; 22 | 23 | // Creating vector of strings from input 24 | // string after spliting by space 25 | vector ip; 26 | 27 | istringstream iss(str); 28 | for (string str; iss >> str;) ip.push_back(str); 29 | 30 | // Create the root of the tree 31 | Node* root = newNode(stoi(ip[0])); 32 | 33 | // Push the root to the queue 34 | queue queue; 35 | queue.push(root); 36 | 37 | // Starting from the second element 38 | int i = 1; 39 | while (!queue.empty() && i < ip.size()) { 40 | 41 | // Get and remove the front of the queue 42 | Node* currNode = queue.front(); 43 | queue.pop(); 44 | 45 | // Get the current node's value from the string 46 | string currVal = ip[i]; 47 | 48 | // If the left child is not null 49 | if (currVal != "N") { 50 | 51 | // Create the left child for the current node 52 | currNode->left = newNode(stoi(currVal)); 53 | 54 | // Push it to the queue 55 | queue.push(currNode->left); 56 | } 57 | 58 | // For the right child 59 | i++; 60 | if (i >= ip.size()) break; 61 | currVal = ip[i]; 62 | 63 | // If the right child is not null 64 | if (currVal != "N") { 65 | 66 | // Create the right child for the current node 67 | currNode->right = newNode(stoi(currVal)); 68 | 69 | // Push it to the queue 70 | queue.push(currNode->right); 71 | } 72 | i++; 73 | } 74 | 75 | return root; 76 | } 77 | 78 | 79 | // } Driver Code Ends 80 | /* Tree node structure used in the program 81 | 82 | struct Node 83 | { 84 | int data; 85 | struct Node* left; 86 | struct Node* right; 87 | 88 | Node(int x){ 89 | data = x; 90 | left = right = NULL; 91 | } 92 | }; */ 93 | 94 | class Solution { 95 | public: 96 | // Function to return the diameter of a Binary Tree. 97 | pair solve(Node* root){ 98 | if(root==NULL) return {0,0}; 99 | 100 | pair left=solve(root->left); 101 | pair right=solve(root->right); 102 | 103 | int height = max(left.first, right.first) + 1; 104 | int Maxdiameter = max({left.second, right.second, left.first+right.first}); 105 | return {height, Maxdiameter}; 106 | } 107 | int diameter(Node* root) { 108 | pair ans = solve(root); 109 | return ans.second + 1; 110 | } 111 | }; 112 | 113 | //{ Driver Code Starts. 114 | 115 | /* Driver program to test size function*/ 116 | int main() { 117 | int t; 118 | scanf("%d\n", &t); 119 | while (t--) { 120 | string s; 121 | getline(cin, s); 122 | Node* root = buildTree(s); 123 | Solution ob; 124 | cout << ob.diameter(root) << endl; 125 | 126 | cout << "~" << "\n"; 127 | } 128 | return 0; 129 | } 130 | 131 | // } Driver Code Ends -------------------------------------------------------------------------------- /Day168_Height_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | struct Node 8 | { 9 | int data; 10 | struct Node *left; 11 | struct Node *right; 12 | 13 | Node(int val) { 14 | data = val; 15 | left = right = NULL; 16 | } 17 | }; 18 | 19 | // Function to Build Tree 20 | Node* buildTree(string str) 21 | { 22 | // Corner Case 23 | if(str.length() == 0 || str[0] == 'N') 24 | return NULL; 25 | 26 | // Creating vector of strings from input 27 | // string after spliting by space 28 | vector ip; 29 | 30 | istringstream iss(str); 31 | for(string str; iss >> str; ) 32 | ip.push_back(str); 33 | 34 | // Create the root of the tree 35 | Node *root = new Node(stoi(ip[0])); 36 | 37 | // Push the root to the queue 38 | queue queue; 39 | queue.push(root); 40 | 41 | // Starting from the second element 42 | int i = 1; 43 | while(!queue.empty() && i < ip.size()) { 44 | 45 | // Get and remove the front of the queue 46 | Node* currNode = queue.front(); 47 | queue.pop(); 48 | 49 | // Get the current node's value from the string 50 | string currVal = ip[i]; 51 | 52 | // If the left child is not null 53 | if(currVal != "N") { 54 | 55 | // Create the left child for the current Node 56 | currNode->left = new Node(stoi(currVal)); 57 | 58 | // Push it to the queue 59 | queue.push(currNode->left); 60 | } 61 | 62 | // For the right child 63 | i++; 64 | if(i >= ip.size()) 65 | break; 66 | currVal = ip[i]; 67 | 68 | // If the right child is not null 69 | if(currVal != "N") { 70 | 71 | // Create the right child for the current node 72 | currNode->right = new Node(stoi(currVal)); 73 | 74 | // Push it to the queue 75 | queue.push(currNode->right); 76 | } 77 | i++; 78 | } 79 | 80 | return root; 81 | } 82 | 83 | // } Driver Code Ends 84 | //User function template for C++ 85 | 86 | /* 87 | struct Node 88 | { 89 | int data; 90 | struct Node* left; 91 | struct Node* right; 92 | 93 | Node(int x){ 94 | data = x; 95 | left = right = NULL; 96 | } 97 | }; 98 | */ 99 | class Solution{ 100 | public: 101 | //Function to find the height of a binary tree. 102 | int height(struct Node* node){ 103 | if(node==NULL) return 0; 104 | return (max(height(node->left), height(node->right))+1); 105 | } 106 | }; 107 | 108 | //{ Driver Code Starts. 109 | int main() 110 | { 111 | int t; 112 | scanf("%d ",&t); 113 | while(t--) 114 | { 115 | string treeString; 116 | getline(cin,treeString); 117 | Node* root = buildTree(treeString); 118 | Solution ob; 119 | cout< 3 | using namespace std; 4 | 5 | // Tree Node 6 | struct Node { 7 | int data; 8 | Node *left; 9 | Node *right; 10 | 11 | Node(int val) { 12 | data = val; 13 | left = right = NULL; 14 | } 15 | }; 16 | 17 | // Function to Build Tree 18 | Node *buildTree(string str) { 19 | // Corner Case 20 | if (str.length() == 0 || str[0] == 'N') 21 | return NULL; 22 | 23 | // Creating vector of strings from input 24 | // string after spliting by space 25 | vector ip; 26 | 27 | istringstream iss(str); 28 | for (string str; iss >> str;) 29 | ip.push_back(str); 30 | 31 | // Create the root of the tree 32 | Node *root = new Node(stoi(ip[0])); 33 | 34 | // Push the root to the queue 35 | queue queue; 36 | queue.push(root); 37 | 38 | // Starting from the second element 39 | int i = 1; 40 | while (!queue.empty() && i < ip.size()) { 41 | 42 | // Get and remove the front of the queue 43 | Node *currNode = queue.front(); 44 | queue.pop(); 45 | 46 | // Get the current Node's value from the string 47 | string currVal = ip[i]; 48 | 49 | // If the left child is not null 50 | if (currVal != "N") { 51 | 52 | // Create the left child for the current Node 53 | currNode->left = new Node(stoi(currVal)); 54 | 55 | // Push it to the queue 56 | queue.push(currNode->left); 57 | } 58 | 59 | // For the right child 60 | i++; 61 | if (i >= ip.size()) 62 | break; 63 | currVal = ip[i]; 64 | 65 | // If the right child is not null 66 | if (currVal != "N") { 67 | 68 | // Create the right child for the current Node 69 | currNode->right = new Node(stoi(currVal)); 70 | 71 | // Push it to the queue 72 | queue.push(currNode->right); 73 | } 74 | i++; 75 | } 76 | 77 | return root; 78 | } 79 | 80 | 81 | // } Driver Code Ends 82 | // User Fuction template for C++ 83 | 84 | class Solution { 85 | public: 86 | //Function to return maximum path sum from any node in a tree. 87 | int maxpath(Node* root, int& maxi){ 88 | if(root==NULL) return 0; 89 | 90 | int leftsum = max(0, maxpath(root->left, maxi)); 91 | int rightsum = max(0, maxpath(root->right, maxi)); 92 | 93 | maxi = max(maxi, (leftsum + rightsum + root->data)); 94 | return root->data + max(leftsum, rightsum); 95 | } 96 | 97 | // pair solve(TreeNode* root){ 98 | // if(root==NULL) return {INT_MIN, 0}; 99 | 100 | // pair left=solve(root->left); 101 | // pair right=solve(root->right); 102 | 103 | // if(left.second<0) left.second=0; 104 | // if(right.second<0) right.second=0; 105 | 106 | // return {max({left.first, right.first, (left.second+right.second+root->data)}), max(left.second, right.second) + root->data}; 107 | // } 108 | 109 | int findMaxSum(Node* root) { 110 | int maxi = INT_MIN; 111 | maxpath(root, maxi); 112 | return maxi; 113 | // pair ans=solve(root); 114 | // return ans.first; 115 | } 116 | }; 117 | 118 | //{ Driver Code Starts. 119 | 120 | 121 | int main() { 122 | int tc; 123 | scanf("%d ", &tc); 124 | while (tc--) { 125 | string treeString; 126 | getline(cin, treeString); 127 | Solution ob; 128 | Node *root = buildTree(treeString); 129 | cout << ob.findMaxSum(root) << "\n"; 130 | 131 | 132 | cout << "~" << "\n"; 133 | } 134 | 135 | 136 | return 0; 137 | } 138 | // } Driver Code Ends -------------------------------------------------------------------------------- /Day168_Same_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSameTree(TreeNode* p, TreeNode* q) { 15 | if (p==NULL||q==NULL) return(p==q); 16 | return (p->val==q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 17 | } 18 | }; -------------------------------------------------------------------------------- /Day169_Vertical_Order_Traversal_of_a_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> verticalTraversal(TreeNode* root) { 15 | map>> nodes; 16 | queue>> todo; 17 | todo.push({root, {0,0}}); 18 | 19 | while(!todo.empty()){ 20 | auto p = todo.front(); 21 | todo.pop(); 22 | TreeNode* node = p.first; 23 | int X = p.second.first, Y = p.second.second; 24 | nodes[X][Y].insert(node->val); 25 | if(node->left) todo.push({node->left, {X-1, Y+1}}); 26 | if(node->right) todo.push({node->right, {X+1, Y+1}}); 27 | } 28 | 29 | vector> ans; 30 | for(auto p : nodes){ 31 | vector col; 32 | for(auto q : p.second){ 33 | col.insert(col.end(), q.second.begin(), q.second.end()); 34 | } 35 | ans.push_back(col); 36 | } 37 | return ans; 38 | } 39 | }; -------------------------------------------------------------------------------- /Day170_Binary_Tree_Right_Side_View.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void Traversal(TreeNode* root, int level, vector &ans){ 15 | if(root==NULL) return; 16 | if(level==ans.size()) ans.push_back(root->val); 17 | 18 | Traversal(root->right, level+1, ans); 19 | Traversal(root->left, level+1, ans); 20 | } 21 | vector rightSideView(TreeNode* root) { 22 | vector ans; 23 | Traversal(root, 0, ans); 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day170_Symmetric_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSymetricHelp(TreeNode* left, TreeNode* right){ 15 | if(left==NULL || right==NULL) return left==right; 16 | if(left->val != right->val) return false; 17 | 18 | return isSymetricHelp(left->left, right->right) && isSymetricHelp(left->right, right->left); 19 | } 20 | bool isSymmetric(TreeNode* root) { 21 | return (root==NULL) || isSymetricHelp(root->left, root->right); 22 | } 23 | }; -------------------------------------------------------------------------------- /Day171_Binary_Tree_Paths.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void getPath(TreeNode* root, string temp, vector &ans){ 15 | if(root==NULL) return; 16 | 17 | if(root->left==NULL && root->right==NULL){ 18 | temp+= to_string(root->val); 19 | ans.push_back(temp); 20 | 21 | return; 22 | } 23 | temp+= to_string(root->val) + "->"; 24 | 25 | getPath(root->left, temp, ans); 26 | getPath(root->right, temp, ans); 27 | 28 | } 29 | 30 | 31 | vector binaryTreePaths(TreeNode* root) { 32 | vector ans; 33 | string temp=""; 34 | getPath(root, temp, ans); 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /Day173_Lowest_Common_Ancestor_of_a_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | if(root==NULL || root==p || root==q) return root; 14 | 15 | TreeNode* left = lowestCommonAncestor(root->left, p, q); 16 | TreeNode* right = lowestCommonAncestor(root->right, p, q); 17 | 18 | if(left==NULL) return right; 19 | else if (right==NULL) return left; 20 | else return root; 21 | } 22 | }; -------------------------------------------------------------------------------- /Day177_Maximum_Width_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int widthOfBinaryTree(TreeNode* root) { 15 | if(!root) return 0; 16 | int ans = 0; 17 | queue> q; 18 | q.push({root, 0}); 19 | 20 | while(!q.empty()){ 21 | int size = q.size(); 22 | long mmin = q.front().second; 23 | int first, last; 24 | 25 | for(int i = 0; ileft) q.push({node->left, (cur_id*2)+1}); 32 | if(node->right) q.push({node->right, (cur_id*2)+2}); 33 | } 34 | 35 | ans = max(ans, last-first+1); 36 | } 37 | 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /Day178_Root_Equals_Sum_of_Children.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool checkTree(TreeNode* root) { 15 | if(!root||(!root->left && !root->right)) return 1; 16 | int sum=0; 17 | 18 | if(root->left) sum+=root->left->val; 19 | if(root->right) sum+=root->right->val; 20 | return (root->val==sum && checkTree(root->left) && checkTree(root->right)); 21 | } 22 | }; -------------------------------------------------------------------------------- /Day179_All_Nodes_Distance_K_in_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | 13 | void marksParent(TreeNode* root, unordered_map &parent_track){ 14 | queue queue; 15 | queue.push(root); 16 | while(!queue.empty()){ 17 | TreeNode* current = queue.front(); 18 | queue.pop(); 19 | if(current->left){ 20 | parent_track[current->left] = current; 21 | queue.push(current->left); 22 | } 23 | if(current->right){ 24 | parent_track[current->right] = current; 25 | queue.push(current->right); 26 | } 27 | } 28 | } 29 | 30 | vector distanceK(TreeNode* root, TreeNode* target, int k) { 31 | unordered_map parent_track; 32 | marksParent(root, parent_track); 33 | 34 | unordered_map visited; 35 | queue queue; 36 | queue.push(target); 37 | visited[target] = true; 38 | int curr_level = 0; 39 | 40 | while(!queue.empty()){ 41 | int size = queue.size(); 42 | if(curr_level==k) break; 43 | curr_level++; 44 | for(int i=0; ileft && !visited[current->left]){ 47 | queue.push(current->left); 48 | visited[current->left] = true; 49 | } 50 | if(current->right && !visited[current->right]){ 51 | queue.push(current->right); 52 | visited[current->right] = true; 53 | } 54 | if(parent_track[current] && !visited[parent_track[current]]){ 55 | queue.push(parent_track[current]); 56 | visited[parent_track[current]] = true; 57 | } 58 | } 59 | } 60 | vector result; 61 | while(!queue.empty()){ 62 | TreeNode* current = queue.front(); queue.pop(); 63 | result.push_back(current->val); 64 | } 65 | return result; 66 | } 67 | }; -------------------------------------------------------------------------------- /Day179_Amount_of_Time_for_Binary_Tree_to_Be_Infected.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int amountOfTime(TreeNode* root, int start) { 16 | map mpp; 17 | TreeNode* target = bfsToMapParents(root, mpp, start); 18 | int maxi = findMaxDistance(mpp, target); 19 | return maxi; 20 | } 21 | 22 | TreeNode* bfsToMapParents(TreeNode* root, map &mpp, int start){ 23 | queue q; 24 | q.push(root); 25 | TreeNode* res; 26 | 27 | while(!q.empty()){ 28 | TreeNode* node = q.front(); 29 | q.pop(); 30 | if(node->val==start) res=node; 31 | if(node->left) { 32 | mpp[node->left]=node; 33 | q.push(node->left); 34 | } 35 | if(node->right) { 36 | mpp[node->right]=node; 37 | q.push(node->right); 38 | } 39 | } 40 | return res; 41 | } 42 | 43 | int findMaxDistance(map &mpp, TreeNode* target){ 44 | queue qu; 45 | qu.push(target); 46 | map vis; 47 | vis[target]=1; 48 | int maxi=0; 49 | 50 | while(!qu.empty()){ 51 | int n=qu.size(); 52 | int change=0; 53 | for(int i=0; ileft and !vis[node->left]){ 57 | qu.push(node->left); 58 | vis[node->left]=1; 59 | change=1; 60 | } 61 | if(node->right and !vis[node->right]){ 62 | qu.push(node->right); 63 | vis[node->right]=1; 64 | change=1; 65 | } 66 | if(mpp[node] and !vis[mpp[node]]){ 67 | qu.push(mpp[node]); 68 | vis[mpp[node]]=1; 69 | change=1; 70 | } 71 | } 72 | if(change) maxi++; 73 | } 74 | return maxi; 75 | } 76 | }; -------------------------------------------------------------------------------- /Day180_Count_Complete_Tree_Nodes.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int countNodes(TreeNode* root) { 15 | if(root==NULL) return 0; 16 | int lh = FHL(root); 17 | int rh = FRH(root); 18 | 19 | if(lh == rh) return (1<left) + countNodes(root->right); 21 | } 22 | 23 | int FHL(TreeNode* node){ 24 | int hght = 0; 25 | while(node){ 26 | hght++; 27 | node = node->left; 28 | } 29 | return hght; 30 | } 31 | 32 | int FRH(TreeNode* node){ 33 | int hght = 0; 34 | while(node){ 35 | hght++; 36 | node = node->right; 37 | } 38 | return hght; 39 | } 40 | }; -------------------------------------------------------------------------------- /Day191_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | class Solution { 14 | public: 15 | // Function to make BT from preorder & inorder 16 | TreeNode* buildTree(vector& preorder, vector& inorder){ 17 | map inMap; 18 | for(int i=0; i& preorder, int preStart, int preEnd, 27 | vector& inorder, int inStart, int inEnd, map& inMap){ 28 | // If the start indices exceed the end indices, return NULL 29 | if(preStart>preEnd || inStart>inEnd) return NULL; 30 | // New TreeNode with value at the current preorder index 31 | TreeNode* root = new TreeNode(preorder[preStart]); 32 | int inRoot = inMap[root->val]; 33 | // No of elements in the left subtree 34 | int numsLeft = inRoot - inStart; 35 | root->left = buildTree(preorder, preStart + 1, preStart + numsLeft, 36 | inorder, inStart, inRoot - 1, inMap); 37 | root->right = buildTree(preorder, preStart + numsLeft + 1, preEnd, 38 | inorder, inRoot + 1, inEnd, inMap); 39 | return root; 40 | } 41 | }; -------------------------------------------------------------------------------- /Day199_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* buildTree(vector& inorder, vector& postorder) { 15 | if(inorder.size() != postorder.size()) return NULL; 16 | map hm; 17 | for(int i=0; i &inorder, int is, int ie, 23 | vector &postorder, int ps, int pe, map &hm){ 24 | if(ps>pe || is>ie) return NULL; 25 | TreeNode* root = new TreeNode(postorder[pe]); 26 | int inRoot = hm[postorder[pe]]; 27 | int numsLeft = inRoot-is; 28 | 29 | root->left = buildTreePostIn(inorder, is, inRoot-1, 30 | postorder, ps, ps+numsLeft-1, hm); 31 | 32 | root->right = buildTreePostIn(inorder, inRoot+1, ie, 33 | postorder, ps+numsLeft, pe-1, hm); 34 | return root; 35 | } 36 | }; -------------------------------------------------------------------------------- /Day226_Serialize_and_Deserialize_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Codec { 11 | public: 12 | // Encodes a tree to a single string. 13 | string serialize(TreeNode* root) { 14 | if(!root) return ""; 15 | 16 | string s = ""; 17 | queue q; 18 | q.push(root); 19 | while(!q.empty()){ 20 | TreeNode* currNode = q.front(); 21 | q.pop(); 22 | if(currNode==NULL) s.append("#,"); 23 | else s.append(to_string(currNode->val)+","); 24 | if(currNode!=NULL){ 25 | q.push(currNode->left); 26 | q.push(currNode->right); 27 | } 28 | } 29 | // cout< q; 41 | q.push(root); 42 | while(!q.empty()){ 43 | TreeNode* node = q.front(); 44 | q.pop(); 45 | getline(s, str, ','); 46 | 47 | if(str=="#") node->left=NULL; 48 | else{ 49 | TreeNode* leftNode = new TreeNode(stoi(str)); 50 | node->left = leftNode; 51 | q.push(leftNode); 52 | } 53 | 54 | getline(s, str, ','); 55 | if(str=="#") node->right=NULL; 56 | else{ 57 | TreeNode* rightNode = new TreeNode(stoi(str)); 58 | node->right = rightNode; 59 | q.push(rightNode); 60 | } 61 | } 62 | return root; 63 | } 64 | }; 65 | 66 | // Your Codec object will be instantiated and called as such: 67 | // Codec ser, deser; 68 | // TreeNode* ans = deser.deserialize(ser.serialize(root)); -------------------------------------------------------------------------------- /Day227_Flatten_Binary_Tree_to_Linked_List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* previous = NULL; 15 | void flatten(TreeNode* root) { 16 | 17 | if(root==NULL) return; 18 | 19 | flatten(root->right); 20 | flatten(root->left); 21 | 22 | root->right=previous; 23 | root->left=NULL; 24 | previous=root; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day227_Search_in_a_Binary_Search_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* searchBST(TreeNode* root, int val) { 15 | int Val=val; 16 | while(root!=NULL && root->val!=Val){ 17 | root = Valval? root->left:root->right; 18 | } 19 | return root; 20 | } 21 | }; -------------------------------------------------------------------------------- /Day228_Delete_Node_in_a_BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | // Function to delete a node from BST. 15 | TreeNode *deleteNode(TreeNode *root, int Key) { 16 | // your code goes here 17 | if(root==NULL) return NULL; 18 | if(root->val==Key) return helper(root); 19 | 20 | TreeNode* dummy = root; 21 | while(root!=NULL){ 22 | if(root->val>Key){ 23 | if(root->left!=NULL && root->left->val==Key){ 24 | root->left = helper(root->left); 25 | break; 26 | } 27 | else root = root->left; 28 | } 29 | else{ 30 | if(root->right!=NULL && root->right->val==Key){ 31 | root->right = helper(root->right); 32 | break; 33 | } 34 | else root = root->right; 35 | } 36 | } 37 | return dummy; 38 | } 39 | 40 | TreeNode* helper(TreeNode* root){ 41 | if(root->left==NULL) return root->right; 42 | else if(root->right==NULL) return root->left; 43 | 44 | TreeNode* rightChild = root->right; 45 | TreeNode* lastRight = findLastRight(root->left); 46 | lastRight->right = rightChild; 47 | return root->left; 48 | } 49 | 50 | TreeNode* findLastRight(TreeNode* root){ 51 | if(root->right==NULL) return root; 52 | return findLastRight(root->right); 53 | } 54 | }; -------------------------------------------------------------------------------- /Day229_Kth_Smallest_Element_in_a_BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int kthSmallest(TreeNode* root, int k) { 16 | stack st; 17 | TreeNode* current = root; 18 | int count = 0; 19 | 20 | while (!st.empty() || current) { 21 | while (current) { 22 | st.push(current); 23 | current = current->left; 24 | } 25 | 26 | current = st.top(); 27 | st.pop(); 28 | count++; 29 | if (count == k) return current->val; 30 | current = current->right; 31 | } 32 | return -1; // This line should never be reached 33 | } 34 | }; -------------------------------------------------------------------------------- /Day229_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | class Solution { 12 | public: 13 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 14 | while(root) { 15 | if(p->val > root->val && q->val > root->val) root = root->right; 16 | else if(p->val < root->val && q->val < root->val) root = root->left; 17 | else return root; 18 | } 19 | return nullptr; 20 | } 21 | }; -------------------------------------------------------------------------------- /Day229_Validate_Binary_Search_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool istValidBST(TreeNode* root, long long minVal, long long maxVal) { 15 | if(!root) return 1; 16 | if(root->val>=maxVal || root->val<=minVal) return 0; 17 | return istValidBST(root->left, minVal, root->val) && istValidBST(root->right, root->val, maxVal); 18 | } 19 | bool isValidBST(TreeNode* root) { 20 | return istValidBST(root, LONG_MIN, LONG_MAX); 21 | } 22 | }; -------------------------------------------------------------------------------- /Day230_Binary_Search_Tree_Iterator.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class BSTIterator { 13 | private: stack mystack; 14 | public: 15 | BSTIterator(TreeNode* root) { 16 | pushAll(root); 17 | } 18 | 19 | bool hasNext() { 20 | return !mystack.empty(); 21 | } 22 | 23 | int next() { 24 | TreeNode* tempNode = mystack.top(); 25 | mystack.pop(); 26 | pushAll(tempNode->right); 27 | return tempNode->val; 28 | } 29 | private: 30 | void pushAll(TreeNode* node){ 31 | for(; node!=NULL; mystack.push(node), node=node->left); 32 | } 33 | }; 34 | 35 | /** 36 | * Your BSTIterator object will be instantiated and called as such: 37 | * BSTIterator* obj = new BSTIterator(root); 38 | * int param_1 = obj->next(); 39 | * bool param_2 = obj->hasNext(); 40 | */ -------------------------------------------------------------------------------- /Day230_Construct_Binary_Search_Tree_from_Preorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* bstFromPreorder(vector& preorder) { 15 | int i = 0; 16 | return build(preorder, i, INT_MAX); 17 | } 18 | TreeNode* build(vector& preorder, int& i, int bound){ 19 | if(i==preorder.size() || preorder[i]>bound) return NULL; 20 | TreeNode* root = new TreeNode(preorder[i++]); 21 | root->left = build(preorder, i, root->val); 22 | root->right = build(preorder, i, bound); 23 | return root; 24 | } 25 | }; -------------------------------------------------------------------------------- /Day230_Two_Sum_IV_nput_is_a_BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | class BSTIterator { 14 | private: stack mystack; 15 | // reverse->True->before 16 | // reverse->False->next 17 | bool reverse = true; 18 | public: 19 | BSTIterator(TreeNode* root, bool isReverse) { 20 | reverse = isReverse; 21 | pushAll(root); 22 | } 23 | 24 | bool hasNext() { 25 | return !mystack.empty(); 26 | } 27 | 28 | int next() { 29 | TreeNode* tempNode = mystack.top(); 30 | mystack.pop(); 31 | if(!reverse) pushAll(tempNode->right); 32 | else pushAll(tempNode->left); 33 | return tempNode->val; 34 | } 35 | private: 36 | void pushAll(TreeNode* node){ 37 | for(; node!=NULL;){ 38 | mystack.push(node); 39 | if(reverse==true) node=node->right; 40 | else node=node->left; 41 | } 42 | } 43 | }; 44 | class Solution { 45 | public: 46 | bool findTarget(TreeNode* root, int k) { 47 | if(!root) return false; 48 | BSTIterator l(root, false); 49 | BSTIterator r(root, true); 50 | 51 | int i = l.next(); 52 | int j = r.next(); 53 | while(ileft); 22 | if(prev!=NULL && (root->valval)){ 23 | if(first==NULL){ 24 | first=prev; 25 | middle=root; 26 | } 27 | else last=root; 28 | } 29 | // Mark the node as previous 30 | prev=root; 31 | inorder(root->right); 32 | } 33 | public: 34 | void recoverTree(TreeNode* root) { 35 | first=middle=last=NULL; 36 | prev = new TreeNode(INT_MIN); 37 | inorder(root); 38 | if(first && last) swap(first->val, last->val); 39 | else if(first && middle) swap(first->val, middle->val); 40 | } 41 | }; -------------------------------------------------------------------------------- /Day236_Count_the_Number_of_Complete_Components.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int src, vector&visited, vector>&adjList, int &edges, int &nodes) { 4 | visited[src]=1; 5 | for(auto it: adjList[src]){ 6 | edges++; 7 | if(visited[it]==0){ 8 | nodes++; 9 | dfs(it, visited, adjList, edges, nodes); 10 | } 11 | } 12 | } 13 | int countCompleteComponents(int n, vector>& edge) { 14 | vector> adjList(n); 15 | for(auto it: edge) { 16 | adjList[it[0]].push_back(it[1]); 17 | adjList[it[1]].push_back(it[0]); 18 | } 19 | 20 | vectorvisited(n, 0); 21 | int edges=0; 22 | int nodes=1; 23 | int ans=0; 24 | 25 | for(int i=0; i> &vis, vector> &grid) { 4 | vis[row][col] = 1; 5 | queue> q; 6 | q.push({row, col}); 7 | int n = grid.size(); 8 | int m = grid[0].size(); 9 | 10 | int drow[] = {-1, 0, 1, 0}; 11 | int dcol[] = {0, 1, 0, -1}; 12 | 13 | while(!q.empty()) { 14 | int row=q.front().first; 15 | int col=q.front().second; 16 | q.pop(); 17 | 18 | for(int i=0; i<4; i++) { 19 | int nrow = row + drow[i]; 20 | int ncol = col + dcol[i]; 21 | 22 | if(nrow>=0 && nrow=0 && ncol>& grid) { 32 | int n=grid.size(); 33 | int m=grid[0].size(); 34 | vector> vis(n, vector(m, 0)); 35 | int cnt=0; 36 | 37 | for (int row=0; row>& isConnected, vector& visited) { 4 | visited[node]=1; 5 | for (int i=0; i>& isConnected) { 13 | int V = isConnected.size(); 14 | vector visited(V, 0); 15 | int cnt=0; 16 | 17 | for(int i=0; i> &ans, int color, int delRow[], int delCol[], int iniColor) { 4 | ans[row][col] = color; 5 | int n = ans.size(); 6 | int m = ans[0].size(); 7 | 8 | for(int i=0; i<4; i++){ 9 | int nrow = row + delRow[i]; 10 | int ncol = col + delCol[i]; 11 | 12 | if(nrow>=0 && nrow=0 && ncol> floodFill(vector>& image, int sr, int sc, int color) { 18 | int iniColor = image[sr][sc]; 19 | vector> ans = image; 20 | 21 | int delRow[] = {-1, 0, 1, 0}; 22 | int delCol[] = {0, 1, 0, -1}; 23 | dfs(sr, sc, ans, color, delRow, delCol, iniColor); 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day237_Rotting_Oranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int orangesRotting(vector>& grid) { 4 | int n = grid.size(); 5 | int m = grid[0].size(); 6 | 7 | queue, int>> q; 8 | vector> vis(n, vector(m, 0));; 9 | 10 | for(int i=0; i=0 && nrow=0 && ncol> updateMatrix(vector>& mat) { 4 | int n = mat.size(); 5 | int m = mat[0].size(); 6 | vector> vis(n, vector(m, 0)); 7 | vector> dist(n, vector(m, 0)); 8 | queue, int>> q; 9 | 10 | for(int i=0; i=0 && nrow=0 && ncol> highestPeak(vector>& isWater) { 4 | int n = isWater.size(); 5 | int m = isWater[0].size(); 6 | vector> vis(n, vector(m, 0)); 7 | vector> dist(n, vector(m, -1)); 8 | queue, int>> q; 9 | 10 | // Initialize queue with water cells 11 | for(int i = 0; i < n; i++) { 12 | for(int j = 0; j < m; j++) { 13 | if(isWater[i][j] == 1) { 14 | q.push({{i, j}, 0}); 15 | vis[i][j] = 1; 16 | dist[i][j] = 0; 17 | } 18 | } 19 | } 20 | 21 | // Direction vectors for 4-way BFS traversal 22 | int delrow[] = {-1, 0, 1, 0}; 23 | int delcol[] = {0, 1, 0, -1}; 24 | 25 | // BFS traversal 26 | while (!q.empty()) { 27 | int row = q.front().first.first; 28 | int col = q.front().first.second; 29 | int steps = q.front().second; 30 | q.pop(); 31 | 32 | dist[row][col] = steps; 33 | 34 | for (int i = 0; i < 4; i++) { 35 | int nrow = row + delrow[i]; 36 | int ncol = col + delcol[i]; 37 | if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && vis[nrow][ncol] == 0) { 38 | vis[nrow][ncol] = 1; 39 | dist[nrow][ncol] = steps + 1; 40 | q.push({{nrow, ncol}, steps + 1}); 41 | } 42 | } 43 | } 44 | return dist; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Day239_Surrounded_Regions.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int row, int col, vector> &vis, 4 | vector> &board) { 5 | vis[row][col] = 1; 6 | int n = board.size(); 7 | int m = board[0].size(); 8 | int delrow[] = {-1, 0, +1, 0}; 9 | int delcol[] = {0, 1, 0, -1}; 10 | 11 | // check for top, right, bottom, left 12 | for(int i=0; i<4; i++) { 13 | int nrow = row + delrow[i]; 14 | int ncol = col + delcol[i]; 15 | // check for valid coordinates and unvisited Os 16 | if(nrow>=0 && nrow=0 && ncol> &board){ 24 | int n = board.size(); 25 | int m = board[0].size(); 26 | vector> vis(n, vector(m, 0)); 27 | 28 | // first row and last row 29 | for(int j=0; j>& grid) { 4 | queue> q; 5 | int n = grid.size(); 6 | int m = grid[0].size(); 7 | vector> vis(n, vector (m, 0)); 8 | 9 | for(int i=0; i=0 && nrow=0 && ncol>& preList, int node, vector& vis, vector& ans){ 4 | if (vis[node]==1) return true; 5 | if (vis[node] == 2) return false; 6 | vis[node] = 1; 7 | 8 | for (int it: preList[node]) { 9 | if (dfs(preList, it, vis, ans)) { 10 | return true; 11 | } 12 | } 13 | vis[node] = 2; 14 | ans.push_back(node); 15 | return false; 16 | } 17 | vector findOrder(int numCourses, vector>& prerequisites) { 18 | vector> preList(numCourses); 19 | vector vis(numCourses, 0); 20 | vector ans; 21 | 22 | for(auto it: prerequisites) { 23 | preList[it[0]].push_back(it[1]); 24 | } 25 | for(int i=0; i>& graph, vector &colour){ 4 | // queue q; 5 | // q.push(start); 6 | // colour[start] = 0; 7 | 8 | // while(!q.empty()){ 9 | // int node = q.front(); 10 | // q.pop(); 11 | // for(auto it: graph[node]){ 12 | // if(colour[it]==-1){ 13 | // colour[it]=!colour[node]; 14 | // q.push(it); 15 | // } 16 | // else if(colour[it]==colour[node]) return 0; 17 | // } 18 | // } 19 | // return 1; 20 | // } 21 | 22 | // bool isBipartite(vector>& graph) { 23 | // int n = graph.size(); 24 | // vector colour(n, -1); 25 | // for(int i=0; i>& graph, vector &colour){ 37 | colour[node] = col; 38 | for(auto it: graph[node]){ 39 | if(colour[it]==-1){ 40 | if(check(it, !col, graph, colour)==0) return 0; 41 | } 42 | else if(colour[it]==col) return 0; 43 | } 44 | return 1; 45 | } 46 | 47 | bool isBipartite(vector>& graph) { 48 | int n = graph.size(); 49 | vector colour(n, -1); 50 | for(int i=0; i>& graph, vector &colour){ 4 | queue q; 5 | q.push(start); 6 | colour[start] = 0; 7 | 8 | while(!q.empty()){ 9 | int node = q.front(); 10 | q.pop(); 11 | for(auto it: graph[node]){ 12 | if(colour[it]==-1){ 13 | colour[it]=!colour[node]; 14 | q.push(it); 15 | } 16 | else if(colour[it]==colour[node]) return 0; 17 | } 18 | } 19 | return 1; 20 | } 21 | 22 | bool isBipartite(vector>& graph) { 23 | int n = graph.size(); 24 | vector colour(n, -1); 25 | for(int i=0; i> &graph, vector &vis, vector &pathvis, vector &check) { 4 | vis[node]=1; 5 | pathvis[node]=1; 6 | check[node]=0; 7 | 8 | for(auto it: graph[node]){ 9 | if(!vis[it]){ 10 | if(dfs(it, graph, vis, pathvis, check)) { 11 | check[node]=0; 12 | return 1; 13 | } 14 | } 15 | else if(pathvis[it]){ 16 | check[node]=0; 17 | return 1; 18 | } 19 | } 20 | check[node]=1; 21 | pathvis[node]=0; 22 | return 0; 23 | } 24 | vector eventualSafeNodes(vector>& graph) { 25 | int V = graph.size(); 26 | vector vis(V, 0); 27 | vector pathvis(V, 0); 28 | vector check(V, 0); 29 | vector safeNodes; 30 | 31 | for(int i=0; i>& prerequisites) { 4 | // vector> adj(N, vector(N, 0)); // matrix 5 | vector> adj(N); // (adjacency list representation). 6 | for(auto it: prerequisites){ 7 | adj[it[0]].push_back(it[1]); 8 | } 9 | 10 | vector indegree(N, 0); 11 | for(int i=0; i q; 16 | for(int i=0; i topo; 21 | while(!q.empty()){ 22 | int node=q.front(); 23 | q.pop(); 24 | topo.push_back(node); 25 | for(auto it: adj[node]){ 26 | indegree[it]--; 27 | if(indegree[it]==0) q.push(it); 28 | } 29 | } 30 | 31 | if(topo.size()==N) return true; 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /Day260_Course_Schedule_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // bool dfs(vector>& preList, int node, vector& vis, vector& ans){ 4 | // if (vis[node]==1) return true; 5 | // if (vis[node] == 2) return false; 6 | // vis[node] = 1; 7 | 8 | // for (int it: preList[node]) { 9 | // if (dfs(preList, it, vis, ans)) { 10 | // return true; 11 | // } 12 | // } 13 | // vis[node] = 2; 14 | // ans.push_back(node); 15 | // return false; 16 | // } 17 | // vector findOrder(int numCourses, vector>& prerequisites) { 18 | // vector> preList(numCourses); 19 | // vector vis(numCourses, 0); 20 | // vector ans; 21 | 22 | // for(auto it: prerequisites) { 23 | // preList[it[0]].push_back(it[1]); 24 | // } 25 | // for(int i=0; i findOrder(int N, vector>& prerequisites) { 35 | // vector> adj(N, vector(N, 0)); // matrix 36 | vector> adj(N); // (adjacency list representation). 37 | for(auto it: prerequisites){ 38 | adj[it[1]].push_back(it[0]); 39 | } 40 | 41 | vector indegree(N, 0); 42 | for(int i=0; i q; 47 | for(int i=0; i topo; 52 | while(!q.empty()){ 53 | int node=q.front(); 54 | q.pop(); 55 | topo.push_back(node); 56 | for(auto it: adj[node]){ 57 | indegree[it]--; 58 | if(indegree[it]==0) q.push(it); 59 | } 60 | } 61 | 62 | if(topo.size()==N) return topo; 63 | return {}; 64 | } 65 | }; -------------------------------------------------------------------------------- /Day262_Find_Eventual_Safe_States.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector eventualSafeNodes(vector>& graph) { 4 | int V = graph.size(); 5 | vector> adjRev(V); 6 | vector indegree(V, 0); 7 | for(int i=0; iit 9 | // it->i 10 | for(auto it: graph[i]){ 11 | adjRev[it].push_back(i); 12 | indegree[i]++; 13 | } 14 | } 15 | 16 | queue q; 17 | vector safeNodes; 18 | for(int i=0; i& wordList) { 4 | queue> q; 5 | q.push({beginWord, 1}); 6 | unordered_set st(wordList.begin(), wordList.end()); 7 | st.erase(beginWord); 8 | while(!q.empty()){ 9 | string word = q.front().first; 10 | int steps = q.front().second; 11 | q.pop(); 12 | if(word == endWord) return steps; 13 | for(int i=0; i depthMap; 3 | vector> ans; 4 | string b; 5 | private: 6 | void dfs(string word, vector &seq) { 7 | if(word==b) { 8 | reverse(seq.begin(), seq.end()); 9 | ans.push_back(seq); 10 | reverse(seq.begin(), seq.end()); 11 | return; 12 | } 13 | 14 | int steps = depthMap[word]; 15 | int sz=word.size(); 16 | for(int i=0; i> findLadders(string beginWord, string endWord, vector& wordList) { 31 | // BFS to find the shortest path 32 | unordered_set wordSet(wordList.begin(), wordList.end()); 33 | queue q; 34 | b=beginWord; 35 | q.push({beginWord}); 36 | depthMap[beginWord]=1; 37 | int sizee = beginWord.size(); 38 | wordSet.erase(beginWord); 39 | 40 | while(!q.empty()) { 41 | string word = q.front(); 42 | q.pop(); 43 | int steps = depthMap[word]; 44 | if(word==endWord) break; 45 | for(int i=0; i seq = {endWord}; 61 | dfs(endWord, seq); 62 | } 63 | return ans; 64 | } 65 | 66 | // vector> findLadders(string beginWord, string endWord, vector& wordList) { 67 | // unordered_set st(wordList.begin(), wordList.end()); 68 | // queue> q; 69 | // q.push({beginWord}); 70 | // vector usedOnLevel; 71 | // usedOnLevel.push_back(beginWord); 72 | // int level = 0; 73 | // vector> ans; 74 | 75 | // while(!q.empty()){ 76 | // vector vec = q.front(); 77 | // q.pop(); 78 | // if(vec.size()>level){ 79 | // level++; 80 | // for(auto it: usedOnLevel) st.erase(it); 81 | // } 82 | 83 | // usedOnLevel.clear(); 84 | // string word = vec.back(); 85 | // if(word==endWord){ 86 | // if(ans.size()==0) ans.push_back(vec); 87 | // else if(ans[0].size()==vec.size()) ans.push_back(vec); 88 | // } 89 | 90 | // for(int i=0; i0){ 95 | // vec.push_back(word); 96 | // q.push(vec); 97 | // // mark as visited on level 98 | // usedOnLevel.push_back(word); 99 | // vec.pop_back(); 100 | // } 101 | // } 102 | // word[i]=orignal; 103 | // } 104 | // } 105 | // return ans; 106 | // } 107 | }; -------------------------------------------------------------------------------- /Day268_Shortest_Path_in_Binary_Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int shortestPathBinaryMatrix(vector>& grid) { 4 | int n=grid.size(); 5 | if(grid[0][0]==1 || grid[n-1][n-1]==1) return -1; 6 | if(n==1) return 1; 7 | vector> dist(n, vector(n, 1e9)); 8 | queue>> q; 9 | dist[0][0]=1; 10 | q.push({1, {0, 0}}); 11 | int dr[] = {0, 1, 0, -1, -1, 1, -1, 1}; 12 | int dc[] = {1, 0, -1, 0, -1, -1, 1, 1}; 13 | while(!q.empty()){ 14 | auto it = q.front(); 15 | q.pop(); 16 | int dis = it.first; 17 | int r = it.second.first; 18 | int c = it.second.second; 19 | if(r==n-1 && c==n-1) return dis; 20 | for(int i=0; i<8; i++){ 21 | int newr = r + dr[i]; 22 | int newc = c + dc[i]; 23 | if(newr>=0 && newr=0 && newc> &heights) { 4 | priority_queue>, 5 | vector>>, 6 | greater>>> pq; 7 | int n = heights.size(); 8 | int m = heights[0].size(); 9 | 10 | vector> dist(n, vector(m, 1e9)); 11 | dist[0][0]=0; 12 | pq.push({0, {0, 0}}); 13 | int dr[] = {-1, 0, 1, 0}; 14 | int dc[] = {0, 1, 0, -1}; 15 | 16 | while(!pq.empty()){ 17 | auto it = pq.top(); 18 | pq.pop(); 19 | int diff = it.first; 20 | int row = it.second.first; 21 | int col = it.second.second; 22 | 23 | if(row==n-1 && col==m-1) return diff; 24 | for(int i=0; i<4; i++){ 25 | int newr = row + dr[i]; 26 | int newc = col + dc[i]; 27 | if(newr>=0 && newc>=0 && newr>& flights, int src, int dst, int k) { 4 | vector>> adj(n); 5 | for(auto it: flights) adj[it[0]].push_back({it[1], it[2]}); 6 | queue>> q; 7 | q.push({0, {src, 0}}); 8 | vector dist(n, 1e9); 9 | dist[src]=0; 10 | 11 | while(!q.empty()){ 12 | auto it = q.front(); 13 | q.pop(); 14 | int stops = it.first; 15 | int cost = it.second.second; 16 | int node = it.second.first; 17 | 18 | if(stops>k) continue; 19 | for(auto iter: adj[node]){ 20 | int adjtNode = iter.first; 21 | int edw = iter.second; 22 | if(cost+edw < dist[adjtNode] && stops<=k){ 23 | dist[adjtNode] = cost + edw; 24 | q.push({stops+1, {adjtNode, cost+edw}}); 25 | } 26 | } 27 | } 28 | if(dist[dst]==1e9) return -1; 29 | return dist[dst]; 30 | } 31 | }; -------------------------------------------------------------------------------- /Day286_Number_of_Ways_to_Arrive_at_Destination.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPaths(int n, vector>& roads) { 4 | vector>> adj(n); 5 | for(auto it: roads){ 6 | adj[it[0]].push_back({it[1], it[2]}); 7 | adj[it[1]].push_back({it[0], it[2]}); 8 | } 9 | priority_queue, vector>, 10 | greater>> pq; 11 | vector dist(n , 1e18); 12 | vector ways(n, 0); 13 | dist[0]=0; 14 | ways[0]=1; 15 | pq.push({0, 0}); 16 | int mod = (int)(1e9 + 7); 17 | while(!pq.empty()){ 18 | long long dis = pq.top().first; 19 | int node = pq.top().second; 20 | pq.pop(); 21 | 22 | for(auto it: adj[node]){ 23 | int adjNode = it.first; 24 | int edw = it.second; 25 | 26 | if(dis+edw < dist[adjNode]){ 27 | dist[adjNode] = dis+edw; 28 | pq.push({dis+edw, adjNode}); 29 | ways[adjNode] = ways[node]; 30 | } 31 | else if(dis+edw==dist[adjNode]){ 32 | ways[adjNode] = (ways[adjNode]+ways[node])%mod; 33 | } 34 | } 35 | } 36 | return ways[n-1]%mod; 37 | } 38 | }; -------------------------------------------------------------------------------- /Day287_Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findTheCity(int n, vector>& edges, int distanceThreshold) { 4 | vector> dist(n, vector(n, INT_MAX)); 5 | for(auto it: edges){ 6 | dist[it[0]] [it[1]] = it[2]; 7 | dist[it[1]] [it[0]] = it[2]; 8 | } 9 | 10 | for(int i=0; i rank, parent, size; 4 | DisjointSet(int n) { 5 | rank.resize(n + 1, 0); 6 | parent.resize(n + 1); 7 | size.resize(n + 1); 8 | for (int i = 0; i <= n; i++) { 9 | parent[i] = i; 10 | size[i] = 1; 11 | } 12 | } 13 | int findUPar(int node) { 14 | if (node == parent[node]) 15 | return node; 16 | return parent[node] = findUPar(parent[node]); 17 | } 18 | void unionByRank(int u, int v) { 19 | int ulp_u = findUPar(u); 20 | int ulp_v = findUPar(v); 21 | if (ulp_u == ulp_v) return; 22 | if (rank[ulp_u] < rank[ulp_v]) { 23 | parent[ulp_u] = ulp_v; 24 | } 25 | else if (rank[ulp_v] < rank[ulp_u]) { 26 | parent[ulp_v] = ulp_u; 27 | } 28 | else { 29 | parent[ulp_v] = ulp_u; 30 | rank[ulp_u]++; 31 | } 32 | } 33 | void unionBySize(int u, int v) { 34 | int ulp_u = findUPar(u); 35 | int ulp_v = findUPar(v); 36 | if (ulp_u == ulp_v) return; 37 | if (size[ulp_u] < size[ulp_v]) { 38 | parent[ulp_u] = ulp_v; 39 | size[ulp_v] += size[ulp_u]; 40 | } 41 | else { 42 | parent[ulp_v] = ulp_u; 43 | size[ulp_u] += size[ulp_v]; 44 | } 45 | } 46 | }; 47 | 48 | 49 | class Solution { 50 | public: 51 | int makeConnected(int n, vector>& connections) { 52 | DisjointSet ds(n); 53 | int extras = 0; 54 | for(auto it: connections){ 55 | int u = it[0]; 56 | int v = it[1]; 57 | if(ds.findUPar(u)==ds.findUPar(v)) extras++; 58 | else ds.unionBySize(u, v); 59 | } 60 | int cntc = 0; 61 | for(int i=0; i=ans) return ans; 66 | return -1; 67 | } 68 | }; -------------------------------------------------------------------------------- /Day313_Number_of_Provinces.cpp: -------------------------------------------------------------------------------- 1 | // class Solution { 2 | // public: 3 | // void traversal(int node, vector>& isConnected, vector& visited) { 4 | // visited[node]=1; 5 | // for (int i=0; i>& isConnected) { 13 | // int V = isConnected.size(); 14 | // vector visited(V, 0); 15 | // int cnt=0; 16 | 17 | // for(int i=0; i rank, parent, size; 31 | DisjointSet(int n) { 32 | rank.resize(n + 1, 0); 33 | parent.resize(n + 1); 34 | size.resize(n + 1); 35 | for (int i = 0; i <= n; i++) { 36 | parent[i] = i; 37 | size[i] = 1; 38 | } 39 | } 40 | 41 | int findUPar(int node) { 42 | if (node == parent[node]) 43 | return node; 44 | return parent[node] = findUPar(parent[node]); 45 | } 46 | 47 | void unionByRank(int u, int v) { 48 | int ulp_u = findUPar(u); 49 | int ulp_v = findUPar(v); 50 | if (ulp_u == ulp_v) return; 51 | if (rank[ulp_u] < rank[ulp_v]) { 52 | parent[ulp_u] = ulp_v; 53 | } 54 | else if (rank[ulp_v] < rank[ulp_u]) { 55 | parent[ulp_v] = ulp_u; 56 | } 57 | else { 58 | parent[ulp_v] = ulp_u; 59 | rank[ulp_u]++; 60 | } 61 | } 62 | 63 | void unionBySize(int u, int v) { 64 | int ulp_u = findUPar(u); 65 | int ulp_v = findUPar(v); 66 | if (ulp_u == ulp_v) return; 67 | if (size[ulp_u] < size[ulp_v]) { 68 | parent[ulp_u] = ulp_v; 69 | size[ulp_v] += size[ulp_u]; 70 | } 71 | else { 72 | parent[ulp_v] = ulp_u; 73 | size[ulp_u] += size[ulp_v]; 74 | } 75 | } 76 | }; 77 | 78 | 79 | 80 | class Solution { 81 | public: 82 | int findCircleNum(vector>& isConnected) { 83 | int V = isConnected.size(); 84 | DisjointSet ds(V); 85 | for(int i=0; i rank, parent, size; 4 | DisjointSet(int n) { 5 | rank.resize(n + 1, 0); 6 | parent.resize(n + 1); 7 | size.resize(n + 1); 8 | for (int i = 0; i <= n; i++) { 9 | parent[i] = i; 10 | size[i] = 1; 11 | } 12 | } 13 | int findUPar(int node) { 14 | if (node == parent[node]) 15 | return node; 16 | return parent[node] = findUPar(parent[node]); 17 | } 18 | void unionByRank(int u, int v) { 19 | int ulp_u = findUPar(u); 20 | int ulp_v = findUPar(v); 21 | if (ulp_u == ulp_v) return; 22 | if (rank[ulp_u] < rank[ulp_v]) { 23 | parent[ulp_u] = ulp_v; 24 | } 25 | else if (rank[ulp_v] < rank[ulp_u]) { 26 | parent[ulp_v] = ulp_u; 27 | } 28 | else { 29 | parent[ulp_v] = ulp_u; 30 | rank[ulp_u]++; 31 | } 32 | } 33 | void unionBySize(int u, int v) { 34 | int ulp_u = findUPar(u); 35 | int ulp_v = findUPar(v); 36 | if (ulp_u == ulp_v) return; 37 | if (size[ulp_u] < size[ulp_v]) { 38 | parent[ulp_u] = ulp_v; 39 | size[ulp_v] += size[ulp_u]; 40 | } 41 | else { 42 | parent[ulp_v] = ulp_u; 43 | size[ulp_u] += size[ulp_v]; 44 | } 45 | } 46 | }; 47 | 48 | class Solution { 49 | public: 50 | vector> accountsMerge(vector>& details) { 51 | int n = details.size(); 52 | DisjointSet ds(n); 53 | unordered_map mapMailNode; 54 | for(int i=0; i> mergeMail(n); 63 | for(auto it: mapMailNode){ 64 | string mail = it.first; 65 | int node = ds.findUPar(it.second); 66 | mergeMail[node].push_back(mail); 67 | } 68 | 69 | vector> ans; 70 | for(int i=0; i temp; 74 | temp.push_back(details[i][0]); 75 | for(auto it: mergeMail[i]){ 76 | temp.push_back(it); 77 | } 78 | ans.push_back(temp); 79 | } 80 | return ans; 81 | } 82 | }; -------------------------------------------------------------------------------- /Day316_Making_A_Large_Island.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | //User function Template for C++ 8 | class DisjointSet { 9 | public: 10 | vector rank, parent, size; 11 | DisjointSet(int n) { 12 | rank.resize(n + 1, 0); 13 | parent.resize(n + 1); 14 | size.resize(n + 1); 15 | for (int i = 0; i <= n; i++) { 16 | parent[i] = i; 17 | size[i] = 1; 18 | } 19 | } 20 | int findUPar(int node) { 21 | if (node == parent[node]) 22 | return node; 23 | return parent[node] = findUPar(parent[node]); 24 | } 25 | void unionByRank(int u, int v) { 26 | int ulp_u = findUPar(u); 27 | int ulp_v = findUPar(v); 28 | if (ulp_u == ulp_v) return; 29 | if (rank[ulp_u] < rank[ulp_v]) { 30 | parent[ulp_u] = ulp_v; 31 | } 32 | else if (rank[ulp_v] < rank[ulp_u]) { 33 | parent[ulp_v] = ulp_u; 34 | } 35 | else { 36 | parent[ulp_v] = ulp_u; 37 | rank[ulp_u]++; 38 | } 39 | } 40 | void unionBySize(int u, int v) { 41 | int ulp_u = findUPar(u); 42 | int ulp_v = findUPar(v); 43 | if (ulp_u == ulp_v) return; 44 | if (size[ulp_u] < size[ulp_v]) { 45 | parent[ulp_u] = ulp_v; 46 | size[ulp_v] += size[ulp_u]; 47 | } 48 | else { 49 | parent[ulp_v] = ulp_u; 50 | size[ulp_u] += size[ulp_v]; 51 | } 52 | } 53 | }; 54 | 55 | class Solution { 56 | private: 57 | bool isValid(int newr, int newc, int n){ 58 | return newr>=0 && newr=0 && newc>& grid) { 62 | int n = grid.size(); 63 | DisjointSet ds(n*n); 64 | for(int row=0; row components; 88 | for(int ind=0; ind<4; ind++){ 89 | int newr = row + dr[ind]; 90 | int newc = col + dc[ind]; 91 | if(isValid(newr, newc, n)){ 92 | if(grid[newr][newc]==1){ 93 | components.insert(ds.findUPar(newr*n + newc)); 94 | } 95 | } 96 | } 97 | int sizeTotal=0; 98 | for(auto it: components){ 99 | sizeTotal += ds.size[it]; 100 | } 101 | mx = max(mx, sizeTotal + 1); 102 | } 103 | } 104 | for(int cellNo=0; cellNo> t; 117 | while(t--){ 118 | 119 | int n; 120 | cin>>n; 121 | vector>grid(n,vector(n)); 122 | for(int i=0;i>grid[i][j]; 125 | Solution ob; 126 | cout< rank, parent, size; 3 | public: 4 | DisjointSet(int n) { 5 | rank.resize(n + 1, 0); 6 | parent.resize(n + 1); 7 | size.resize(n + 1); 8 | for (int i = 0; i <= n; i++) { 9 | parent[i] = i; 10 | size[i] = 1; 11 | } 12 | } 13 | 14 | int findUPar(int node) { 15 | if (node == parent[node]) 16 | return node; 17 | return parent[node] = findUPar(parent[node]); 18 | } 19 | 20 | void unionByRank(int u, int v) { 21 | int ulp_u = findUPar(u); 22 | int ulp_v = findUPar(v); 23 | if (ulp_u == ulp_v) return; 24 | if (rank[ulp_u] < rank[ulp_v]) { 25 | parent[ulp_u] = ulp_v; 26 | } 27 | else if (rank[ulp_v] < rank[ulp_u]) { 28 | parent[ulp_v] = ulp_u; 29 | } 30 | else { 31 | parent[ulp_v] = ulp_u; 32 | rank[ulp_u]++; 33 | } 34 | } 35 | 36 | void unionBySize(int u, int v) { 37 | int ulp_u = findUPar(u); 38 | int ulp_v = findUPar(v); 39 | if (ulp_u == ulp_v) return; 40 | if (size[ulp_u] < size[ulp_v]) { 41 | parent[ulp_u] = ulp_v; 42 | size[ulp_v] += size[ulp_u]; 43 | } 44 | else { 45 | parent[ulp_v] = ulp_u; 46 | size[ulp_u] += size[ulp_v]; 47 | } 48 | } 49 | }; 50 | 51 | class Solution { 52 | public: 53 | int removeStones(vector>& stones) { 54 | int n = stones.size(); 55 | int maxRow = 0; 56 | int maxCol = 0; 57 | for(auto it: stones){ 58 | maxRow = max(maxRow, it[0]); 59 | maxCol = max(maxCol, it[1]); 60 | } 61 | 62 | DisjointSet ds(maxRow + maxCol + 1); 63 | unordered_map stoneNodes; 64 | for(auto it: stones){ 65 | int nodeRow = it[0]; 66 | int nodeCol = it[1] + maxRow + 1; 67 | ds.unionBySize(nodeRow, nodeCol); 68 | stoneNodes[nodeRow]=1; 69 | stoneNodes[nodeCol]=1; 70 | } 71 | 72 | int cnt = 0; 73 | for(auto it: stoneNodes){ 74 | if(ds.findUPar(it.first)==it.first) cnt++; 75 | } 76 | 77 | return n - cnt; 78 | } 79 | }; -------------------------------------------------------------------------------- /Day322_Critical_Connections_in_a_Network.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int timer = 1; 3 | private: 4 | void dfs(int node, int parent, vector &vis, vector adj[], int tin[], int low[], vector> &bridges){ 5 | vis[node]=1; 6 | tin[node] = low[node] = timer; 7 | timer++; 8 | for(auto it: adj[node]){ 9 | if(it==parent) continue; 10 | if(vis[it]==0){ 11 | dfs(it, node, vis, adj, tin, low, bridges); 12 | low[node]=min(low[node],low[it]); 13 | // node--------it 14 | if(low[it]>tin[node]){ 15 | bridges.push_back({it, node}); 16 | } 17 | } 18 | else{ 19 | low[node] = min(low[node], low[it]); 20 | } 21 | } 22 | } 23 | public: 24 | vector> criticalConnections(int n, vector>& connections) { 25 | vector adj[n]; 26 | for(auto it: connections){ 27 | adj[it[0]].push_back(it[1]); 28 | adj[it[1]].push_back(it[0]); 29 | } 30 | vector vis(n, 0); 31 | int tin[n]; 32 | int low[n]; 33 | vector> bridges; 34 | dfs(0, -1, vis, adj, tin, low, bridges); 35 | return bridges; 36 | } 37 | }; -------------------------------------------------------------------------------- /Day327_Network_Delay_Time.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int node, int time, vector>> &adj, vector &dist) { 4 | if(time>=dist[node]) return; 5 | dist[node]=time; 6 | for (auto it : adj[node]) { 7 | int neighbour = it.first; 8 | int weight = it.second; 9 | dfs(neighbour, time+weight, adj, dist); 10 | } 11 | } 12 | 13 | int networkDelayTime(vector>& times, int n, int k) { 14 | vector>> adj(n + 1); // 1-based indexing 15 | for (auto it : times) { 16 | int u = it[0]; 17 | int v = it[1]; 18 | int w = it[2]; 19 | adj[u].push_back({v, w}); 20 | } 21 | vector dist(n + 1, INT_MAX); 22 | dfs(k, 0, adj, dist); 23 | 24 | int totalTime = 0; 25 | for(int i=1; i<=n; i++) { 26 | if(dist[i]==INT_MAX) return -1; 27 | totalTime=max(totalTime, dist[i]); 28 | } 29 | return totalTime; 30 | } 31 | }; -------------------------------------------------------------------------------- /Day35_Check_if_Array_Is_Sorted_and_Rotated.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool check(vector& nums){ 4 | int n = nums.size(); 5 | int count = 0; 6 | 7 | for (int i=1; i nums[i]) count++; 9 | } 10 | // condition property of sorted and rotated array. 11 | if (nums[n-1] > nums[0]) count++; 12 | // If the count of violations is less than or equal to 1, return true 13 | return (count<=1); 14 | } 15 | }; -------------------------------------------------------------------------------- /Day35_Remove_Duplicates_from_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int n = nums.size(); 5 | // set st; 6 | // for(int i=0; i& nums, int k) { 4 | k = k%nums.size(); 5 | reverse(nums.begin(), nums.end()); 6 | reverse(nums.begin(), nums.begin()+k); 7 | reverse(nums.begin()+k, nums.end()); 8 | } 9 | }; -------------------------------------------------------------------------------- /Day36_Move_Zeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int j=-1; 5 | for(int i=0; i& nums) { 4 | int maximum=0; 5 | int cnt=0; 6 | 7 | for(int i=0; i& nums) { 4 | int XOR1=0; 5 | int XOR2=0; 6 | 7 | for(int i=1; i<=nums.size(); i++){ 8 | XOR1 = XOR1^nums[i-1]; 9 | XOR2 = XOR2^i; 10 | } 11 | return XOR1^XOR2; 12 | } 13 | }; -------------------------------------------------------------------------------- /Day42_Single_Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int xoor=0; 5 | for(int i=0; i twoSum(vector& nums, int target) { 4 | vector ans; 5 | map mpp; 6 | for(int i=0; i& nums) { 4 | // sort(nums.begin(),nums.end()); 5 | int n = nums.size(); 6 | int low=0; 7 | int mid=0; 8 | int high=n-1; 9 | while(mid<=high){ 10 | if(nums[mid]==0){ 11 | swap(nums[low], nums[mid]); 12 | low++; 13 | mid++; 14 | } 15 | else if(nums[mid]==1) mid++; 16 | else{ 17 | swap(nums[mid], nums[high]); 18 | high--; 19 | } 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Day49_Majority_element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | int n = nums.size(); 5 | int cnt=0; 6 | int el; 7 | for(int i=0; i& prices) { 4 | int maxprofit=0, profit, mini=prices[0]; 5 | for(int i=1; i& nums) { 4 | int maxi=INT_MIN; 5 | int sum=0; 6 | for(int i=0; imaxi) maxi=sum; 9 | if(sum<0) sum=0; 10 | } 11 | // if(maxi<0) maxi=0; 12 | return maxi; 13 | } 14 | }; -------------------------------------------------------------------------------- /Day52_Rearrange_Array_Elements_by_Sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | vector ans(nums.size(),0); 5 | int posIndex=0; 6 | int negIndex=1; 7 | int n=nums.size(); 8 | 9 | for(int i=0; i& nums) { 4 | int n=nums.size(), longest=1; 5 | if(n==0) return 0; 6 | unordered_set st; 7 | for(int i=0; i& nums) { 4 | int ind=-1; 5 | int n=nums.size(); 6 | 7 | for(int i=n-2; i>=0; i--){ 8 | if(nums[i]ind; i--){ 19 | if(nums[i]>nums[ind]){ 20 | swap(nums[i], nums[ind]); 21 | break; 22 | } 23 | } 24 | reverse(nums.begin()+ind+1, nums.end()); 25 | return; 26 | } 27 | }; -------------------------------------------------------------------------------- /Day53_Replace_Elements_with_Greatest_Element_on_Right_Side.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector replaceElements(vector& arr) { 4 | int n=arr.size(); 5 | if(arr.size()==1) return {-1}; 6 | int Maxi = max(arr[n- 2], arr[n-1]); 7 | 8 | for(int i=n-3; i>=0; i--){ 9 | if(arr[i]>Maxi){ 10 | int temp=Maxi; 11 | Maxi=arr[i]; 12 | arr[i]=temp; 13 | } 14 | else arr[i] = Maxi; 15 | 16 | } 17 | arr[n-2]=arr[arr.size()-1]; 18 | arr[n-1]=-1; 19 | return arr; 20 | } 21 | }; -------------------------------------------------------------------------------- /Day54_Rotate_Image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | int n=matrix.size(); 5 | for(int i=0; i>& matrix) { 4 | vector rows; 5 | vector col; 6 | for(int i=0; i< matrix.size(); i++){ 7 | for(int j=0; j spiralOrder(vector>& mat) { 4 | vector ans; 5 | int n=mat.size(); 6 | int m=mat[0].size(); 7 | int top=0, left=0, bottom=n-1, right=m-1; 8 | 9 | // Loop until all elements are not traversed. 10 | while(top<=bottom && left<=right) { 11 | // For moving left to right 12 | for(int i=left; i<=right; i++) ans.push_back(mat[top][i]); 13 | top++; 14 | // For moving top to bottom. 15 | for(int i=top; i<=bottom; i++) ans.push_back(mat[i][right]); 16 | right--; 17 | // For moving right to left. 18 | if(top<=bottom){ 19 | for (int i=right; i>=left; i--) ans.push_back(mat[bottom][i]); 20 | bottom--; 21 | } 22 | // For moving bottom to top. 23 | if(left<=right){ 24 | for(int i=bottom; i>=top; i--)ans.push_back(mat[i][left]); 25 | left++; 26 | } 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Day55_Subarray_Sum_Equals_K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | int presum=0, cnt=0; 5 | map mpp; 6 | mpp[0]=1; 7 | for(int i=0; i getRow(int n) { 4 | long long ans=1; 5 | vector res; 6 | for(int i=0; i<=n; i++){ 7 | res.push_back(ans); 8 | ans*=(n-i); 9 | ans/=(i+1); 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /Day56_Pascal_Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector returnRow(int n){ 4 | vector ans; 5 | int term=1; 6 | ans.push_back(1); 7 | for(int col=1; col> generate(int numRows) { 15 | vector> ans; 16 | for(int i=1; i<=numRows; i++){ 17 | ans.push_back(returnRow(i)); 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /Day57_3Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& arr) { 4 | vector> ans; 5 | sort(arr.begin(), arr.end()); 6 | int n=arr.size(); 7 | 8 | for (int i=0; i0) k--; 19 | else { 20 | vector temp={arr[i], arr[j], arr[k]}; 21 | ans.push_back(temp); 22 | j++; 23 | k--; 24 | //skip the duplicates: 25 | while (j> fourSum(vector& nums, int target) { 4 | int n=nums.size(); 5 | vector> ans; 6 | sort(nums.begin(), nums.end()); 7 | 8 | for (int i=0; i0 && nums[i]==nums[i-1]) continue; 10 | for (int j=i+1; ji+1 && nums[j]==nums[j-1]) continue; 12 | // 2 pointers: 13 | int k=j+1; 14 | int l=n-1; 15 | while (k temp={nums[i], nums[j], nums[k], nums[l]}; 22 | ans.push_back(temp); 23 | k++; 24 | l--; 25 | //skip the duplicates: 26 | while (k majorityElement(vector& v){ 4 | int n=v.size(); 5 | int cnt1=0, cnt2=0; 6 | int el1=INT_MIN, el2=INT_MIN; 7 | 8 | // Applying the Extended Boyer Moore's Voting Algorithm: 9 | for(int i=0; i ls; // list of answers 26 | cnt1=0, cnt2=0; 27 | for(int i=0; i=mini) ls.push_back(el1); 33 | if(cnt2>=mini) ls.push_back(el2); 34 | 35 | // if it is told to sort the answer array: 36 | // sort(ls.begin(), ls.end()); //TC --> O(2*log2) ~ O(1); 37 | return ls; 38 | } 39 | }; -------------------------------------------------------------------------------- /Day58_Count_the_Number_of_Beautiful_Subarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long beautifulSubarrays(vector& nums) { 4 | int n=nums.size(); 5 | long long xr=0; 6 | unordered_map mpp; 7 | mpp[xr]++; // Insert the value {0,1}. 8 | long long cnt=0; 9 | int k=0; 10 | 11 | for(int i=0; i> merge(vector>& arr) { 4 | int n=arr.size(); 5 | sort(arr.begin(), arr.end()); 6 | vector> ans; 7 | 8 | for(int i=0; ians.back()[1]) ans.push_back(arr[i]); 11 | // if the current interval lies in the last interval 12 | else ans.back()[1] = max(ans.back()[1], arr[i][1]); 13 | } 14 | return ans; 15 | } 16 | }; -------------------------------------------------------------------------------- /Day59_Merge_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int n, vector& nums2, int m) { 4 | int i=n; 5 | for(int j=0; j &count, vector> &v, int left, int mid, int right) { 4 | vector> temp(right-left+1); 5 | int i=left; 6 | int j=mid+1; 7 | int k=0; 8 | 9 | while(i<=mid && j<=right) { 10 | // mind that we're sorting in descending order 11 | if (v[i].first<=v[j].first) temp[k++] = v[j++]; 12 | else { 13 | // only line responsible to update count, related to problem constraint, 14 | // remaining part is just regular mergeSort 15 | count[v[i].second] += right-j+1; 16 | temp[k++]=v[i++]; 17 | } 18 | } 19 | while(i<=mid) temp[k++]=v[i++]; 20 | while(j<=right) temp[k++]=v[j++]; 21 | for(int i=left; i<=right; i++) v[i]=temp[i-left]; 22 | } 23 | 24 | 25 | void mergeSort(vector &count, vector> &v, int left, int right) { 26 | if (left>=right) return; 27 | int mid=left+(right-left)/2; 28 | mergeSort(count, v, left, mid); 29 | mergeSort(count, v, mid+1, right); 30 | merge(count, v, left, mid, right); 31 | } 32 | 33 | 34 | vector countSmaller(vector& nums) { 35 | int n=nums.size(); 36 | vector> v(n); 37 | 38 | for (int i=0; i count(n, 0); 40 | 41 | // sorting in descending order 42 | mergeSort(count, v, 0, n-1); 43 | return count; 44 | } 45 | }; -------------------------------------------------------------------------------- /Day60_Find_All_Duplicates_in_an_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicates(vector& nums) { 4 | vector result; 5 | unordered_map freq; 6 | 7 | for (int num : nums) { 8 | freq[num]++; 9 | } 10 | 11 | for (auto pair : freq) { 12 | if (pair.second>1) { 13 | result.push_back(pair.first); 14 | } 15 | } 16 | return result; 17 | } 18 | }; -------------------------------------------------------------------------------- /Day60_Find_All_Numbers_Disappeared_in_an_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDisappearedNumbers(vector& nums) { 4 | int n=nums.size(); 5 | vectorfreq(n+1, 0); 6 | vectorres{}; 7 | 8 | for(auto num: nums){ 9 | freq[num]++; 10 | } 11 | 12 | for(int i{1}; i<=n; ++i){ 13 | if(!freq[i]) res.push_back(i); 14 | } 15 | return res; 16 | } 17 | }; -------------------------------------------------------------------------------- /Day60_Find_Missing_and_Repeated_Values.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findMissingAndRepeatedValues(vector>& grid) { 4 | int n = grid.size(),sum=0; 5 | vector s; 6 | 7 | for(int i=0; i ans(2); 15 | 16 | for(int i=0; i0 && s[i]==s[i-1]) { 18 | ans[0]=s[i-1]; 19 | } 20 | } 21 | 22 | int m=n*n; 23 | int count=(m*(m+1))/2; 24 | 25 | ans[1]=count-(sum-ans[0]); 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Day60_Find_the_Duplicate_Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | unordered_map map; 5 | for(int i=0; i& nums) { 4 | int n=nums.size(); 5 | double ans=INT_MIN; 6 | double pre=1; 7 | double suf=1; 8 | 9 | for(int i=0; i &arr, int low, int mid, int high) { 5 | vector temp; 6 | int left=low; 7 | int right=mid+1; 8 | 9 | // Storing elements in temp array in a sorted manner. 10 | while (left<=mid && right<=high) { 11 | if (arr[left]<=arr[right]) temp.push_back(arr[left++]); 12 | else temp.push_back(arr[right++]); 13 | } 14 | 15 | // if elements on the left half are still left // 16 | while(left<=mid) temp.push_back(arr[left++]); 17 | // if elements on the right half are still left // 18 | while(right<=high) temp.push_back(arr[right++]); 19 | // transfering all elements from temporary to arr // 20 | for (int i=low; i<=high; i++) arr[i]=temp[i-low]; 21 | } 22 | 23 | int countPairs(vector &arr, int low, int mid, int high) { 24 | int right=mid+1; 25 | int cnt=0; 26 | for (int i=low; i<=mid; i++) { 27 | while (right<=high && arr[i]>(2ll*arr[right])) right++; 28 | cnt+=(right-(mid+1)); 29 | } 30 | return cnt; 31 | } 32 | 33 | int mergeSort(vector &arr, int low, int high) { 34 | int cnt=0; 35 | if (low>=high) return cnt; 36 | int mid=(low+high)/2 ; 37 | cnt+=mergeSort(arr, low, mid); // left half 38 | cnt+=mergeSort(arr, mid + 1, high); // right half 39 | cnt+=countPairs(arr, low, mid, high); //Modification 40 | merge(arr, low, mid, high); // merging sorted halves 41 | return cnt; 42 | } 43 | 44 | int reversePairs(vector& nums) { 45 | int n=nums.size(); 46 | return mergeSort(nums, 0, n-1); 47 | } 48 | }; -------------------------------------------------------------------------------- /Day65_Search_a_2D_Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | int n=matrix.size(); 5 | int m=matrix[0].size(); 6 | if (n==0) return false; 7 | 8 | int i=0, j=m-1; 9 | 10 | while (i=0) { 11 | if (matrix[i][j]==target) return true; 12 | else if (matrix[i][j]>target) j--; 13 | else i++; 14 | } 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /Day66_Binary_Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& arr, int target) { 4 | int start=0, end=arr.size()-1; 5 | int mid=(start+end)/2; 6 | 7 | while (start<=end) { 8 | if (arr[mid]==target) return mid; 9 | else if (arr[mid]& nums, int target) { 4 | int ans = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); 5 | return ans; 6 | } 7 | }; -------------------------------------------------------------------------------- /Day74_Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int First(vector& nums, int target, int n){ 4 | int low=0, high=n-1; 5 | int first=-1; 6 | 7 | while(low<=high){ 8 | int mid=(low+high)/2; 9 | if(nums[mid]==target) first=mid, high=mid-1; 10 | else if(nums[mid]& nums, int target, int n){ 17 | int low=0, high=n-1; 18 | int last=-1; 19 | 20 | while(low<=high){ 21 | int mid=(low+high)/2; 22 | if(nums[mid]==target) last=mid, low=mid+1; 23 | else if(nums[mid] searchRange(vector& nums, int target) { 30 | int n=nums.size(); 31 | vector ans; 32 | 33 | ans.push_back(First(nums, target, n)); 34 | ans.push_back(Last(nums, target, n)); 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /Day77_Search_in_Rotated_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& arr, int k) { 4 | int n=arr.size(); 5 | int low=0, high=n-1; 6 | 7 | while(low<=high) { 8 | int mid=(low+high)/2; 9 | //if mid points the target 10 | if (arr[mid]==k) return mid; 11 | 12 | //if left part is sorted: 13 | if (arr[low]<=arr[mid]) { 14 | //element exists: 15 | if (arr[low]<=k && k<=arr[mid]) high=mid-1; 16 | //element does not exist: 17 | else low=mid+1; 18 | } 19 | 20 | // if right part is sorted: 21 | else { 22 | //element exists: 23 | if (arr[mid]<=k && k<=arr[high]) low=mid+1; 24 | //element does not exist: 25 | else high=mid-1; 26 | } 27 | } 28 | return -1; 29 | } 30 | }; -------------------------------------------------------------------------------- /Day79_Search_in_Rotated_Sorted_Array_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector& arr, int k) { 4 | int n=arr.size(); 5 | int low=0, high=n-1; 6 | 7 | while (low<=high) { 8 | int mid = low + (high-low)/2; 9 | 10 | // if mid points the target 11 | if (arr[mid]==k) return -1; 12 | 13 | // Edge case: arr[low]==arr[mid]==arr[high] 14 | if (arr[low]==arr[mid] && arr[mid]==arr[high]) { 15 | low=low+1; 16 | high=high-1; 17 | continue; 18 | } 19 | 20 | // if left part is sorted: 21 | else if (arr[low]<=arr[mid]) { 22 | if (arr[low]<=k && k<=arr[mid]) high=mid-1; 23 | else low=mid+1; 24 | } 25 | // if right part is sorted: 26 | else { 27 | if (arr[mid]<=k && k<=arr[high]) low=mid+1; 28 | else high=mid-1; 29 | } 30 | } 31 | return 0; 32 | } 33 | }; -------------------------------------------------------------------------------- /Day83_Find_Minimum_in_Rotated_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& arr) { 4 | int low=0, high=arr.size()-1; 5 | int ans=INT_MAX; 6 | 7 | while (low <= high) { 8 | int mid=(low+high)/2; 9 | // Search Space=Sorted, 10 | // then arr[low] is min. 11 | if (arr[low]<=arr[high]) { 12 | ans=min(ans, arr[low]); 13 | break; 14 | } 15 | 16 | if (arr[low]<=arr[mid]) { 17 | ans=min(ans, arr[low]); 18 | low=mid+1; 19 | } 20 | 21 | else { 22 | ans=min(ans, arr[mid]); 23 | high=mid-1; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Day86_Single_Element_in_a_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNonDuplicate(vector& arr) { 4 | int n = arr.size(); 5 | //Edge cases: 6 | if (n==1) return arr[0]; 7 | if (arr[0]!=arr[1]) return arr[0]; 8 | if (arr[n-1]!=arr[n-2]) return arr[n-1]; 9 | 10 | int low=1, high=n-2; 11 | while (low<=high) { 12 | int mid=(low+high)/2; 13 | //if arr[mid] is the single element: 14 | if (arr[mid]!=arr[mid+1] && arr[mid]!=arr[mid-1]) return arr[mid]; 15 | //we are in the left: 16 | if ((mid%2==1 && arr[mid]==arr[mid-1])||(mid%2==0 && arr[mid]==arr[mid+1])) low=mid+1; 17 | //we are in the right: 18 | else high = mid - 1; 19 | } 20 | // dummy return statement: 21 | return -1; 22 | } 23 | }; -------------------------------------------------------------------------------- /Day8_Reverse_integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int temp = x; 5 | long a=0; 6 | while(x!=0) { 7 | a = a*10 + x%10; 8 | x /= 10; 9 | } 10 | if (a>INT_MAX || a& arr) { 4 | int n = arr.size(); 5 | 6 | // Edge cases: 7 | if (n==1) return 0; 8 | if (arr[0]>arr[1]) return 0; 9 | if (arr[n-1]>arr[n-2]) return n-1; 10 | 11 | int low=1, high=n-2; 12 | while(low<=high) { 13 | int mid=(low+high)/2; 14 | //If arr[mid] is the peak: 15 | if (arr[mid-1]arr[mid+1]) return mid; 16 | // If we are in the left: 17 | if (arr[mid]>arr[mid-1]) low=mid+1; 18 | // If we are in the right or arr[mid] is a common point. 19 | else high=mid-1; 20 | } 21 | return -1; 22 | } 23 | }; -------------------------------------------------------------------------------- /Day90_Find_the_Key_of_the_Numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int generateKey(int num1, int num2, int num3) { 4 | string str1 = string(4-to_string(num1).length(), '0') + to_string(num1); 5 | string str2 = string(4-to_string(num2).length(), '0') + to_string(num2); 6 | string str3 = string(4-to_string(num3).length(), '0') + to_string(num3); 7 | string ans; 8 | 9 | for(int i=0; i<4; i++){ 10 | char mini=min(str1[i], min(str2[i], str3[i])); 11 | ans.push_back(mini); 12 | } 13 | int result=stoi(ans); 14 | return result; 15 | } 16 | }; -------------------------------------------------------------------------------- /Day91_Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long double power(double x, long int n) { 4 | if (n==1) return x; 5 | if (n==0) return 1; 6 | if (n<0) return 1/power(x, -n); 7 | if (n%2==0) return power(x*x, n/2); 8 | else return x*power(x*x, n/2); 9 | } 10 | 11 | long double myPow(double x, int n) { 12 | return power(x, n); 13 | } 14 | }; -------------------------------------------------------------------------------- /Day92_Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | int ans = sqrt(x); 5 | return ans; 6 | } 7 | }; -------------------------------------------------------------------------------- /Day93_Koko_Eating_Bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool possible(vector piles, int mid, int h){ 4 | long long hours=0; 5 | for(int i=0; i0) hours++; 9 | if(hours>h) return false; 10 | } 11 | return true; 12 | } 13 | 14 | int minEatingSpeed(vector& piles, int h) { 15 | int min=1; 16 | int max=*max_element(piles.begin(),piles.end()); 17 | int ans=0; 18 | 19 | while(min<=max){ 20 | int mid=(min+max)/2; 21 | if(possible(piles, mid, h)){ 22 | ans=mid; 23 | max=mid-1; 24 | } 25 | else min=mid+1; 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Day94_Minimum_Number_of_Days_to_Make_m_Bouquets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool possible(vector &arr, int day, int m, int k) { 4 | int n=arr.size(); 5 | int cnt=0; 6 | int noOfB=0; 7 | 8 | // count number of bouquets: 9 | for (int i=0; i=m; 18 | } 19 | 20 | int minDays(vector& arr, int m, int k) { 21 | long long val= m*1ll*k*1ll; 22 | int n=arr.size(); 23 | if (val>n) return -1; // impossible case. 24 | 25 | //find maximum and minimum: 26 | int mini=INT_MAX, maxi=INT_MIN; 27 | for (int i=0; i &arr, int div) { 4 | int n=arr.size(); 5 | //Find the summation of division values: 6 | int sum=0; 7 | for (int i=0; i& arr, int limit) { 12 | int n=arr.size(); 13 | if (n>limit) return -1; 14 | int low=1, high =*max_element(arr.begin(), arr.end()); 15 | 16 | //Apply binary search: 17 | while (low<=high) { 18 | int mid=(low+high)/2; 19 | if (sumByD(arr, mid)<=limit) { 20 | high=mid-1; 21 | } 22 | else low=mid+1; 23 | } 24 | return low; 25 | } 26 | }; -------------------------------------------------------------------------------- /Day96_Capacity_To_Ship_Packages_Within_D_Days.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDays(vector &weights, int cap) { 4 | int days=1; 5 | int load=0; 6 | int n=weights.size(); 7 | 8 | for (int i=0; icap) { 10 | days+=1; 11 | load=weights[i]; 12 | } 13 | //load the weight on the same day. 14 | else load+=weights[i]; 15 | } 16 | return days; 17 | } 18 | 19 | int shipWithinDays(vector &weights, int days) { 20 | int low=*max_element(weights.begin(), weights.end()); 21 | int high=accumulate(weights.begin(), weights.end(), 0); 22 | 23 | while (low <= high) { 24 | int mid=(low+high)/2; 25 | int numberOfDays=findDays(weights, mid); 26 | if (numberOfDays<=days) high=mid-1; 27 | else low=mid+1; 28 | } 29 | return low; 30 | } 31 | }; -------------------------------------------------------------------------------- /Day97_Kth_Missing_Positive_Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthPositive(vector& arr, int k) { 4 | int n=arr.size(); 5 | int low=0, high=n-1; 6 | 7 | while (low<=high) { 8 | int mid=(low+high)/2; 9 | int missing=arr[mid]-(mid+1); 10 | if (missing