├── Searching ├── Analysis.md ├── count_squares.cpp ├── peak_element.cpp ├── find_pair_difference.cpp └── common_elements_in_3_sorted_arrays.cpp ├── Binary Search Tree ├── README.md ├── minimum_element_in_bst.cpp ├── lowest_common_ancestor_of_BST.cpp ├── ceil_in_bst.cpp ├── find_closest_element_in_BST.cpp ├── floor_in_bst.cpp ├── smaller_on_right.cpp ├── populate_inorder_successor_of_all_nodes.cpp ├── kth_smallest_element_in_BST.cpp ├── check_whether_BST_contains_dead_end.cpp ├── construct_BST_from_preorder.cpp ├── insert_node_in_bst.cpp ├── check_for_BST.cpp ├── kth_largest_element_in_BST.cpp ├── fixing_two_nodes_of_BST.cpp ├── count_BST_nodes_that_lie_in_given_range.cpp ├── find_common_nodes_in_two_BSTs.cpp └── brothers_from_different_roots.cpp ├── 00 Interview-prep └── Binary Search Tree │ ├── dummy │ └── Sorted List to BST │ └── README.md ├── Codechef ├── special_triplets.cpp ├── chef_and_bulb_invention.cpp ├── olympics_ratings.cpp ├── problem_difficulties.cpp ├── summer_heat.cpp ├── richie_rich.cpp ├── chess_match.cpp ├── yet_another_sod_problem.cpp ├── cyclic_quadrilateral.cpp ├── chef_and_spells.cpp ├── the_two_dishes.cpp ├── maximum_light_up.cpp ├── obtain_the_sum.cpp ├── magical_doors.cpp ├── find_the_direction.cpp ├── false_number.cpp ├── three_dices.cpp ├── cricket_ranking.cpp ├── chef_in_vaccination_queue.cpp ├── penalty_shots.cpp ├── beautiful_pairs.cpp ├── the_grid_fill_problem.cpp ├── red_alert.cpp ├── from_rational_to_binary.cpp ├── bella_ciao.cpp ├── joker_and_batman.cpp ├── bitwise_tuples.cpp ├── html_tags.cpp ├── prefix_sums.cpp ├── even_tuples.cpp └── total_correct_submissions.cpp ├── Stack ├── implement_k_stacks_in_an_array.cpp ├── reverse_a_string_using_stack.cpp ├── stock_span.cpp ├── next_greater_element.cpp ├── special_stack.cpp ├── delete_middle_element_of_stack.cpp ├── implement_two_stacks_in_array.cpp ├── implement stack using queues.cpp ├── evaluation_of_postfix_expression.cpp ├── parenthesis_checker.cpp ├── valid_substring.cpp └── maximum_rectangular_area_of_histogram.cpp ├── Codeforces ├── A-watermelon.cpp ├── A-regular_bracket_sequence.cpp ├── A-Casimir's_string_solitaire.cpp ├── A-cherry.cpp ├── A-odd_set.cpp ├── A-find_the_array.cpp ├── A-pretty_permutations.cpp ├── A-balanced_substring.cpp ├── E1-permutation_minimization_by_deque.cpp ├── B-fedor_and_new_game.cpp ├── B1-wonderful_coloring-1.cpp ├── A-polycarp_and_coins.cpp ├── A-exciting_bets.cpp ├── B-customizing_the_track.cpp ├── B-random_teams.cpp ├── A-lever.cpp ├── B-plus_and_multiply.cpp ├── A-point_on_spiral.cpp ├── B-numbers_box.cpp ├── A-shortest_path_with_obstacle.cpp ├── A-pizzaForces.cpp └── A-single_push.cpp ├── Recursion and Backtracking ├── README.md ├── subsets_of_string.cpp ├── valid_sudoku.cpp ├── print_maze_paths.cpp ├── print_zigzag.java ├── permutation_of_string.cpp └── possible_words from phone_digits.cpp ├── Bit Manipulation ├── power_of_two.cpp ├── single number.cpp ├── number_of_1_bits.cpp ├── rightmost_different_bit.cpp ├── bit_manipulation.cpp ├── find_position_of_set_bit.cpp ├── bit_difference.cpp ├── swap_all_odd_and_even_bits.cpp └── power_set.cpp ├── Hashing ├── count_distinct_elements.cpp ├── count_frequency.cpp ├── union_of_two_arrays.cpp ├── array_is_a_subset_of_another_array.cpp ├── intersection_of_two_arrays.cpp ├── longest_consecutive_subsequence.cpp ├── subarray_with_given_sum.cpp ├── subarray_with_sum_0.cpp ├── count_pairs_with_given_sum.cpp ├── count_distinct_element_in_every_window.cpp ├── longest_subarray_with_sum_k.cpp └── second_most_repeated_string_in_a_subsequence.cpp ├── Binary Tree ├── height_of_binary_tree.cpp ├── Inorder_traversal_recursive.cpp ├── Preorder_traversal_recursive.cpp ├── Postorder_traversal_recursive.cpp ├── maximum_and_minimum_of_binary_tree.cpp ├── Preorder_traversal_iterative.cpp ├── vertical_sum.cpp ├── check_if_binary_tree_is_sum_tree.cpp ├── transform_to_sum_tree.cpp ├── diameter_of_binary_tree.cpp ├── maximum_width_of_binary_tree.cpp ├── binary_tree_to_doubly_linked_list.cpp ├── size_of_binary_tree.cpp ├── Inorder_traversal_iterative.cpp ├── check_if_tree_is_isomorphic.cpp ├── Postorder_traversal_iterative_2_stacks.cpp ├── check_if_tree_is_balanced_or_not.cpp ├── children_sum_parent.cpp ├── Postorder_traversal_iterative_1_stack.cpp ├── leaf_at_same_level.cpp ├── zigzag_traversal.cpp ├── reverse_level_order_traversal.cpp ├── serialize_and_deserialize_binary_tree.cpp └── left_view_of_binary_tree.cpp ├── Leetcode Daily Challenge ├── partition equal subset sum.cpp ├── minimum cost to move chips to the same position.cpp ├── domino and tromino trilling.cpp ├── consecutive characters.cpp ├── house robber.cpp ├── maximum product subarray.cpp ├── jump game III.cpp ├── insertion sort list.cpp ├── binary tree tilt.cpp ├── convert binary number in linked list to integer.cpp ├── nth magical number.cpp └── odd even linked list.cpp ├── Arrays ├── next greater element III.cpp ├── buy_sell_stock.cpp ├── majority element.cpp ├── two sum.cpp ├── merge intervals.cpp ├── smallest_subarray_having_sum_greater_than_a_given_value.cpp ├── sort colors.cpp ├── longest_repeating_character_replacement.cpp ├── minimum number of arrows to burst ballons(merge interval type Q).cpp ├── container with most water.cpp ├── maximum_product_subarray.cpp ├── finding 3 digit even numbers.cpp ├── maximum_sum_of_subarray_less_than_or_equal_to_x.cpp ├── rotate_a_number.java ├── length_of_longest_substring.cpp ├── Number_of_subarrays_with maximum_values_in_given_range.cpp ├── longest_substring_with_at_most_k_distinct_characters.cpp ├── subarray_with_given_sum.cpp └── substring_of_length_k_with_k-1_distinct_elements.cpp ├── Linked List ├── check_if_circular_linked_list.cpp ├── delete_without_head_pointer.cpp ├── delete_kth_node_from_circular_linked_list.cpp ├── README.md ├── reverse_doubly_linked_list.cpp ├── middle_element_of_linked_list.cpp ├── remove_duplicates_from_sorted_linked_list.cpp ├── multiply_two_linked_lists.cpp ├── length_of_the_loop.cpp ├── given_linked_list_of_0s_1s_and_2s_sort_it.cpp ├── linked list cycle II.cpp ├── split_circular_linked_list_into_two_halves.cpp ├── intersection_point_in_Y_shapped_linked_lists.cpp ├── reverse_linked_list_in_groups_of_given_size.cpp ├── nth_node_from_end_of_the_linked_list.cpp ├── delete middle node of a linked list.cpp ├── remove_duplicates_from_unsorted_linked_list.cpp └── partition list.cpp ├── Math tricks ├── primality_test.cpp ├── power_logarithmic.cpp ├── consecutive_numbers_that_sum_up_to_given_number.cpp ├── gcd_of_array.cpp ├── binary_exponention.cpp └── gcd_by_euclidean.cpp ├── Strings ├── palindrome_string.cpp ├── isomorphic_strings.cpp └── factorial_of_large_numbers.cpp ├── Queue ├── queue_reversal.cpp ├── generate_binary_numbers.cpp ├── find winner of circular game.cpp ├── implementation_of_dequeue_stl.cpp ├── implement queues using stack.cpp ├── reverse_first_k_elements_of_queue.cpp ├── implementation_of_queue_stl.cpp ├── queue_using_two_stacks.cpp └── first_negative_integer_in_every_window_of_size_k.cpp ├── Greedy ├── task scheduler.cpp ├── gas station.cpp ├── minimum number of arrows to burst ballons(merge interval type Q).cpp └── candy.cpp ├── Matrix ├── rotate_image.cpp ├── sorted_matrix.cpp ├── row_with_max_1s.cpp └── make_matrix_beautiful.cpp ├── Graphs ├── shortest_path_in_undirected_graph.cpp ├── DFS.cpp ├── topological_sort_using_dfs.cpp ├── BFS.cpp └── detect_the_cycle_in_undirected_graph_using_DFS.cpp ├── Heaps and Priority Queues ├── top k frequent elements.cpp └── find k closest elements.cpp ├── Dynamic Progamming ├── 14 print longest common subsequence.cpp ├── 21 sequence pattern matching.cpp ├── 20 longest repeating subsequence.cpp ├── 18 longest palindromic subsequence.cpp ├── 22 minimum number of insertions to make string palindrome.cpp ├── 16 print shortest common supersequence.cpp ├── 19 minimum number of deletions to make string palindrome.cpp ├── 17.01 delete operation for two strings.cpp ├── 13 longest common substring.cpp ├── 09 coin change problem(total number of ways).cpp ├── 07 unbounded knapsack.cpp ├── 08 rod cutting problem.cpp ├── 01 subsetSum.cpp ├── 0-1 knapsack.cpp ├── 17.02 edit distance.cpp ├── 03 count subset with given sum.cpp ├── 15 shortest common supersequence.cpp └── 10 coin change problem (minimum number of coins).cpp ├── Sorting ├── chocolate_distribution_problem.cpp ├── three_way_partitioning.cpp ├── Sorting_Algorithms │ ├── Insertionsort.cpp │ └── Selectionsort.cpp ├── sort_using_comparator.cpp ├── merge_intervals.cpp └── sort_by_set_bit.cpp ├── resources.md ├── Other Competitions └── ediblity_test.cpp └── Prefix Sum └── array_manipulation.cpp /Searching/Analysis.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Binary Search Tree/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /00 Interview-prep/Binary Search Tree/dummy: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Codechef/special_triplets.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/AUG21C/problems/SPCTRIPS 2 | -------------------------------------------------------------------------------- /Codechef/chef_and_bulb_invention.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/AUG21C/problems/CHFINVNT 2 | -------------------------------------------------------------------------------- /Codechef/olympics_ratings.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/AUG21C/problems/OLYRANK 2 | 3 | -------------------------------------------------------------------------------- /Codechef/problem_difficulties.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/AUG21C/problems/PROBDIFF 2 | -------------------------------------------------------------------------------- /Stack/implement_k_stacks_in_an_array.cpp: -------------------------------------------------------------------------------- 1 | ARTICLE: https://www.geeksforgeeks.org/efficiently-implement-k-stacks-single-array/ 2 | -------------------------------------------------------------------------------- /Codeforces/A-watermelon.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | long int w; 7 | cin>>w; 8 | if((w%2) == 0 && w != 2) cout<<"YES"<& nums) { 2 | // xor operation 3 | int n = nums.size(); 4 | int Xor = nums[0]; 5 | for(int i=1; i s; 4 | for(int i=0; i 2 | using namespace std; 3 | int countSquares(int a, int b) 4 | { 5 | return (floor(sqrt(b)) - ceil(sqrt(a)) + 1); 6 | } 7 | int main() 8 | { 9 | int a = 9, b = 25; 10 | cout << "Count of squares is "<< countSquares(a, b); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /00 Interview-prep/Binary Search Tree/Sorted List to BST/README.md: -------------------------------------------------------------------------------- 1 | 1. try this question: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | 2. just replace finding mid from (low + high) / 2 with slow and fast method and done 3 | 3. we have considered node and nextToEndNode instead of low and high pointers 4 | -------------------------------------------------------------------------------- /Binary Tree/height_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | //Function to find the height of a binary tree. 2 | 3 | // problem link: https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1 4 | int height(struct Node* node){ 5 | if(node == NULL) return 0; 6 | return max(height(node->left), height(node->right))+1; 7 | } 8 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/partition equal subset sum.cpp: -------------------------------------------------------------------------------- 1 | bool canPartition(vector& nums) { 2 | int sum = accumulate(nums.begin(), nums.end(), 0); 3 | 4 | if (sum%2) return false; 5 | bitset<20001> bits(1); 6 | for (auto &num : nums) bits |= bits << num; 7 | return bits[sum/2]; 8 | } 9 | -------------------------------------------------------------------------------- /Binary Search Tree/minimum_element_in_bst.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/minimum-element-in-bst/1# 2 | int minValue(Node* curr) { 3 | while(curr != NULL && curr->left != NULL) 4 | { 5 | if(curr->left) curr = curr->left; 6 | else return curr->data; 7 | } 8 | return curr->data; 9 | } 10 | -------------------------------------------------------------------------------- /Codechef/summer_heat.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/JUNE21C/problems/COCONUT 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t; 8 | cin>>t; 9 | for(int i=0; i>xa>>xb>>ya>>yb; 13 | cout<<(ya/xa)+(yb/xb)< mp; 4 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>a>>b>>x; 13 | cout<<(b-a)/x< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>n>>a>>b; 13 | cout<<(2*(180+n) - a - b)< INT_MAX) return -1; 8 | return ans; 9 | } 10 | 11 | return -1; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Binary Tree/Inorder_traversal_recursive.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/inorder-traversal/1# 2 | vector inOrder(Node* root) { 3 | 4 | if(root != NULL) 5 | { 6 | inOrder(root->left); 7 | ans.push_back(root->data); 8 | inOrder(root->right); 9 | } 10 | return ans; 11 | } 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/minimum cost to move chips to the same position.cpp: -------------------------------------------------------------------------------- 1 | int minCostToMoveChips(vector& position) { 2 | int even = 0, odd = 0, cost = 0; 3 | int n = position.size(); 4 | for(int i=0; inext; 7 | while(curr != head && curr != NULL) 8 | { 9 | curr = curr->next; 10 | } 11 | if(curr == NULL) return false; 12 | return true; 13 | } 14 | -------------------------------------------------------------------------------- /Stack/reverse_a_string_using_stack.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/reverse-a-string-using-stack/1 2 | char* reverse(char *str, int len) 3 | { 4 | stack s; 5 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>l>>r; 13 | ans=(r/3)-(l/3); 14 | if(l%3 == 0 ) ans++; 15 | 16 | cout<data = del->next->data; // copying the data 7 | Node *temp = del->next; 8 | del->next = del->next->next; 9 | delete(temp); 10 | } 11 | -------------------------------------------------------------------------------- /Math tricks/primality_test.cpp: -------------------------------------------------------------------------------- 1 | // used for: Given a number n, check if it is prime or not 2 | // a*b=n 3 | // For a divisor a, b one of the divisors lies above sqrt(n) and one will be below sqrt(n) 4 | // time complexity : O (sqrt (n)) 5 | 6 | bool isPrime(int n) 7 | { 8 | if(n == 1) return false; 9 | for(int i=2; i*i<=n; i++) 10 | { 11 | if(n % i == 0) return false; 12 | } 13 | return true; 14 | } 15 | -------------------------------------------------------------------------------- /Strings/palindrome_string.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/palindrome-string0817/1 2 | 3 | 4 | int isPalindrome(string str) 5 | { 6 | int start=0, end=str.length()-1; 7 | while(start < end) 8 | { 9 | if(str[start++] != str[end--]) return 0; 10 | else 11 | { 12 | if(start >= end) return 1; 13 | } 14 | } 15 | return 1; 16 | } 17 | -------------------------------------------------------------------------------- /Codechef/cyclic_quadrilateral.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/START5B/problems/CYCLICQD 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>a>>b>>c>>d; 13 | if(a+c == 180 && b+d == 180) cout<<"YES"< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>a>>b>>c; 13 | if(a+b > b+c) max = a+b; 14 | else max = b+c; 15 | if(max < a+c) max = a+c; 16 | cout< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long long int t; 8 | cin>>t; 9 | for(int i=0; i>n>>s; 13 | if(n >= s) cout< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>p>>a>>b>>c>>x>>y; 13 | if((a*x+b) < (a*y +c)) ans = (p/(a*x +b)); 14 | else ans= (p/(a*y +c)); 15 | cout< s; 8 | for(int i=0; i rev(queue q) 3 | { 4 | queue q1; 5 | stack s; 6 | int len = q1.size(); 7 | while(! q.empty()) 8 | { 9 | s.push(q.front()); 10 | q.pop(); 11 | } 12 | while(! s.empty()) 13 | { 14 | q1.push(s.top()); 15 | s.pop(); 16 | } 17 | return q1; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Arrays/buy_sell_stock.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ 2 | int maxProfit(vector& arr) { 3 | int n = arr.size(),index; 4 | // kadane's algorithm 5 | int mini=arr[0], maxi=0; 6 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long long int t; 8 | cin>>t; 9 | for(int i=0; i>n>>s; 13 | sum =((n*(n+1))/2); 14 | if(sum - s >0 && sum-s <= n) cout<& nums) { 2 | int n = nums.size(); 3 | int count = 0, major; 4 | for(int i=0; i &ans) 3 | { 4 | if(root != NULL) 5 | { 6 | ans.push_back(root->data); 7 | solve(root->left, ans); 8 | solve(root->right, ans); 9 | } 10 | } 11 | vector preorder(Node* root) 12 | { 13 | vector ans; 14 | solve(root, ans); 15 | 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Math tricks/power_logarithmic.cpp: -------------------------------------------------------------------------------- 1 | // print x^n using recursion: 2 | // naive way isuse the logic: x*func(x, n) 3 | // to optimize it we use logarithimic logic: x^n = x^n/2 * x^n/2 if n---->even 4 | // x^n = x^n/2 * x^n/2 * x if n---->odd 5 | int power(int x, int n) 6 | { 7 | if(n == 0) return 1; 8 | int temp = power(x, n/2); 9 | int ans = temp*temp; 10 | if(n % 2 == 0) 11 | { 12 | ans = ans*x; 13 | } 14 | return ans; 15 | } 16 | -------------------------------------------------------------------------------- /Hashing/array_is_a_subset_of_another_array.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/array-subset-of-another-array2317/1 2 | string isSubset(int a1[], int a2[], int n, int m) { 3 | unordered_set s; 4 | for(int i=0; i &ans) 3 | { 4 | if(root != NULL) 5 | { 6 | solve(root->left, ans); 7 | solve(root->right, ans); 8 | 9 | ans.push_back(root->data); 10 | } 11 | } 12 | vector postOrder(Node* root) 13 | { 14 | vector ans; 15 | solve(root, ans); 16 | 17 | return ans; 18 | } 19 | -------------------------------------------------------------------------------- /Codeforces/A-regular_bracket_sequence.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/problemset/problem/1469/A 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long long int t; 8 | cin>>t; 9 | for(int z=0; z>s; 13 | long long int len = s.length(); 14 | 15 | if(len % 2 != 0 || s[0] == ')' || s[len-1] == '(') 16 | { 17 | cout<<"NO"< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>s; 13 | long int len = s.length(),count=0; 14 | // 1 open 15 | if(s[0] == '0') count++; 16 | for(int j=1; j 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long long int t; 8 | cin>>t; 9 | 10 | for(int i=0; i>x; 14 | if(x%4 == 0) cout<<"North"< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>str; 13 | if(str[0] != '1') 14 | { 15 | str2='1'; 16 | str.insert(0, str2); 17 | } 18 | else 19 | { 20 | str2='0'; 21 | str.insert(1, str2); 22 | } 23 | cout< D(n+1, 0), T(n+1, 0); 6 | D[0] = 0, D[1] = 1, D[2] = 2; 7 | T[0] = 0, T[1] = 1, T[2] = 2; 8 | 9 | for (int i = 3; i <= n; i++) { 10 | D[i] = (D[i-1] + D[i-2] + 2*T[i-2]) % mod; 11 | T[i] = (T[i-1] + D[i-1]) % mod; 12 | } 13 | 14 | return D[n]; 15 | } 16 | -------------------------------------------------------------------------------- /Linked List/delete_kth_node_from_circular_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // function to delete kth node from circular linked list 2 | Node *delete_kth_node(Node *head, int k) 3 | { 4 | if(head == NULL) return NULL; 5 | if(head-> next == NULL) 6 | { 7 | delete(head); 8 | return NULL; 9 | } 10 | 11 | Node *curr = head; 12 | for(int i=0; inext; 15 | } 16 | Node *temp = curr->next; 17 | curr->next = curr->next->next; 18 | delete(temp); 19 | 20 | -------------------------------------------------------------------------------- /Math tricks/consecutive_numbers_that_sum_up_to_given_number.cpp: -------------------------------------------------------------------------------- 1 | long int countConsecutive(long int N) 2 | { 3 | // constraint on values of L gives us the 4 | // time Complexity as O(N^0.5) 5 | long int count = 0; 6 | for (long int L = 1; L * (L + 1) < 2 * N; L++) { 7 | float a = (1.0 * N - (L * (L + 1)) / 2) / (L + 1); 8 | if (a - (int)a == 0.0) 9 | count++; 10 | } 11 | return count; 12 | } 13 | // for more info: https://www.geeksforgeeks.org/count-ways-express-number-sum-consecutive-numbers/ 14 | -------------------------------------------------------------------------------- /Codechef/three_dices.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/START6B/problems/THREDICE 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>x>>y; 13 | long int temp = 6-x-y; 14 | if(x+y < 6) 15 | { 16 | double answer = temp/6.0; 17 | answer = floor(answer * 1000000) / 1000000; 18 | cout< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>s; 13 | long int len = s.length(), aAndc=0, b=0; 14 | for(int j=0; j 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>r1>>w1>>c1; 13 | cin>>r2>>w2>>c2; 14 | if(r1 > r2) a++; 15 | else b++; 16 | if(c1 > c2) a++; 17 | else b++; 18 | if(w1 > w2) a++; 19 | else b++; 20 | if(a > b) cout<<"A"<& tasks, int n) { 2 | int highestFreq = 0, numberOfMostFreq = 0; 3 | 4 | unordered_map freq; 5 | for(auto i: tasks) 6 | { 7 | freq[i]++; 8 | highestFreq = max(highestFreq , freq[i]); 9 | } 10 | for(auto i: freq) 11 | { 12 | if(i.second == highestFreq) 13 | { 14 | numberOfMostFreq++; 15 | } 16 | } 17 | return max((highestFreq - 1) * (n+1) + numberOfMostFreq , (int)tasks.size()); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Matrix/rotate_image.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://leetcode.com/problems/rotate-image/ 2 | void rotate(vector>& matrix) { 3 | int size = matrix.size(); 4 | for(int i=0; idata == n1 || root->data == n2) return root; // case 1 8 | Node* lca1 = LCA(root->left, n1, n2); 9 | Node* lca2 = LCA(root->right, n1, n2); 10 | if(lca1 != NULL && lca2 != NULL) return root; // case 2 11 | if(lca1 != NULL) return lca1; 12 | else return lca2; 13 | } 14 | -------------------------------------------------------------------------------- /Math tricks/gcd_of_array.cpp: -------------------------------------------------------------------------------- 1 | // GCD of three or more numbers equals the product of the prime factors common to all the numbers 2 | // it can also be calculated by repeatedly taking the GCDs of pairs of numbers 3 | int findGCD(int arr[], int n) 4 | { 5 | int result = arr[0]; 6 | for (int i = 1; i < n; i++) 7 | { 8 | result = gcd(arr[i], result); 9 | 10 | if(result == 1) 11 | { 12 | return 1; 13 | } 14 | } 15 | return result; 16 | } 17 | // for more info: https://www.geeksforgeeks.org/gcd-two-array-numbers/ 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/consecutive characters.cpp: -------------------------------------------------------------------------------- 1 | int maxPower(string s) { 2 | int len = s.length(); 3 | int currStringCount = 1, maxStringCount = 1; 4 | 5 | for(int i=0; i shortestPathInUndirectedGraph(vector adj[], int v, int src) 2 | { 3 | vector dist(v, INT_MAX); 4 | dist[src] = 0; 5 | q.push(src); 6 | queue q; 7 | 8 | while(! q.empty()) 9 | { 10 | int top = q.front(); 11 | q.pop(); 12 | 13 | for(auto i: adj[top]) 14 | { 15 | if(dist[top]+1 < dist[i]) 16 | { 17 | dist[i] = dist[top] + 1; 18 | q.push(i); 19 | } 20 | } 21 | } 22 | return dist; 23 | } 24 | -------------------------------------------------------------------------------- /Arrays/two sum.cpp: -------------------------------------------------------------------------------- 1 | vector twoSum(vector& nums, int target) { 2 | unordered_map mp; 3 | vector ans; 4 | int n = nums.size(); 5 | for(int i=0; i i) 12 | { 13 | ans.push_back(i); 14 | ans.push_back(mp[(-nums[i] + target)]); 15 | } 16 | } 17 | return ans; 18 | } 19 | -------------------------------------------------------------------------------- /Bit Manipulation/rightmost_different_bit.cpp: -------------------------------------------------------------------------------- 1 | 2 | // problem link: https://practice.geeksforgeeks.org/problems/rightmost-different-bit-1587115621/1/?track=P100-Bit%20Magic&batchId=197 3 | 4 | int posOfRightMostDiffBit(int m, int n) 5 | { 6 | int len; 7 | if(m > n) len = (int)(log2(m)+1); 8 | else len = (int)(log2(n)+1); 9 | for(int i=1; i<=len; i++) 10 | { 11 | if((m & (1 << (i-1))) != (n & (1 << (i-1)))) 12 | { 13 | return i; 14 | } 15 | } 16 | return -1; 17 | } 18 | -------------------------------------------------------------------------------- /Codeforces/A-cherry.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1554/problem/A 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | long int t; 9 | cin>>t; 10 | for(int i=0; i>n; 14 | long long int arr[n], pdt=0; 15 | for(int j=0; j>arr[j]; 18 | } 19 | for(int j=1; jdata == key) return root->data; 8 | else if(root->data < key) root = root->right; 9 | else if(root->data > key) 10 | { 11 | ans = root->data; 12 | root = root->left; 13 | } 14 | } 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Hashing/intersection_of_two_arrays.cpp: -------------------------------------------------------------------------------- 1 | // intersection of two arrays using hashing 2 | // time complexity: O(m+n) 3 | // space complexity O(m) 4 | int intersection(int a[], int m, int b[], int n) 5 | { 6 | unordered_set s; 7 | for(int i=0; i& nums) { 2 | 3 | int size = nums.size(); 4 | int oddSum = 0, evenSum = 0; 5 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>n>>p>>x>>y; 13 | long int arr[n], t=0; 14 | for(int j=0; j>arr[j]; 17 | if(j+1 <= p) 18 | { 19 | if(arr[j] == 1) t+=y; 20 | else t+=x; 21 | } 22 | } 23 | cout< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>n; 15 | if(j % 2 == 0 && n == 1) two++; 16 | else 17 | { 18 | if(n == 1)one++; 19 | } 20 | } 21 | if(one == two) cout<<"0"<two) cout<<"2"< one) cout<<"1"< topKFrequent(vector& nums, int k) { 2 | priority_queue, vector>, greater>> pq; 3 | unordered_map cnt; 4 | for (auto num : nums) cnt[num]++; 5 | for (auto kv : cnt) { 6 | pq.push({kv.second, kv.first}); 7 | while (pq.size() > k) pq.pop(); 8 | } 9 | vector res; 10 | while (!pq.empty()) { 11 | res.push_back(pq.top().second); 12 | pq.pop(); 13 | } 14 | return res; 15 | } 16 | -------------------------------------------------------------------------------- /Codeforces/A-odd_set.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1542/problem/A 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | long int t; 9 | cin>>t; 10 | for(int i=0; i>n; 14 | long long int arr[2*n], even=0, odd=0; 15 | for(int j=0; j<2*n; j++) 16 | { 17 | cin>>arr[j]; 18 | if(arr[j] % 2 == 0) even++; 19 | else odd++; 20 | } 21 | if(even == odd) cout<<"Yes"< 0 && j > 0) 9 | { 10 | if(a[i - 1] == b[j - 1]) 11 | { 12 | res.push_back(a[i - 1]); 13 | i--; 14 | j--; 15 | } 16 | else 17 | { 18 | if(dp[i][j - 1] > dp[i - 1][j]) 19 | { 20 | j--; 21 | } 22 | else 23 | { 24 | i--; 25 | } 26 | } 27 | } 28 | reverse(res.begin(), res.end()); 29 | return res; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/maximum product subarray.cpp: -------------------------------------------------------------------------------- 1 | int maxProduct(vector& nums) { 2 | // problem is only when we see a negative number 3 | int maxPdt = nums[0], minPdt = nums[0], best = nums[0]; 4 | int n = nums.size(); 5 | 6 | for(int i=1; i 3 | using namespace std; 4 | bool isPerfectSquare(double x) 5 | { 6 | if(x - (int)x == 0) return true; 7 | return false; 8 | } 9 | int main() 10 | { 11 | long int t; 12 | cin>>t; 13 | for(int i=0; i>n; 17 | double root = sqrt(n); 18 | 19 | if(isPerfectSquare(root)) ans = (int) root; 20 | else ans = ((int) root)+1; 21 | cout< calculateSpan(int price[], int n) 4 | { 5 | vector vec; 6 | stack s; 7 | s.push(0); 8 | vec.push_back(1); 9 | for(int i=1; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t; 8 | cin>>t; 9 | for(int i=0; i>n; 13 | if(n % 2 == 0) 14 | { 15 | for(int j=0; j arr, long long n, long long m){ 5 | sort(arr.begin(), arr.end()); 6 | long int diff, end=m-1,start=0,ans=(arr[m-1]-arr[0]); 7 | while(end < n) 8 | { 9 | diff=arr[end] - arr[start]; 10 | ans=min(ans, diff); 11 | start++; 12 | end++; 13 | } 14 | return ans; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Heaps and Priority Queues/find k closest elements.cpp: -------------------------------------------------------------------------------- 1 | vector findClosestElements(vector& arr, int k, int x) { 2 | int n = arr.size(); 3 | vector ans; 4 | priority_queue> pq; 5 | for(int i=0; i k) 9 | { 10 | pq.pop(); 11 | } 12 | } 13 | for(int i=0; i 4 | 5 | ### ⭕ Number Theory (Code N Code) 6 | * https://www.notion.so/Code-N-Code-fa88457ed92041e88d4cfb6c9de03b93 7 | 8 | ### ⭕ Recursion and backtracking (Pepcoding) 9 | * https://www.youtube.com/playlist?list=PL-Jc9J83PIiFxaBahjslhBD1LiJAV7nKs 10 | 11 | ### ⭕ CP and Stl tricks (Luv Yt channel) 12 | * (https://www.youtube.com/channel/UCDzhFuVYou1D8w1ABZo3b9A) 13 | 14 | ### ⭕ For Queues - CodeWhoop 15 | * https://www.codewhoop.com/queue/ 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Codechef/beautiful_pairs.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/LTIME98C/problems/BUTYPAIR 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | long int t; 9 | cin>>t; 10 | for(int i=0; i>n; 14 | long int pair = n*(n-1); 15 | long int arr[n]; 16 | map mp; 17 | for(int j=0; j>arr[j]; 20 | mp[arr[j]]++; 21 | } 22 | 23 | for(auto k:mp) 24 | { 25 | if(k.second > 1) pair = pair - ((k.second) * (k.second-1)); 26 | } 27 | cout<& gas, vector& cost) { 2 | int currPetrol = 0, totalPetrol = 0; 3 | int startIndex = 0; 4 | int totalCities = gas.size(); 5 | 6 | for(int i=0; i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | long int t; 7 | cin>>t; 8 | for(int i=0; i>len; 12 | string s; 13 | cin>>s; 14 | bool check = false; 15 | for(int i=1; i> ans; 3 | sort(intervals.begin(), intervals.end()); 4 | ans.push_back(intervals[0]); 5 | if(intervals.size() == 1) return ans; 6 | int ans_idx = 0; 7 | 8 | for(int i=0; i= intervals[i+1][0]) 11 | { 12 | ans[ans_idx][1] = max(ans[ans_idx][1], intervals[i+1][1]); 13 | } 14 | else 15 | { 16 | ans.push_back(intervals[i+1]); 17 | ans_idx++; 18 | } 19 | } 20 | return ans; 21 | } 22 | -------------------------------------------------------------------------------- /Math tricks/binary_exponention.cpp: -------------------------------------------------------------------------------- 1 | // for detailed info: https://cp-algorithms.com/algebra/binary-exp.html 2 | // many a times in the contests, it is asked to find modulo along with exponention 3 | // for eg.: to compute (x^y) % p 4 | // this needs modulo after every iteration since not doing so can cause overflow of large numbers 5 | // checkout above mentioned link to understand exactly what binary exponention algo is 6 | long long power(long long a, long long b, long long m) 7 | { 8 | a%=m; 9 | long long res=1; 10 | while(b > 0) 11 | { 12 | if (b & 1) res = res * a % m; 13 | a = a * a % m; 14 | b /= 2; 15 | } 16 | return res; 17 | } 18 | -------------------------------------------------------------------------------- /Math tricks/gcd_by_euclidean.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Recursive function to return gcd of a and b 4 | int gcd(int a, int b) 5 | { 6 | if (b == 0) 7 | return a; 8 | return gcd(b, a % b); 9 | 10 | } 11 | // this is based on euclidean algorithm which says: 12 | // 1.If we subtract a smaller number from a larger (we reduce a larger number), GCD doesn’t change. So if we keep subtracting repeatedly the larger of two, we end up with GCD. 13 | // 2.Now instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0. 14 | // for more info : https://www.geeksforgeeks.org/c-program-find-gcd-hcf-two-numbers/ 15 | -------------------------------------------------------------------------------- /Arrays/smallest_subarray_having_sum_greater_than_a_given_value.cpp: -------------------------------------------------------------------------------- 1 | // Problem link: https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x5651/1 2 | // My YouTube Code Explanation video😎: https://www.youtube.com/watch?v=WI8886xXRlU 3 | 4 | int sb(int arr[], int n, int x) 5 | { 6 | int sum=0,start=0,len=n; 7 | for(int i=0; i x) 11 | { 12 | len=min(len, i-start+1); 13 | sum=sum-arr[start]; // sliding window technique 14 | start++; 15 | } 16 | } 17 | return len; 18 | } 19 | -------------------------------------------------------------------------------- /Stack/next_greater_element.cpp: -------------------------------------------------------------------------------- 1 | 2 | // problem link: https://practice.geeksforgeeks.org/problems/next-larger-element-1587115620/1 3 | vector nextLargerElement(vector arr, int n) 4 | { 5 | stack s; 6 | vector vec; 7 | vec.push_back(-1); 8 | s.push(arr[n-1]); 9 | for(int i=n-2; i>=0; i--) 10 | { 11 | while(s.empty() == false && arr[i] >= s.top()) s.pop(); 12 | if(s.empty()) vec.push_back(-1); 13 | else vec.push_back(s.top()); 14 | s.push(arr[i]); 15 | } 16 | reverse(vec.begin(), vec.end()); 17 | return vec; 18 | } 19 | -------------------------------------------------------------------------------- /Bit Manipulation/bit_manipulation.cpp: -------------------------------------------------------------------------------- 1 | int setbit(int n, int k) 2 | { 3 | return (n | (1 << (k - 1))); 4 | } 5 | 6 | int clearbit(int n, int k) 7 | { 8 | return (n & (~(1 << (k - 1)))); 9 | } 10 | int getbit(long long int n, long long int k) 11 | { 12 | return (n >> k) & 1; 13 | } 14 | int updatebit(long long int n, long long int k, long long int value) 15 | { 16 | long long int temp=~(1<> (k - 1)); 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Bit Manipulation/find_position_of_set_bit.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/find-position-of-set-bit3706/1 2 | // logic: number of set bits will be one only if it is a power of two 3 | // so we used the same logic as that of power of two 4 | // now we had to return the position, so for that this expression (int)(log2(n)+1) basically returns the numbers of bits required to represent this number and since this 1 will be then present at the very first position therefore this is the answer 5 | int findPosition(int n) { 6 | 7 | if(n == 0) return -1; 8 | if((n & (n-1)) == 0) return (int)(log2(n)+1); 9 | return -1; 10 | } 11 | -------------------------------------------------------------------------------- /Linked List/README.md: -------------------------------------------------------------------------------- 1 | # Comparison of Linked Lists with Arrays & Dynamic Arrays 2 | | Parameter | Linked List | Array | Dynamic Array | 3 | | --- | --- | --- | --- | 4 | | `Indexing` | `O(n)` | `O(1)` | `O(1)` | 5 | | `Insertion or Deletion at beginning` | `O(1)` | `O(n) if array is not full` | `O(n)` | 6 | | `Insertion at ending` | `O(n)` | `O(1) if array is not full`| `O(1) if array is not full` `O(n)if array is full` | 7 | | `Deletion at ending` | `O(n)` | `O(1)` | `O(n)` | 8 | | `Insertion at middle` | `O(n)` | `O(n) if array is not full` | `O(n)` | 9 | | `Deletion at middle` | `O(n)` | `O(n) if array is not full` | `O(n)` | 10 | | `Wasted Space` | `O(n) for pointers` | `0` | `O(n)` | 11 | -------------------------------------------------------------------------------- /Linked List/reverse_doubly_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/reverse-a-doubly-linked-list/1 2 | // idea is to simply swap previous and next links 3 | Node* reverseDLL(Node * head) 4 | { 5 | if(head == NULL || head->next == NULL) return head; 6 | Node *curr = head; 7 | while(curr->next != NULL) // here if we use the condition as (curr->next != NULL) then at the last curr becomes curr->prev and therefore curr becomes null and since we are returning that has head than it will give seg fault 8 | { 9 | swap(curr->next, curr->prev); 10 | curr = curr->prev; 11 | } 12 | swap(curr->prev, curr->next); 13 | return curr; 14 | } 15 | -------------------------------------------------------------------------------- /Other Competitions/ediblity_test.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.hackerrank.com/contests/lgm-heist/challenges/edibility-test/problem 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t, n; 8 | cin>>t; 9 | for(int i=0; i>n; 12 | long long int arr[n], one = 0, two = 0; 13 | for(int j=0; j>arr[j]; 16 | if(j < n/2) one+=arr[j]; 17 | else two+=arr[j]; 18 | 19 | } 20 | 21 | if(one == two ) cout<<"GOOD"< helper; 2 | 3 | void push(stack& s, int a){ 4 | s.push(a); 5 | if(! helper.empty()) 6 | { 7 | if(helper.top() >= s.top()) helper.push(a); 8 | } 9 | else 10 | { 11 | helper.push(a); 12 | } 13 | 14 | } 15 | 16 | bool isFull(stack& s,int n){ 17 | if(s.size() == n) return true; 18 | return false; 19 | } 20 | 21 | bool isEmpty(stack& s){ 22 | return s.empty(); 23 | } 24 | 25 | int pop(stack& s){ 26 | if(helper.top() == s.top()) helper.pop(); 27 | int temp = s.top(); 28 | s.pop(); 29 | return temp; 30 | } 31 | 32 | int getMin(stack& s){ 33 | return helper.top(); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Binary Tree/maximum_and_minimum_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/max-and-min-element-in-binary-tree/1 2 | // recursive solution where we simply compare data of root with its left and with its right and return maximum 3 | // time complexity = O(n) 4 | // space complexity = O(height of binary tree) 5 | int findMax(Node *root) 6 | { 7 | if(root == NULL) return INT_MIN; 8 | return max(root->data, (max(findMax(root->left), findMax(root->right)))); 9 | } 10 | int findMin(Node *root) 11 | { 12 | if(root == NULL) return INT_MAX; 13 | return min(root->data, (min(findMin(root->left), findMin(root->right)))); 14 | } 15 | -------------------------------------------------------------------------------- /Bit Manipulation/bit_difference.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/bit-difference-1587115620/1# 2 | int countBit(int n, int k) 3 | { 4 | if((n & (1 << (k-1))) != 0) return 1; 5 | else return 0; 6 | } 7 | 8 | int countBitsFlip(int a, int b){ 9 | 10 | int A = (int)(log2(a)+1); 11 | int B = (int)(log2(b)+1); 12 | int n, count = 0; 13 | if(A > B) n = A; 14 | else n = B; 15 | 16 | for(int i=1; i<=n; i++) 17 | { 18 | if(countBit(a, i) != countBit(b, i)) count += 1; 19 | } 20 | 21 | 22 | return count; 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Queue/generate_binary_numbers.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/generate-binary-numbers-1587115620/1 2 | 3 | // using queue in O(n) time complexity 4 | // idea: push 1 to the queue and push it into the vector, 5 | // then append 0 as well as 1 making two variables and then appened both to the vector 6 | 7 | vector generate(int N) 8 | { 9 | queue q; 10 | vector vec; 11 | q.push("1"); 12 | for(int i=0; i s; 5 | int ans, best=0; 6 | for(int i=0; i given sum 3 | { 4 | unordered_set s; 5 | long int sum=0; 6 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i d; 12 | long int n; 13 | cin>>n; 14 | long int arr[n]; 15 | 16 | for(int j=0; j>arr[j]; 19 | 20 | } 21 | d.push_back(arr[0]); 22 | for(int j=1; j&s, int sizeOfStack) 5 | { 6 | stack helper; 7 | int mid = sizeOfStack/2; 8 | for(int i=0; ileft, k, minDiff); 9 | if(abs(k - root->data) < minDiff) 10 | { 11 | minDiff = abs(k - root->data); 12 | } 13 | inorderTraversal(root->right, k, minDiff); 14 | 15 | } 16 | 17 | int minDiff(Node *root, int k) 18 | { 19 | int minDiff = INT_MAX; 20 | inorderTraversal(root, k, minDiff); 21 | return minDiff; 22 | } 23 | -------------------------------------------------------------------------------- /Binary Tree/Preorder_traversal_iterative.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/preorder-traversal/1# 2 | // iterative solution 3 | vector preorder(Node* root) 4 | { 5 | vector ans; 6 | stack s; 7 | Node *curr = root; 8 | while(curr != NULL || s.empty() == false) 9 | { 10 | // for left subtree 11 | while(curr != NULL) 12 | { 13 | s.push(curr); 14 | ans.push_back(curr->data); // for root 15 | curr = curr->left; 16 | } 17 | curr = s.top(); 18 | s.pop(); 19 | 20 | curr = curr->right; // for right subtree 21 | } 22 | return ans; 23 | } 24 | -------------------------------------------------------------------------------- /Codeforces/B-fedor_and_new_game.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/problemset/problem/467/B 2 | #include 3 | using namespace std; 4 | 5 | int kthBit(unsigned int n, unsigned int k) 6 | { 7 | return ((n & (1 << (k - 1))) >> (k - 1)); 8 | } 9 | 10 | int main() 11 | { 12 | long int n, m, k, count=0, diff=0, maxi=0; 13 | cin>>n>>m>>k; 14 | long int arr[m+1]; 15 | for(int i=0; i>arr[i]; 18 | if(maxi < arr[i]) maxi = arr[i]; 19 | } 20 | 21 | for(int i=0; idata == key : simply return root->data 3 | // 2. root->data > key : root = root->left 4 | // 3. root->data < key : current root can possibly be an answer so store that in a variable 5 | 6 | int floor(Node* root, int key) 7 | { 8 | int ans=-1; 9 | while(root != NULL) 10 | { 11 | if(root->data == key) return root->data; 12 | else if(root->data > key) root = root->left; 13 | else if(root->data < key) 14 | { 15 | ans = root->data; 16 | root = root->right; 17 | } 18 | } 19 | return ans; 20 | } 21 | -------------------------------------------------------------------------------- /Codechef/the_grid_fill_problem.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/START11C/problems/FILLGRID 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long long int t; 8 | cin>>t; 9 | for(int i=0; i>n; 13 | if(n != 2) 14 | { 15 | for(int j=0; j 0 && arr[mid - 1] > arr[mid]) 10 | { 11 | return peak(arr, low, (mid - 1), n); 12 | } 13 | // If middle element is not peak and its right neighbour is greater than it, then right half must have a peak element 14 | else 15 | return peak(arr, (mid + 1), high, n); 16 | } 17 | int peakElement(int arr[], int n) 18 | { 19 | return peak(arr, 0, n-1, n); 20 | } 21 | -------------------------------------------------------------------------------- /Linked List/middle_element_of_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1 2 | 3 | // middle element of linked list 4 | // works on the concept that we keep two pointers slow and fast 5 | // slow pointer moves one position and fast pointer moves 2 positions 6 | // when fast reaches last position, slow would have reached the middle and in this way we get the middle element 7 | // even number of nodes and odd number of nodes have slightly different approach 8 | 9 | int getMiddle(Node *head) 10 | { 11 | Node *slow=head; 12 | Node *fast=head; 13 | while(fast != NULL && fast -> next != NULL) 14 | { 15 | slow=slow->next; 16 | fast=fast->next->next; 17 | } 18 | return (slow -> data); 19 | } 20 | -------------------------------------------------------------------------------- /Binary Search Tree/smaller_on_right.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/smaller-on-right4318/1/?track=P100-Binary%20Search%20Tree&batchId=197 2 | // idea is to traverse array from right to left and add elements into the set(which uses self balancing bst) 3 | // for each element we need to find the element just smaller than current element so we use lower bound for this 4 | 5 | 6 | int countSmallerRight(int arr[], int n) { 7 | 8 | sets; 9 | int smallerOnRight =0; 10 | for(int i=n-1; i>=0; i--) 11 | { 12 | s.insert(arr[i]); 13 | auto it = s.lower_bound(arr[i]); 14 | if(distance(s.begin(),it) > smallerOnRight) smallerOnRight= distance(s.begin(),it); 15 | } 16 | return smallerOnRight; 17 | } 18 | -------------------------------------------------------------------------------- /Matrix/sorted_matrix.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/sorted-matrix2333/1# 2 | 3 | vector> sortedMatrix(int N, vector> matrix) { 4 | 5 | int ans[N*N], count=0; 6 | 7 | for(int i=0; i &mp){ 5 | 6 | if(root == NULL) return; 7 | 8 | solve(root->left, horizontalDist-1, mp); 9 | mp[horizontalDist] += root->data; 10 | solve(root->right, horizontalDist+1, mp); 11 | 12 | } 13 | 14 | 15 | vector verticalSum(Node *root) { 16 | map mp; 17 | solve(root, 0, mp); 18 | 19 | vector ans; 20 | for(auto i: mp){ 21 | ans.push_back(i.second); 22 | } 23 | return ans; 24 | } 25 | -------------------------------------------------------------------------------- /Linked List/remove_duplicates_from_sorted_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/remove-duplicate-element-from-sorted-linked-list/1 2 | // comparing curr with curr->next and if they are same we delete the duplicate node with the use of another pointer 3 | // and transfer the link to curr->next->next 4 | 5 | Node *removeDuplicates(Node *head) 6 | { 7 | Node *curr = head; 8 | while(curr != NULL && curr->next != NULL) // base case conditions 9 | { 10 | if(curr->data == curr->next->data) 11 | { 12 | Node *temp = curr->next; 13 | curr->next = curr->next->next; 14 | delete(temp); 15 | } 16 | else curr = curr->next; 17 | } 18 | 19 | return head; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Linked List/multiply_two_linked_lists.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/multiply-two-linked-lists/1# 2 | 3 | long long multiplyTwoLists (Node* l1, Node* l2) 4 | { 5 | Node *curr1 = l1; 6 | Node *curr2 = l2; 7 | long long int first=0, second=0; 8 | 9 | while(curr1 != NULL || curr2 != NULL) 10 | { 11 | if(curr1 != NULL) 12 | { 13 | first = (first*10)%1000000007 + curr1->data; 14 | curr1 = curr1->next; 15 | } 16 | 17 | if(curr2 != NULL) 18 | { 19 | second = (second*10)%1000000007 + curr2->data; 20 | curr2 = curr2->next; 21 | } 22 | } 23 | long long int ans = ((first%1000000007) * (second%1000000007) ) %1000000007; 24 | } 25 | -------------------------------------------------------------------------------- /Codeforces/B1-wonderful_coloring-1.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1551/problem/B1 2 | 3 | #include 4 | using namespace std; 5 | 6 | int countDistinct(string s, int n) 7 | { 8 | 9 | unordered_map m; 10 | 11 | for (int i = 0; i < n; i++) { 12 | m[s[i]]++; 13 | } 14 | long int count=0, len=m.size(); 15 | 16 | for (auto i : m) 17 | { 18 | if(i.second >=2) count++; 19 | } 20 | 21 | return (m.size()+count); 22 | } 23 | 24 | int main() 25 | { 26 | long int t; 27 | cin>>t; 28 | for(int i=0; i>s; 32 | long int n=s.length(),k; 33 | k=countDistinct(s, n); 34 | cout< &arr, int index, vector&visited) 3 | { 4 | int size = arr.size(); 5 | if(index < 0 || index > size - 1 || visited[index]) return false; 6 | if(arr[index] == 0) return true; 7 | visited[index] = true; 8 | return (JumpGame(arr, index+arr[index], visited) || JumpGame(arr, index-arr[index], visited)); 9 | 10 | } 11 | bool canReach(vector& arr, int start) { 12 | vector visited(arr.size(), false);; 13 | return JumpGame(arr, start, visited); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Stack/implement_two_stacks_in_array.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/1# 2 | 3 | void twoStacks :: push1(int x) 4 | { 5 | top1++; 6 | arr[top1] = x; 7 | } 8 | 9 | //Function to push an integer into the stack2. 10 | void twoStacks ::push2(int x) 11 | { 12 | top2--; 13 | arr[top2] = x; 14 | } 15 | 16 | //Function to remove an element from top of the stack1. 17 | int twoStacks ::pop1() 18 | { 19 | if(top1 >= 0) 20 | { 21 | return arr[top1--]; 22 | } 23 | else return -1; 24 | } 25 | 26 | //Function to remove an element from top of the stack2. 27 | int twoStacks :: pop2() 28 | { 29 | if(top2 < size) 30 | { 31 | return arr[top2++]; 32 | } 33 | else return -1; 34 | } 35 | -------------------------------------------------------------------------------- /Arrays/longest_repeating_character_replacement.cpp: -------------------------------------------------------------------------------- 1 | int characterReplacement(string s, int k) { 2 | unordered_map freq; 3 | int start = 0, end = 0; 4 | int highestFreq = 0; 5 | int ans = 0; 6 | int size = s.length(); 7 | 8 | while(end < size) 9 | { 10 | freq[s[end]]++; 11 | int currFreq = freq[s[end]]; 12 | highestFreq = max(currFreq, highestFreq); 13 | // since atmost k characters can be replaced 14 | if((end - start + 1 - highestFreq) > k) 15 | { 16 | freq[s[start]]--; 17 | start++; 18 | } 19 | ans = max(ans, end - start+1); 20 | end++; 21 | } 22 | return ans; 23 | } 24 | -------------------------------------------------------------------------------- /Codeforces/A-polycarp_and_coins.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1551/problem/A 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | long int t; 9 | cin>>t; 10 | for(int i=0; i>n; 14 | if(n % 3 == 0) 15 | { 16 | c1=(n/3); 17 | c2=(n/3); 18 | } 19 | else if((n-1) % 3 == 0) 20 | { 21 | c1=(n+2)/3; 22 | c2=(n-1)/3; 23 | if(c1+2*c2 != n) swap(c1,c2); 24 | } 25 | else 26 | { 27 | c1=(n+1)/3; 28 | c2=(n-2)/3; 29 | if(c1+2*c2 != n) swap(c1,c2); 30 | } 31 | cout< s; 6 | long int sum=0; 7 | for(int i=0; idata; 8 | int left_sum = sumTree(root->left, ans); 9 | int right_sum = sumTree(root->right, ans); 10 | 11 | if((!(root->left == NULL && root->right == NULL)) && root->data != left_sum + right_sum) 12 | { 13 | ans = 0; 14 | } 15 | return sum+left_sum+right_sum; 16 | } 17 | 18 | bool isSumTree(Node* root) 19 | { 20 | int ans = 1; 21 | sumTree(root, ans); 22 | return ans; 23 | } 24 | -------------------------------------------------------------------------------- /Codeforces/A-exciting_bets.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1543/problem/A 2 | // idea: (during the contest) I tried the question for 4-5 test cases and luckily after a lot research got a pettern which all of them satisfied 3 | 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | long int t; 10 | cin>>t; 11 | for(int i=0; i>a>>b; 15 | cout<>& points) { 2 | int size = points.size(); 3 | sort(points.begin(), points.end()); 4 | int minimum = points[0][0]; 5 | int maximum = points[0][1]; 6 | int ans = 1; 7 | for(int i=1; i= minimum && points[i][0] <= maximum) 10 | { 11 | minimum = max(minimum, points[i][0]); 12 | maximum = min(maximum, points[i][1]); 13 | } 14 | else 15 | { 16 | ans++; 17 | minimum = points[i][0]; 18 | maximum = points[i][1]; 19 | } 20 | } 21 | return ans; 22 | } 23 | -------------------------------------------------------------------------------- /Greedy/minimum number of arrows to burst ballons(merge interval type Q).cpp: -------------------------------------------------------------------------------- 1 | int findMinArrowShots(vector>& points) { 2 | int size = points.size(); 3 | sort(points.begin(), points.end()); 4 | int minimum = points[0][0]; 5 | int maximum = points[0][1]; 6 | int ans = 1; 7 | for(int i=1; i= minimum && points[i][0] <= maximum) 10 | { 11 | minimum = max(minimum, points[i][0]); 12 | maximum = min(maximum, points[i][1]); 13 | } 14 | else 15 | { 16 | ans++; 17 | minimum = points[i][0]; 18 | maximum = points[i][1]; 19 | } 20 | } 21 | return ans; 22 | } 23 | -------------------------------------------------------------------------------- /Greedy/candy.cpp: -------------------------------------------------------------------------------- 1 | int candy(vector& ratings) { 2 | // in one go compare with previous elements 3 | // in other go compare with next elements 4 | int n = ratings.size(); 5 | vectorleft(n, 1), right(n, 1); 6 | 7 | //traverse left to right and compare curr value with left side value 8 | for(int i=1; i ratings[i-1]) left[i] = left[i-1]+1; 10 | 11 | //traverse right to left and compare curr value with right side value 12 | for(int i=n-2; i>=0; i--) 13 | if(ratings[i] > ratings[i+1]) right[i] = right[i+1]+1; 14 | 15 | int ans = 0; 16 | for(int i=0; inext != NULL) 9 | { 10 | slow = slow->next; 11 | fast = fast->next->next; 12 | if(slow == fast) break; 13 | } 14 | if(slow != fast) return 0; 15 | 16 | int count=0; 17 | fast = fast->next; 18 | while(fast != slow) 19 | { 20 | fast = fast->next; 21 | count++; 22 | } 23 | return count+1; 24 | } 25 | -------------------------------------------------------------------------------- /Binary Tree/transform_to_sum_tree.cpp: -------------------------------------------------------------------------------- 1 | // Convert a given tree to a tree where every node contains sum of values of 2 | // nodes in left and right subtrees in the original tree 3 | 4 | // problem link: https://practice.geeksforgeeks.org/problems/transform-to-sum-tree/1# 5 | // store value of current node in actual tree then recursively call for its left, recursively call for its right 6 | // add the values which came from recursive calls and return cuurent node data + current node actual data 7 | int sumTree(Node* root) 8 | { 9 | if(root == NULL) return 0; 10 | int sum = root->data; 11 | root->data = sumTree(root->left) + sumTree(root->right); 12 | return sum+root->data; 13 | } 14 | 15 | void toSumTree(Node *node) 16 | { 17 | sumTree(node); 18 | } 19 | -------------------------------------------------------------------------------- /Linked List/given_linked_list_of_0s_1s_and_2s_sort_it.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/given-a-linked-list-of-0s-1s-and-2s-sort-it/1# 2 | 3 | Node* segregate(Node *head) 4 | { 5 | int arr[3] = {0}; 6 | Node *curr = head; 7 | while(curr != NULL) 8 | { 9 | if(curr->data == 0) arr[0]++; 10 | else if(curr->data == 1) arr[1]++; 11 | else arr[2]++; 12 | 13 | curr = curr->next; 14 | } 15 | curr = head; 16 | 17 | for(int i=0; i<3; i++) 18 | { 19 | while(arr[i] != 0) 20 | { 21 | curr->data = i; 22 | arr[i]--; 23 | curr = curr->next; 24 | } 25 | } 26 | return head; 27 | } 28 | -------------------------------------------------------------------------------- /Arrays/container with most water.cpp: -------------------------------------------------------------------------------- 1 | int maxArea(vector& arr) { 2 | // we will have left as 0th index and right as last index 3 | // so we are starting with maximum width and then we are in search of maximum height if we reducing width 4 | int size = arr.size(); 5 | int left = 0, right = size-1, ans = 0; 6 | while(right > left) 7 | { 8 | int lh = arr[left]; 9 | int rh = arr[right]; 10 | int width = right - left; 11 | int height = min(lh, rh); 12 | 13 | ans = max(ans, width*height); 14 | if(lh > rh) 15 | { 16 | right--; 17 | } 18 | else 19 | { 20 | left++; 21 | } 22 | } 23 | return ans; 24 | } 25 | -------------------------------------------------------------------------------- /Binary Tree/diameter_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | // problem link:https://practice.geeksforgeeks.org/problems/diameter-of-binary-tree/1 2 | // idea is to find left height and right height for every node 3 | // and the maximum of summation of both is the answer 4 | // this program is very much similar to that of height of binary tree 5 | int solve(int &maxi, Node* root) 6 | { 7 | if(root == NULL) return 0; 8 | int left_height = solve(maxi, root->left); 9 | int right_height = solve(maxi, root->right); 10 | maxi = max(left_height + right_height + 1, maxi); 11 | return 1+max(left_height, right_height); 12 | } 13 | // Function to return the diameter of a Binary Tree. 14 | int diameter(Node* root) { 15 | int maxi=0; 16 | solve(maxi, root); 17 | return maxi; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Dynamic Progamming/18 longest palindromic subsequence.cpp: -------------------------------------------------------------------------------- 1 | // refer notes pg: 41 2 | int longestPalindromeSubseq(string x) { 3 | int m = x.length(); 4 | int n = m; 5 | string y = x; 6 | reverse(y.begin(), y.end()); 7 | 8 | int dp[m + 1][n + 1]; 9 | 10 | memset(dp, 0, sizeof(dp)); 11 | 12 | for(int i = 1; i < m + 1; i++) 13 | { 14 | for(int j = 1; j < n + 1; j++) 15 | { 16 | if(x[i - 1] == y[j - 1]) 17 | { 18 | dp[i][j] = 1 + dp[i - 1][j - 1]; 19 | } 20 | else 21 | { 22 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); 23 | } 24 | } 25 | } 26 | return dp[m][n]; 27 | } 28 | -------------------------------------------------------------------------------- /Stack/implement stack using queues.cpp: -------------------------------------------------------------------------------- 1 | // https://www.youtube.com/watch?v=jDZQKzEtbYQ 2 | queue helperQueue; 3 | MyStack() { 4 | 5 | } 6 | 7 | void push(int x) { 8 | int size = helperQueue.size(); 9 | helperQueue.push(x); 10 | for(int i=0; i &visited, vector adj[], vector &ans) 2 | { 3 | visited[vertex] = 1; 4 | ans.push_back(vertex); 5 | for(int i=0; i dfsOfGraph(int vertices, vector adj[]) 16 | { 17 | vector visited(vertices, 0), ans; 18 | // for loop is for unconnected components 19 | for (int i=0; i>& board) { 3 | vector> rows(9), cols(9), blocks(9); 4 | 5 | for (int i = 0; i < 9; i++) { 6 | for (int j = 0; j < 9; j++) { 7 | 8 | if (board[i][j] == '.') continue; 9 | 10 | int curr = board[i][j] - '0'; 11 | if (rows[i].count(curr) || cols[j].count(curr) || blocks[(i/3)*3+j/3].count(curr)) 12 | return false; 13 | 14 | rows[i].insert(curr); 15 | cols[j].insert(curr); 16 | blocks[(i/3)*3+j/3].insert(curr); 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | -------------------------------------------------------------------------------- /Binary Search Tree/populate_inorder_successor_of_all_nodes.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/populate-inorder-successor-for-all-nodes/1# 2 | // basically we are doing simple inorder traversal and storing the previous node 3 | // then we are making prevNode->next = current node 4 | 5 | void solve(Node* root, Node* &prevNode) 6 | { 7 | //cout<data<left != NULL) solve(root->left, prevNode); 11 | 12 | if(prevNode != NULL) prevNode->next = root; 13 | prevNode = root; 14 | 15 | if(root->right != NULL) solve(root->right, prevNode); 16 | } 17 | 18 | void populateNext(Node *root) 19 | { 20 | Node* prevNode = NULL; 21 | solve(root, prevNode); 22 | } 23 | -------------------------------------------------------------------------------- /Sorting/three_way_partitioning.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/three-way-partitioning/1# 2 | 3 | void threeWayPartition(vector& arr,int a, int b) 4 | { 5 | 6 | // following method is known as dnf sort 7 | // using three pointers 8 | int n=arr.size(); 9 | int low=0, mid=0, high=n-1; 10 | while(mid <= high) 11 | { 12 | if(arr[mid] < a) 13 | { 14 | swap(arr[mid], arr[low]); 15 | mid++; 16 | low++; 17 | } 18 | else if(arr[mid] > b) 19 | { 20 | swap(arr[mid], arr[high]); 21 | high--; 22 | } 23 | else 24 | { 25 | mid++; 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Arrays/maximum_product_subarray.cpp: -------------------------------------------------------------------------------- 1 | // PROBLEM LINK: https://leetcode.com/problems/maximum-product-subarray/ 2 | int maxProduct(vector& arr) { 3 | // modified kadane's algorithm 4 | // issue is when we encounter a negative number 5 | // so used two variables to store min and max of the products so that if upcoming number is negative, it can pair up with negative product to give the maximum 6 | int best=arr[0]; 7 | int max_product=arr[0], min_product=arr[0]; 8 | int n=arr.size(); 9 | for(int j=1; j q; 5 | q.push(node); 6 | int max=0; 7 | while(q.size() != 0) 8 | { 9 | int count = q.size(); 10 | if(count > max) max = count; 11 | for(int i=0; i left) q.push(top->left); 18 | if(top -> right) q.push(top->right); 19 | } 20 | } 21 | 22 | } 23 | return max; 24 | } 25 | -------------------------------------------------------------------------------- /Codeforces/B-customizing_the_track.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1543/problem/B 2 | // tried it for multiple test cases and noted the pattern and sectionized the code 3 | 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | long int t; 10 | cin>>t; 11 | for(int i=0; i>n; 15 | long long int arr[n], sum=0, temp; 16 | for(int i=0; i>arr[i]; 19 | sum+=arr[i]; 20 | } 21 | if(sum % n == 0) cout<<"0"< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>n>>d>>h; 13 | long int arr[n]; 14 | bool alert = false; 15 | for(int j=0; j>arr[j]; 18 | } 19 | for(int j=0; j h) 25 | { 26 | cout<<"YES"< 5 | using namespace std; 6 | 7 | void printMazePaths(int sr, int sc, int dr, int dc, string str) 8 | { 9 | if(sc == dc && sr == dr) 10 | { 11 | cout< dc || sr > dr) 15 | { 16 | return; 17 | } 18 | printMazePaths(sr, sc+1, dr, dc, str+"h"); 19 | printMazePaths(sr+1, sc, dr, dc, str+"v"); 20 | } 21 | 22 | int main(){ 23 | int n; 24 | int m; 25 | cin >> n >> m; 26 | printMazePaths(0, 0, n - 1, m - 1, ""); 27 | } 28 | -------------------------------------------------------------------------------- /Queue/find winner of circular game.cpp: -------------------------------------------------------------------------------- 1 | // to checkout a better approach look at josephus problem which is efficient recursive solution for same problem 2 | int findTheWinner(int n, int k) { 3 | queue membersQ; 4 | for(int i=1; i<=n; i++) 5 | { 6 | membersQ.push(i); 7 | } 8 | int count = 1; 9 | while(membersQ.size() != 1) 10 | { 11 | if(count == k) 12 | { 13 | // cout<left, head, prev); // recursively calling for left subtree 7 | 8 | if(prev == NULL) head = node; // if that is first node then we make it head 9 | else 10 | { 11 | node->left = prev; 12 | prev->right = node; 13 | } 14 | prev = node; 15 | 16 | conversion(node->right, head, prev); // recursively calling for right subtree 17 | } 18 | 19 | Node * bToDLL(Node *root) 20 | { 21 | Node *head = NULL; 22 | Node *prev = NULL; 23 | conversion(root, head, prev); 24 | return head; 25 | } 26 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/insertion sort list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* insertionSortList(ListNode* head) { 14 | if(head == NULL) return head; 15 | 16 | ListNode *dummy = new ListNode(0); 17 | ListNode *prev = dummy, *curr = head, *next; 18 | 19 | while(curr){ 20 | next = curr->next; 21 | while(prev->next && prev->next->val < curr -> val) prev = prev -> next; 22 | 23 | curr->next = prev->next; 24 | prev->next = curr; 25 | 26 | curr = next; 27 | prev = dummy; 28 | } 29 | return dummy->next; 30 | } 31 | -------------------------------------------------------------------------------- /Codeforces/B-random_teams.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/problemset/problem/478/B 2 | // we don't have to count the permutations, we have to count only the combinations 3 | 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | long long int n, m, kmin, kmax, remaining, min_each; // minimum people in each team; 10 | cin>>n>>m; 11 | // for k max only one group will have all rest members after divding equally 12 | kmax = ((n-m+1) * (n-m))/2; 13 | // for kmin 14 | // equally divided in each team 15 | min_each = (n/m); 16 | remaining = n - (min_each * m); 17 | long long int group1; // more people 18 | long long int group2; // less people 19 | group1 = remaining; 20 | group2 = m-remaining; 21 | kmin = group1 * (((min_each+1) * (min_each))/2) + group2 * (((min_each) * (min_each-1))/2); 22 | cout< 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string s; 9 | cin>>s; 10 | long long int len = s.length(); 11 | long long int left=0, right=0, pivot=0; 12 | 13 | for(int j=0; j= '1' && s[i] <= '9') 24 | { 25 | left += ((s[i]-48) * (i-pivot)); 26 | } 27 | 28 | if(i > pivot && s[i] >= '1' && s[i] <= '9') 29 | { 30 | right += (s[i]-48) * (i-pivot); 31 | } 32 | 33 | } 34 | //cout< 0 && j > 0) 9 | { 10 | if(a[i - 1] == b[j - 1]) 11 | { 12 | res.push_back(a[i - 1]); 13 | i--; 14 | j--; 15 | } 16 | else 17 | { 18 | if(dp[i][j - 1] > dp[i - 1][j]) 19 | { 20 | res.push_back(b[j - 1]); 21 | j--; 22 | } 23 | else 24 | { 25 | res.push_back(a[i - 1]); 26 | i--; 27 | } 28 | } 29 | } 30 | 31 | while(i > 0) { 32 | res.push_back(a[i-1]); 33 | i--; 34 | } 35 | 36 | while(j > 0) { 37 | res.push_back(b[j-1]); 38 | j--; 39 | } 40 | 41 | reverse(res.begin(), res.end()); 42 | return res; 43 | } 44 | -------------------------------------------------------------------------------- /Dynamic Progamming/19 minimum number of deletions to make string palindrome.cpp: -------------------------------------------------------------------------------- 1 | // refer notes pg: 41 2 | int deletionsToMakeStringPalindrome(string x) { 3 | int m = x.length(); 4 | int n = m; 5 | string y = x; 6 | reverse(y.begin(), y.end()); 7 | 8 | int dp[m + 1][n + 1]; 9 | 10 | memset(dp, 0, sizeof(dp)); 11 | 12 | for(int i = 1; i < m + 1; i++) 13 | { 14 | for(int j = 1; j < n + 1; j++) 15 | { 16 | if(x[i - 1] == y[j - 1]) 17 | { 18 | dp[i][j] = 1 + dp[i - 1][j - 1]; 19 | } 20 | else 21 | { 22 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); 23 | } 24 | } 25 | } 26 | int LCSlen = dp[m][n]; 27 | return m - LCSlen; 28 | } 29 | -------------------------------------------------------------------------------- /Codechef/from_rational_to_binary.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/LTIME97C/problems/REALBIN/ 2 | // logic I used: - when the fraction wil be a recurring decimal -> false else true 3 | // to check the same we have the logc as: 4 | // Express the denominator as the product of its prime factors. 5 | // If the prime factorization contains only factors of 2 and 5, the decimal representation will terminate. If any factors other than 2 and 5 are present, the fraction will have a repeating decimal. 6 | // for more info on the same visit: https://www.geeksforgeeks.org/find-recurring-sequence-fraction/ 7 | #include 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int t; 13 | cin>>t; 14 | while(t--) 15 | { 16 | long long int a,b; 17 | cin>>a>>b; 18 | if((b&(b-1))==0) cout<<"Yes"< mp; // to store frequency of elements 11 | for(int i=0; ileft ? depthfirstsearch(root->left) : 0), right = (root->right ? depthfirstsearch(root->right) : 0); 18 | result += abs(left - right); 19 | return left + right + root->val; 20 | } 21 | int findTilt(TreeNode* root) { 22 | if (root) depthfirstsearch(root); 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Queue/implementation_of_dequeue_stl.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void display(deque x) 7 | { 8 | deque :: iterator it; 9 | for (it = x.begin(); it != x.end(); ++it) 10 | cout << ' ' << *it; 11 | cout << '\n'; 12 | } 13 | 14 | int main() 15 | { 16 | deque a; 17 | a.push_back(10); 18 | a.push_front(20); 19 | a.push_back(30); 20 | a.push_front(15); 21 | cout << "The deque a is : "; 22 | display(a); 23 | 24 | cout << "a.size() : " << a.size()<next != NULL) 16 | { 17 | slow = slow->next; 18 | fast = fast->next->next; 19 | if(slow == fast) break; 20 | } 21 | 22 | if(fast == NULL || fast->next == NULL) 23 | { 24 | return NULL; 25 | } 26 | 27 | slow = head; 28 | while(slow != fast) 29 | { 30 | slow = slow->next; 31 | fast = fast->next; 32 | } 33 | return fast; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Linked List/split_circular_linked_list_into_two_halves.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/split-a-circular-linked-list-into-two-halves/1# 2 | 3 | // to head Node of given lined list. head1_ref1 and *head_ref2 4 | // are pointers to head pointers of resultant two halves. 5 | 6 | // using slow and fast pointers 7 | // don't forget to make two two newly formed lists circular 8 | void splitList(Node *head, Node **head1_ref, Node **head2_ref) 9 | { 10 | Node *slow = head; 11 | Node *fast = head; 12 | if(head == NULL) return; 13 | 14 | while(fast->next != head && fast->next->next != head) 15 | { 16 | slow = slow->next; 17 | fast = fast->next->next; 18 | } 19 | // even: 20 | if(fast->next->next == head) fast = fast->next; 21 | *head1_ref = head; 22 | *head2_ref = slow->next; 23 | fast->next = slow->next; 24 | slow->next = head; 25 | } 26 | -------------------------------------------------------------------------------- /Codeforces/B-plus_and_multiply.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1542/problem/B 2 | // try to make a tree of all such possiblities and 3 | // it can be noticed that every such number will be of the type: 4 | // a^x + y*b = n --> (n - temp) % b == integer --> temp*=a; 5 | #include 6 | using namespace std; 7 | 8 | bool checker(long long int n, long long int a, long long int b) 9 | { 10 | long long int x=1; 11 | while(x <= n) 12 | { 13 | if((n - x) % b == 0) 14 | { 15 | return true; 16 | } 17 | if(a == 1) break; 18 | x*=a; 19 | } 20 | return false; 21 | } 22 | int main() 23 | { 24 | long int t; 25 | cin>>t; 26 | for(int i=0; i>n>>a>>b; 30 | if(checker(n, a, b)) cout<<"Yes"<& coin, int sum) 3 | { 4 | int n = coin.size(); 5 | int dp[n + 1][sum + 1]; 6 | // initializing values 7 | for(int i=0; i<=n; i++) 8 | { 9 | dp[i][0] = 1; 10 | } 11 | for(int j=1; j<=sum; i++) 12 | { 13 | dp[0][j] = 0; 14 | } 15 | // filing the matrix 16 | for(int i=1; i5 6 1 | 8 4 5 10 | // 5 6 1 8 4 5->4 1 | 8 4 5 11 | // this way they meet at the same point 12 | 13 | int intersectPoint(Node* head1, Node* head2) 14 | { 15 | Node *curr1 = head1; 16 | Node *curr2 = head2; 17 | while(curr1 != curr2) 18 | { 19 | curr1 = curr1 == NULL? head2 : curr1->next; 20 | curr2 = curr2 == NULL? head1 : curr2->next; 21 | } 22 | return curr1->data; 23 | 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Binary Search Tree/kth_smallest_element_in_BST.cpp: -------------------------------------------------------------------------------- 1 | 2 | // problem link: https://practice.geeksforgeeks.org/problems/find-k-th-smallest-element-in-bst/1 3 | // refer kth largest problem 4 | // the code is similar to sa kth largest elemnt with a slight change 5 | 6 | void solve(Node* root, int key, int &count, bool &check, int &ans) 7 | { 8 | if(root == NULL) return; 9 | solve(root->left, key, count, check, ans); 10 | 11 | count++; 12 | if(count == key) 13 | { 14 | //cout<data; 15 | ans = root->data; 16 | return; 17 | } 18 | 19 | solve(root->right, key, count, check,ans); 20 | } 21 | 22 | int KthSmallestElement(Node *root, int key) { 23 | int count=0, ans = -1; 24 | bool check = false; 25 | solve(root, key, count, check, ans); 26 | 27 | return ans; 28 | } 29 | -------------------------------------------------------------------------------- /Codechef/bella_ciao.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/JUNE21C/problems/CHFHEIST/ 2 | #include 3 | using namespace std; 4 | // p+p+..(d times) 5 | // p+p+..(d times) + q+q+..(d times) 6 | // p+p+..(d times) + 2*(q+q+..(d times)) 7 | 8 | // rather than using loop use simple mathematics 9 | // my first code had the mistake with "m" 10 | int main() 11 | { 12 | long int t; 13 | cin>>t; 14 | for(int i=0; i>D>>d>>p>>q; 18 | long int n; // splitting on the basis of whether D is divisible by d 19 | if(D % d == 0) 20 | { 21 | n=(D/d); 22 | cout<<((p*d*n) + ((q*d)*((n-1)*(n))/2) )<= 0 && arr[j] > temp) // if current element is smaller than the element to its left 16 | { // then swap it until all the previous reach their correct position 17 | arr[j+1]=arr[j]; 18 | j--; 19 | } 20 | arr[j+1]=temp; // when every element reaches its correct position, store temp to current position 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Prefix Sum/array_manipulation.cpp: -------------------------------------------------------------------------------- 1 | // array manipulation - hackerrank 2 | // problem link: https://www.hackerrank.com/challenges/crush/problem 3 | // based on prefix sum + hashing 4 | 5 | #include 6 | using namespace std; 7 | const int N = 1e7+10; // large sized arrays should be declared globally 8 | long long int arr[N]; // globally declared arrays will be intialized to zero 9 | 10 | int main() 11 | { 12 | long int n, m; 13 | cin>>n>>m; 14 | while(m--) 15 | { 16 | int a, b, d; 17 | cin>>a>>b>>d; 18 | arr[a] += d; 19 | arr[b+1] -= d; 20 | } 21 | for(int i=1; i<=n; i++) 22 | { 23 | arr[i] +=arr[i-1]; 24 | } 25 | long long int max = -1; 26 | for(int i=1; i<=n; i++) 27 | { 28 | if(max < arr[i]) max = arr[i]; 29 | } 30 | cout<left == NULL && root->right == NULL) 10 | { 11 | if(root->data <= low && root->data >= up) ans=1; 12 | 13 | } 14 | solve(root->left, low, root->data-1, ans); 15 | solve(root->right, root->data+1, up, ans); 16 | } 17 | 18 | bool isDeadEnd(Node *root) 19 | { 20 | int ans=0; 21 | solve(root, 01, INT_MAX, ans); 22 | if(ans) return true; 23 | return false; 24 | } 25 | -------------------------------------------------------------------------------- /Binary Search Tree/construct_BST_from_preorder.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/preorder-to-postorder4423/1# 2 | // idea is to check whether nthe element is lying in range or not 3 | // root will have the range INT_MIN to INT_MAX 4 | // as we go left we change max limit as pre[pos] and as we go right we change min limit as pre[pos] 5 | 6 | Node* build(int pre[], int n, int &pos, int min, int max){ 7 | 8 | if(pos == n) return NULL; 9 | int element = pre[pos]; 10 | if(element > max || element < min) return NULL; 11 | 12 | Node* root = newNode(element); 13 | pos++; 14 | 15 | root->left = build(pre, n, pos, min, element); 16 | root->right = build(pre, n, pos, element, max); 17 | 18 | return root; 19 | } 20 | 21 | Node* constructTree(int pre[], int size) 22 | { 23 | if(size == 0) return NULL; 24 | int pos = 0; 25 | return build(pre, size, pos, INT_MIN, INT_MAX); 26 | } 27 | -------------------------------------------------------------------------------- /Dynamic Progamming/07 unbounded knapsack.cpp: -------------------------------------------------------------------------------- 1 | // notes pg: 23-25 2 | // just a minor change in line 23 3 | 4 | int unboundedKnapsack(vector& wt, vector& val, int W, int n) 5 | { 6 | int dp[n + 1][W + 1]; 7 | // initializing values 8 | for(int i=0; i < n+1; i++) 9 | { 10 | dp[i][0] = 0; 11 | } 12 | for(int j=0; j mainStack; 3 | stack helperStack; 4 | MyQueue() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | while(! mainStack.empty()) 10 | { 11 | int temp = mainStack.top(); 12 | mainStack.pop(); 13 | helperStack.push(temp); 14 | } 15 | mainStack.push(x); 16 | while(! helperStack.empty()) 17 | { 18 | int temp = helperStack.top(); 19 | helperStack.pop(); 20 | mainStack.push(temp); 21 | } 22 | } 23 | 24 | int pop() { 25 | int poppedElement = mainStack.top(); 26 | mainStack.pop(); 27 | return poppedElement; 28 | } 29 | 30 | int peek() { 31 | return mainStack.top(); 32 | } 33 | 34 | bool empty() { 35 | return mainStack.empty(); 36 | } 37 | -------------------------------------------------------------------------------- /Recursion and Backtracking/permutation_of_string.cpp: -------------------------------------------------------------------------------- 1 | // problem link:https://practice.geeksforgeeks.org/problems/permutations-of-a-given-string2041/1# 2 | // logic: to swap every character with every other character so as to generate all permutations 3 | void per(string str,vector &result, int index) 4 | { 5 | int n=str.length(); 6 | if(index == n) 7 | { 8 | result.push_back(str); 9 | return; 10 | } 11 | for(int i=index; ifind_permutation(string str) 19 | { 20 | vector result; 21 | int index=0; 22 | per(str, result, 0); 23 | sort(result.begin(), result.end()); 24 | return result; 25 | } 26 | -------------------------------------------------------------------------------- /Binary Tree/size_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // problem link: https://practice.geeksforgeeks.org/problems/size-of-binary-tree/1 3 | // method 1 4 | // i simply copied the code for traversal of tree and instead of returning vector of elements, i simply returned vector size 5 | 6 | 7 | // void solve(Node *root, vector &ans) 8 | // { 9 | // if(root != NULL) 10 | // { 11 | // ans.push_back(root->data); 12 | // solve(root->left, ans); 13 | // solve(root->right, ans); 14 | // } 15 | // } 16 | 17 | // int size(Node* root) 18 | // { 19 | // vector ans; 20 | // solve(root, ans); 21 | 22 | // return ans.size(); 23 | // } 24 | 25 | // int getSize(Node* node) 26 | // { 27 | // int answer = size(node); 28 | // return answer; 29 | // } 30 | //} 31 | 32 | 33 | // method 2: 34 | int getSize(Node* node) 35 | { 36 | if(node == NULL) return 0; 37 | return 1+getSize(node->left)+getSize(node->right); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Dynamic Progamming/08 rod cutting problem.cpp: -------------------------------------------------------------------------------- 1 | // refer notes pg: 25-27 2 | int rodCutting(vector& length, vector& price, int n) 3 | { 4 | int len = length.size(); 5 | int dp[n + 1][len + 1]; 6 | // initializing values 7 | for(int i=0; i < n+1; i++) 8 | { 9 | dp[i][0] = 0; 10 | } 11 | for(int j=0; jnext; 20 | totalElements++; 21 | } 22 | curr = head; 23 | while(curr != NULL) 24 | { 25 | decimal += ((curr->val) * (pow(2, totalElements))); 26 | totalElements--; 27 | curr = curr->next; 28 | } 29 | return decimal; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Arrays/finding 3 digit even numbers.cpp: -------------------------------------------------------------------------------- 1 | // approach 1: brute force 2 | 3 | vector findEvenNumbers(vector& arr) { 4 | // i for hundred position 5 | // j for ten position 6 | // k for unit position 7 | vector res; 8 | unordered_set s; 9 | int len = arr.size(); 10 | for(int i=0; iright 5 | vector inOrder(Node* root) 6 | { 7 | vector ans; 8 | stack s; 9 | Node *curr = root; 10 | while(curr != NULL || s.empty() == false) 11 | { 12 | // for left subtree 13 | while(curr != NULL) 14 | { 15 | s.push(curr); 16 | curr = curr->left; 17 | } 18 | curr = s.top(); 19 | s.pop(); 20 | ans.push_back(curr->data); // for root 21 | curr = curr->right; // for right subtree 22 | } 23 | return ans; 24 | } 25 | -------------------------------------------------------------------------------- /Codechef/joker_and_batman.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/START6B/problems/JOKRBTMN 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>n>>m>>l; 13 | unordered_map mp; 14 | for(int j=0; j>k; 18 | for(int it=0; it>input; 22 | mp[input] = j; 23 | } 24 | } 25 | long int strip[l], count=1; 26 | for(int it=0; it>strip[it]; 29 | } 30 | for(int it=0; it& arr, int sum, int n) 4 | { 5 | bool dp[n + 1][sum + 1]; 6 | // initializing values 7 | for(int i=0; idata != root2->data) return false; 15 | 16 | return (isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right,root2->right))|| (isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right,root2->left)); 17 | } 18 | -------------------------------------------------------------------------------- /Sorting/sort_using_comparator.cpp: -------------------------------------------------------------------------------- 1 | // watch this for more info: https://www.youtube.com/watch?v=3pvZhwp0U9w 2 | // Given an array of integers, sort it in such a way that the odd numbers appear 3 | // first and the even numbers appear later. 4 | // The odd numbers should be sorted in descending order and 5 | // the even numbers should be sorted in ascending order. 6 | #include 7 | using namespace std; 8 | bool comparator(int a, int b) 9 | { 10 | if(a%2!=0 && b%2!=0) 11 | { 12 | return a>b; 13 | } 14 | else if(a%2==0 && b%2==0) 15 | { 16 | return a>n; 29 | int arr[n]; 30 | for(int i=0; i>arr[i]; 33 | } 34 | sort(arr, arr+n, comparator); 35 | for(int i=0; inext; 14 | curr->next = prev; 15 | prev = curr; 16 | curr = next; 17 | } 18 | 19 | if(next != NULL) 20 | { // recursively calling for next k nodes 21 | head->next = reverse(next, k); // connecting first element with new head of linked list 22 | } 23 | return prev; 24 | } 25 | -------------------------------------------------------------------------------- /Searching/find_pair_difference.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/find-pair-given-difference1559/1# 2 | // two pointer approach 3 | // we used to place one pointer at the beginning and other at the end in case of sum 4 | // but here, if with decrease high from end still we may get difference less than x and increasing the low pointer may also result in the same 5 | // we cannot judge the criteria using this 6 | // so for the difference, we place one pointer at 0 and other at index 1 7 | bool findPair(int arr[], int size, int x){ 8 | sort(arr, arr+size); 9 | int low=0; 10 | int high=1; 11 | while(low < size && high < size) 12 | { 13 | if(arr[high] - arr[low] == x && low != high) return true; // to avoid the failing case when difference=0. when low=high in that case we can get diff 0 but that is obviously not correct 14 | else if(arr[high] - arr[low] < x) high++; 15 | else low++; 16 | } 17 | return false; 18 | } 19 | -------------------------------------------------------------------------------- /Binary Search Tree/insert_node_in_bst.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/insert-a-node-in-a-bst/1 2 | // idea is that if key is greater than current node's data then make current = current->right 3 | // else if key is smaller than current node's then make current = current->left 4 | // else if the current node's data is equal to key than no need to change anything, simply return root 5 | // iterative solution 6 | 7 | Node* insert(Node* root, int key) { 8 | Node *keynode = new Node(key); 9 | Node *parent = NULL; 10 | Node *curr = root; 11 | 12 | while(curr != NULL) 13 | { 14 | parent = curr; 15 | 16 | if(curr->data < key) curr = curr->right; 17 | else if(curr->data > key) curr = curr->left; 18 | else return root; 19 | } 20 | if(parent == NULL) return keynode; 21 | 22 | if(parent->data < key) parent->right = keynode; 23 | else parent->left = keynode; 24 | return root; 25 | } 26 | -------------------------------------------------------------------------------- /Binary Tree/Postorder_traversal_iterative_2_stacks.cpp: -------------------------------------------------------------------------------- 1 | // problem link : https://practice.geeksforgeeks.org/problems/postorder-traversal/1 2 | // iterative solution using two stacks 3 | // issue with post order. why it is complicated? 4 | // ans: because it requires two signals: 1. if left subtree is finished 2. if right subtree is finished 5 | // idea is that one stack will be storing left elements and other will be storing the right elements 6 | vector postOrder(Node* root) 7 | { 8 | vector ans; 9 | stack curr; 10 | if(root == NULL) return ans; 11 | stack s1, s2; 12 | s1.push(root); 13 | while(! s1.empty()) 14 | { 15 | root = s1.pop(); 16 | s2.push(root); 17 | if(root->left != NULL) s1.push(root->left); 18 | if(root->right != NULL) s2.push(root->right); 19 | } 20 | while(! s2.empty()) 21 | { 22 | ans.push_back(s2.top()->data); 23 | s2.pop(); 24 | } 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /Codeforces/A-point_on_spiral.cpp: -------------------------------------------------------------------------------- 1 | // problem link: 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int x, y, ans; 8 | cin>>x>>y; 9 | long int maxi = max(abs(x), abs(y)); 10 | ans = 4*(maxi-1); // ans=4 11 | //cout<0 && y<0 ))) && check == true) 24 | { 25 | if(x == maxi) ans +=1; 26 | else if((-x) == maxi) ans+= 3; 27 | else if(y == maxi) ans+= 2; 28 | else if((-y) == maxi) ans+=4; 29 | } 30 | else if(((abs(x) == abs(y) )) && check == true) 31 | { 32 | if(x>0 && y>0) ans+=1; 33 | if(x<0 && y>0) ans+=2; 34 | if(x<0 && y<0) ans+=3; 35 | if(x>0 && y<0) ans+=4; 36 | } 37 | if (abs(abs(x) - abs(y)) == 1 && x>0 && y<0 && check == true) ans-=1; 38 | cout< modifyQueue(queue q, int k) 11 | { 12 | queue ans; 13 | int n = q.size(); 14 | stack s; 15 | for(int i=0; ileft, ans); 11 | int right_height = solve(maxi, root->right, ans); 12 | if(left) 13 | if(abs(left_height - right_height) > 1) ans=0; 14 | return 1+max(left_height, right_height); 15 | } 16 | bool isBalanced(Node *root) 17 | { 18 | int maxi=0; 19 | int ans=1; 20 | solve(maxi, root, ans); 21 | if(ans == 1) return true; 22 | return false; 23 | } 24 | -------------------------------------------------------------------------------- /Dynamic Progamming/0-1 knapsack.cpp: -------------------------------------------------------------------------------- 1 | // given weight and value vectors and knapsack capacity W 2 | // find maximum profit 3 | // refer notes pg: 3-9 4 | 5 | int 01knapsack(vector& wt, vector& val, int W, int n) 6 | { 7 | int dp[n + 1][W + 1]; 8 | // initializing values 9 | for(int i=0; i < n+1; i++) 10 | { 11 | dp[i][0] = 0; 12 | } 13 | for(int j=0; jv, u appears before v in that ordering 3 | // using dfs 4 | 5 | 6 | void topoUsingDfs(int curr, vector &visited, vector &topo, vectoradj[]) 7 | { 8 | visited[curr] = 1; 9 | for(auto it: adj[curr]) 10 | { 11 | if(! visited[it]) topoUsingDfs(it, visited, topo, adj); 12 | } 13 | topo.push_back(curr); 14 | } 15 | 16 | vector topoSort(int v, vector adj[]) 17 | { 18 | vector visited(v, 0); 19 | vector topo; 20 | for(int i=0; ileft and root->right 4 | 5 | void childrenSum(int &ans, Node* root) 6 | { 7 | if(root == NULL) return; 8 | 9 | if(root->left == NULL && root->right == NULL) return; 10 | 11 | int sum = 0; 12 | 13 | if(root->left) sum += root->left->data; 14 | if(root->right) sum += root->right->data; 15 | 16 | if(root->data != sum) 17 | { 18 | ans = 0; 19 | return; 20 | } 21 | if(root->left) childrenSum(ans, root->left); 22 | if(root->right) childrenSum(ans, root->right); 23 | 24 | } 25 | 26 | int isSumProperty(Node *root) 27 | { 28 | int ans=1; 29 | childrenSum(ans, root); 30 | return ans; 31 | } 32 | -------------------------------------------------------------------------------- /Codechef/bitwise_tuples.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/JUNE21C/problems/BITTUP 2 | // firstly tried the brute force approach by variable number of for loops and tried to observe the pattern 3 | // and interestingly found an equation which satisfied all the test cases: (2^n - 1)^m 4 | // but here binary exponention is used as well since modulo along with exponention 5 | // for more info on binary exponention: https://cp-algorithms.com/algebra/binary-exp.html 6 | #include 7 | using namespace std; 8 | long long power(long long a, long long b, long long num) 9 | { 10 | a%=num; 11 | long long res=1; 12 | while(b > 0) 13 | { 14 | if (b & 1) res = res * a % num; 15 | a = a * a % num; 16 | b /= 2; 17 | } 18 | return res; 19 | } 20 | int main() 21 | { 22 | long int t,n,m; 23 | cin>>t; 24 | for(int i=0; i>n>>m; 27 | cout< bfsOfGraph(int v, vector adj[]) { 2 | vector bfs; 3 | vector visited(v, 0); 4 | for(int i=0; i q; 9 | q.push(i); 10 | visited[i] = 1; 11 | while(! q.empty()) 12 | { 13 | int top = q.front(); 14 | q.pop(); 15 | bfs.push_back(top); 16 | 17 | for(int i=0; i n* min(a,b) 2 | // 2->8 3 | // mid = 5 5/2 = 2 (2 divisors pehle aa chuke hai) 5/3 = 1 4 | // 3 divisors before this number and this number is not divisible 3 = 0) then ans will be equal to sum all elements simply 3 | // if there are odd number of non-positive numbers(number >= 0) then ans will be equal to sum all elements - min_absolute value from all elements 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | long int t; 11 | cin>>t; 12 | for(int z=0; z>n>>m; 16 | long int a[n][m], total_abs_sum=0, mini = INT_MAX, ans, negative=0; 17 | 18 | for(int i=0; i>a[i][j]; 23 | total_abs_sum += abs(a[i][j]); 24 | if(a[i][j] <= 0) negative++; 25 | if(abs(a[i][j]) < mini) mini = abs(a[i][j]); 26 | } 27 | } 28 | 29 | if(negative% 2 != 0) ans = total_abs_sum - (2*abs(mini)); 30 | else ans = total_abs_sum; 31 | cout<next; 18 | } 19 | Node *second = head; 20 | while(first != NULL) 21 | { 22 | first = first -> next; 23 | second = second -> next; 24 | } 25 | return (second->data); 26 | } 27 | -------------------------------------------------------------------------------- /Sorting/Sorting_Algorithms/Selectionsort.cpp: -------------------------------------------------------------------------------- 1 | // selection sort algorithm visualizer: https://www.hackerearth.com/practice/algorithms/sorting/selection-sort/visualize/ 2 | // time complexity: BEST CASE: O(N^2) 3 | // AVERAGE CASE: O(N^2) 4 | // WORST CASE: O(N^2) 5 | // Space complexity: O(1) 6 | // UNSTABLE 7 | // IN-PLACE ALGORITHM 8 | // it works on finding minimum element in each iteration and swap it 9 | void selectionsort(int arr[], int n) 10 | { 11 | int min; 12 | // reduces the effective size of the array by one in each iteration 13 | for(int i=0; inext == NULL) { 18 | delete head; 19 | return NULL; 20 | } 21 | ListNode* slow = head; 22 | ListNode* fast = head; 23 | ListNode* prev = head; 24 | while(fast != NULL && fast->next != NULL) 25 | { 26 | if(slow != head) prev = prev->next; 27 | slow = slow->next; 28 | fast = fast->next->next; 29 | } 30 | prev->next = slow->next; 31 | delete slow; 32 | return head; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Queue/implementation_of_queue_stl.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void displayQueue(queue q) 6 | { 7 | int n = q.size(); 8 | 9 | for(int i=0; i q1; 22 | 23 | //Enqueue - Pushing elements to queue 24 | q1.push(1); 25 | q1.push(2); 26 | q1.push(4); 27 | 28 | cout<<"Elements of Queue are : "; 29 | //display Queue 30 | displayQueue(q1); 31 | 32 | //Show front and rear of queue 33 | cout<<"Element at front is : "< postOrder(Node* root) 5 | { 6 | vector ans; 7 | stack s; 8 | Node *curr = root; 9 | Node *prev = NULL; 10 | 11 | while(curr != NULL || s.empty() == false) 12 | { 13 | if(curr != NULL) 14 | { 15 | s.push(curr); 16 | curr = curr->left; 17 | } 18 | else 19 | { 20 | curr = s.top(); 21 | if(curr->right == NULL || curr->right == prev) 22 | { 23 | ans.push_back(curr->data); 24 | s.pop(); 25 | prev = curr; 26 | curr = NULL; 27 | } 28 | else 29 | { 30 | curr = curr->right; 31 | } 32 | } 33 | } 34 | return ans; 35 | } 36 | -------------------------------------------------------------------------------- /Stack/evaluation_of_postfix_expression.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1 2 | 3 | int evaluatePostfix(string str) 4 | { 5 | stack s; 6 | int len = str.length(); 7 | for(int i=0; i= 48 && str[i] <= 57) 10 | { 11 | s.push(str[i] - 48); 12 | } 13 | else 14 | { 15 | int op2 = s.top(); 16 | s.pop(); 17 | 18 | int op1 = s.top(); 19 | s.pop(); 20 | 21 | switch (str[i]) 22 | { 23 | case '+': s.push(op1 + op2); break; 24 | case '-': s.push(op1 - op2); break; 25 | case '*': s.push(op1 * op2); break; 26 | case '/': s.push(op1 / op2); break; 27 | } 28 | } 29 | } 30 | return s.top(); 31 | } 32 | -------------------------------------------------------------------------------- /Dynamic Progamming/03 count subset with given sum.cpp: -------------------------------------------------------------------------------- 1 | // similar to partition equal subset with just few changes 2 | // refer notes to understand the similarities 3 | // notes pg 15-16 4 | int countSubsetWithGivenSum(vector& nums, int sum) { 5 | int n = nums.size(); 6 | 7 | int dp[n+1][sum + 1]; 8 | for(int i=0; inext==NULL) return head; 5 | unordered_set s; 6 | Node *curr = head; 7 | Node *prev = head; 8 | Node *temp = NULL; 9 | bool check = false; 10 | while(curr != NULL) 11 | { 12 | if(s.find(curr->data) != s.end()) 13 | { 14 | temp = curr; 15 | prev->next = curr->next; 16 | delete(curr); 17 | check = true; 18 | } 19 | else 20 | { 21 | s.insert(curr->data); 22 | temp = curr; 23 | } 24 | 25 | if(curr != head && check == false) prev = prev->next; 26 | curr = temp->next; 27 | check = false; 28 | } 29 | return head; 30 | } 31 | -------------------------------------------------------------------------------- /Binary Search Tree/check_for_BST.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/check-for-bst/1 2 | // method 1: maintain a range in which every node is supposed to be 3 | // if going towards left, change max limit 4 | // if going towards right, change min limit 5 | 6 | // method 2: a bt is bst if and only if its inorder traversal is sorted 7 | // traverse the tree in inorder manner 8 | // maintain a global variable prev which ensures if prev one is smaller 9 | // no need to use any auxiliary array 10 | 11 | // method 1: 12 | bool solve(Node* root, int min, int max) 13 | { 14 | if(root == NULL) return true; 15 | 16 | if(root->data > min && root->data < max ) 17 | { 18 | return solve(root->left, min, root->data) && solve(root->right, root->data, max); 19 | } 20 | else return false; 21 | } 22 | 23 | bool isBST(Node* root) 24 | { 25 | if(solve(root, INT_MIN, INT_MAX)) return true; 26 | return false; 27 | } 28 | -------------------------------------------------------------------------------- /Stack/parenthesis_checker.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/parenthesis-checker2744/1 2 | bool match(char a, char top) 3 | { 4 | if((a == ')' && top == '(') || (a == '}' && top == '{') || (a == ']' && top == '[')) return true; 5 | return false; 6 | } 7 | 8 | bool ispar(string x) 9 | { 10 | stack s; 11 | for(int i=0; i s; 8 | s.push(-1); 9 | int len = str.length(), curr = 0, res = 0; 10 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>str; 13 | long int n=str.length(); 14 | if(n <= 3) cout<<"Error"<') // to check for the basic syntax 17 | { 18 | for(int j=2; j= 'a' && str[j] <= 'z' ) || str[j] >= '0' && str[j] <= '9') // to check if body is aplha numeric 21 | { 22 | if(j == n-2) cout<<"Success"< &visited, vector adj[]) 4 | { 5 | visited[curr] = 1; 6 | for(auto it: adj[curr]) 7 | { 8 | if(visited[it] == 0) 9 | { 10 | if(cycleDetectionUsingDfs(it, curr, visited, adj)) return true; 11 | } 12 | else if(prev != it) 13 | { 14 | return true; 15 | } 16 | } 17 | return false; 18 | } 19 | 20 | bool isCycle(int v, vector adj[]) 21 | { 22 | vector visited(v, 0); 23 | for(int i=0; iright, key, count, check); 8 | 9 | if(check == false)count++; 10 | if(count == key) 11 | { 12 | //cout<data; 13 | count = root->data; 14 | check = true; // if we don't keep bool check than when function goes back to previous caller everytime it will do count++ which will change 15 | return; 16 | } 17 | 18 | solve(root->left, key, count, check); 19 | } 20 | 21 | int kthLargest(Node *root, int key) 22 | { 23 | int count=0; 24 | bool check = false; 25 | solve(root, key, count, check); 26 | 27 | return count; 28 | } 29 | -------------------------------------------------------------------------------- /Matrix/row_with_max_1s.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1# 2 | int rowWithMax1s(vector > arr, int n, int m) { 3 | // hint = take full adavantage of rows being sorted 4 | // if we find first index of 1 in a row we can calculate total 1's 5 | // we start from the top-right index and traverse left in case its a 1 and down in case its a 0 6 | int row=arr.size(), col=arr[0].size(); 7 | int i=0, j=col-1, count=0; 8 | int maxi=0 ,ans=-1; 9 | while(i <= row-1 && j >= 0) 10 | { 11 | if(arr[i][j] == 1) 12 | { 13 | j--; 14 | count++; 15 | } 16 | else 17 | { 18 | if(count > maxi) 19 | { 20 | maxi=max(maxi, count); 21 | ans=i; 22 | } 23 | i++; 24 | } 25 | } 26 | // incase our first row has all ones -> for such cases 27 | if(count > maxi) 28 | { 29 | ans=i; 30 | } 31 | return ans; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Binary Tree/leaf_at_same_level.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/leaf-at-same-level/1 2 | 3 | bool leafLevel(Node* node, int level, int *firstLevel) 4 | { 5 | if(node == NULL) return true; // if node is null 6 | if(node->left == NULL && node->right == NULL) // leaf node 7 | { 8 | if(*firstLevel == 0) // leaf node seen for the first time 9 | { 10 | *firstLevel = level; // noting first leaf node level 11 | return true; 12 | } 13 | else 14 | { 15 | return (level == *firstLevel); // if leaf node is not for the first time 16 | } 17 | } 18 | // if not a leaf node then recursively call for its left and right 19 | return (leafLevel(node->left, level+1, firstLevel) && leafLevel(node->right, level+1, firstLevel)); 20 | } 21 | 22 | bool check(Node *root) 23 | { 24 | int level=0; 25 | int firstLevel = 0; 26 | return leafLevel(root, level, &firstLevel); 27 | } 28 | -------------------------------------------------------------------------------- /Binary Tree/zigzag_traversal.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/zigzag-tree-traversal/1# 2 | // using the same code of level order traversal with one slight change 3 | // reversing the output after every alternate levels 4 | 5 | vector zigZagTraversal(Node* node) 6 | { 7 | vector ans; 8 | queue q; 9 | q.push(node); 10 | int idx=0, temp=0; 11 | while(q.size() != 0) 12 | { 13 | int count = q.size(); 14 | for(int i=0; idata); 21 | if(top -> left) q.push(top->left); 22 | if(top -> right) q.push(top->right); 23 | } 24 | } 25 | if(idx%2 != 0) reverse(ans.begin()+temp, ans.end()); 26 | idx++; 27 | temp+=count; 28 | } 29 | return ans; 30 | } 31 | -------------------------------------------------------------------------------- /Codechef/prefix_sums.cpp: -------------------------------------------------------------------------------- 1 | // problem link: codechef.com/LTIME100B/problems/UNQEQ/ 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>n; 13 | if(((n/2) % 2) != 0 || n==2) cout<<"NO"< (n/2) && check == false) 22 | { 23 | num++; 24 | check =true; 25 | } 26 | 27 | cout< (n/2) && check == false) 37 | { 38 | num--; 39 | check =true; 40 | } 41 | 42 | cout< s; 9 | for(int i=0; i= arr[i]) 12 | { 13 | int curr = s.top(); 14 | s.pop(); 15 | temp = (s.empty() ? i : (i-s.top()-1))*arr[curr]; 16 | res = max(res, temp); 17 | } 18 | s.push(i); 19 | } 20 | while(s.empty() == false) 21 | { 22 | curr = s.top(); 23 | s.pop(); 24 | temp = arr[curr] * (s.empty() ? n : (n-s.top()-1)); 25 | res = max(res, temp); 26 | } 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /Arrays/maximum_sum_of_subarray_less_than_or_equal_to_x.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/maximum-sum-of-subarray-less-than-or-equal-to-x4033/1/?category[]=sliding-window&category[]=sliding-window&difficulty[]=0&page=1&sortBy=submissions&query=category[]sliding-windowdifficulty[]0page1sortBysubmissionscategory[]sliding-window# 2 | // window sliding technique 3 | int findMaxSubarraySum(long long arr[], int n, long long x) 4 | { 5 | // little modification of kadane's Algorithm 6 | int best=0,sum=0,start=0,j; 7 | 8 | for(j=0; j<=n; j++) 9 | { 10 | if(sum <= x) 11 | { 12 | best=max(best,sum); 13 | } 14 | 15 | 16 | while(sum+arr[j] > x && start < j) 17 | { 18 | sum-=arr[start]; // if sum is greater than the required sum than we decrement the starting elements 19 | start++; 20 | } 21 | sum+=arr[j]; 22 | } 23 | 24 | 25 | return best; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Binary Tree/reverse_level_order_traversal.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/reverse-level-order-traversal/1# 2 | // almost similar code as that of level order traversal the only difference is adding reverse at two places 3 | vector reverseLevelOrder(Node *node) 4 | { 5 | vector ans; 6 | queue q; 7 | q.push(node); 8 | int idx=0; 9 | while(q.size() != 0) 10 | { 11 | int count = q.size(); 12 | for(int i=0; idata); 19 | if(top -> left) q.push(top->left); 20 | if(top -> right) q.push(top->right); 21 | } 22 | } 23 | 24 | reverse(ans.begin()+idx, ans.end()); 25 | idx += count; 26 | 27 | } 28 | reverse(ans.begin(), ans.end()); 29 | return ans; 30 | } 31 | -------------------------------------------------------------------------------- /Arrays/rotate_a_number.java: -------------------------------------------------------------------------------- 1 | // problem link: https://www.pepcoding.com/resources/online-java-foundation/getting-started/rotate-a-number-official/ojquestion# 2 | import java.util.*; 3 | 4 | public class Main{ 5 | 6 | public static void main(String[] args) { 7 | 8 | Scanner scn = new Scanner(System.in); 9 | int n = scn.nextInt(); 10 | int k = scn.nextInt(); 11 | int temp,count=0,temp1; 12 | temp1 = n; 13 | while(temp1 > 0) 14 | { 15 | temp1 = temp1 / 10; 16 | count++; 17 | } 18 | if(k > 0) 19 | { 20 | k = k % count; 21 | if(k == 0) 22 | { 23 | k = count; 24 | } 25 | } 26 | else 27 | { 28 | if(k == 0) k=count; 29 | else 30 | { 31 | k = (-k) % count; 32 | k = count - k; 33 | } 34 | } 35 | temp = n % ((int) Math.pow(10,k)); 36 | n = n - temp; 37 | n = n / ((int)Math.pow(10,k)); 38 | n = n + (temp * ((int ) Math.pow(10,count-k))); 39 | System.out.println(n); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Queue/queue_using_two_stacks.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/queue-using-two-stacks/1# 2 | // push: simply pushing the element in o(1) 3 | // pop: if both are empty we return -1 4 | // if s2 is empty then we transfer all the elements from s1 to s2 and then return top of s2 since elements in s2 will now be in reversed order 5 | // now after we transferred all elements from s1 to s2, now we have to simply pop the element from s2 until its empty since element are stored in reversed order 6 | //Function to push an element in queue by using 2 stacks. 7 | void StackQueue :: push(int x) 8 | { 9 | s1.push(x); 10 | return; 11 | } 12 | 13 | //Function to pop an element from queue by using 2 stacks. 14 | 15 | int StackQueue :: pop() 16 | 17 | { 18 | if(s1.empty() && s2.empty()) return -1; 19 | 20 | if(s2.empty()) 21 | { 22 | while(s1.empty() == false) 23 | { 24 | s2.push(s1.top()); 25 | s1.pop(); 26 | } 27 | 28 | } 29 | int temp = s2.top(); 30 | s2.pop(); 31 | return temp; 32 | } 33 | -------------------------------------------------------------------------------- /Binary Search Tree/fixing_two_nodes_of_BST.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/fixed-two-nodes-of-a-bst/1 2 | // idea: inorder traversal of bst is sorted. using this fact we have to find the elements which are violating this 3 | // there can be 2 cases in that: 4 | // 1. the nodes which are to be swapped are adjacent 5 | // 2. not adjacent 6 | // basically the problem is reduced to finding two elements from array which are making array unsorted 7 | 8 | Node* prev = NULL; 9 | Node* first = NULL; 10 | Node* second = NULL; 11 | 12 | void solve(Node* root) 13 | { 14 | if(root == NULL) return; 15 | solve(root->left); 16 | 17 | if(prev != NULL && root->data < prev->data) 18 | { 19 | if(first == NULL) first = prev; 20 | second = root; 21 | } 22 | prev = root; 23 | 24 | solve(root->right); 25 | } 26 | 27 | void correctBST( struct Node* root ) 28 | { 29 | solve(root); 30 | swap(first->data, second->data); 31 | return; 32 | } 33 | -------------------------------------------------------------------------------- /Codeforces/A-shortest_path_with_obstacle.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1547/problem/A 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long int t; 8 | cin>>t; 9 | for(int i=0; i>xa>>ya; 13 | cin>>xb>>yb; 14 | cin>>xf>>yf; 15 | if(xa != xb && ya != yb) ans=(abs(xa-xb)+abs(ya-yb)); 16 | if(xa == xb) 17 | { 18 | if(xf == xa && ((yf < ya && yf > yb) || (yf > ya && yf < yb))) 19 | { 20 | ans=abs(ya-yb)+2; 21 | } 22 | else 23 | { 24 | ans=abs(ya-yb); 25 | } 26 | } 27 | if(ya == yb ) 28 | { 29 | if(yf == ya && ((xf < xa && xf > xb) || xf > xa && xf < xb)) 30 | { 31 | ans=abs(xa-xb)+2; 32 | } 33 | else 34 | { 35 | ans=abs(xa-xb); 36 | } 37 | } 38 | cout< countDistinct (int arr[], int n, int k) 3 | { 4 | vector ans; 5 | unordered_map mp; 6 | int left=0, right=0; 7 | for(right=0; rightval < x) 21 | { 22 | curr1->next = curr; 23 | curr1 = curr1->next; 24 | } 25 | else 26 | { 27 | curr2->next = curr; 28 | curr2 = curr2->next; 29 | } 30 | curr = curr->next; 31 | } 32 | curr1->next = dummy2->next; 33 | curr2->next = NULL; 34 | return dummy1->next; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Codechef/even_tuples.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/START6B/problems/ETU 2 | P#include 3 | using namespace std; 4 | 5 | 6 | int main() 7 | { 8 | long int t; 9 | cin>>t; 10 | for(int i=0; i>n>>q; 14 | long int arr[n], odd[n+1], even[n+1], e=0, o=0; 15 | odd[0]=0, even[0]=0; 16 | for(int j=0; j>arr[j]; 19 | if(arr[j]% 2 == 0) 20 | { 21 | even[j+1]=(++e); 22 | odd[j+1]=o; 23 | } 24 | else 25 | { 26 | even[j+1]=e; 27 | odd[j+1]=(++o); 28 | } 29 | } 30 | long int l, r, ans=0; 31 | for(int j=0; j>l>>r; 34 | long int n_odd = odd[r]-odd[l-1]; 35 | long int n_even = even[r]-even[l-1]; 36 | ans = n_even*(n_odd*(n_odd-1))/2 + (n_even*(n_even-1)*(n_even-2))/6; 37 | cout<data >= l && root->data <= h) 12 | { 13 | count++; 14 | solve(root->left, l, h, count); 15 | solve(root->right, l, h, count); 16 | } 17 | 18 | else if(root->data < l) solve(root->right, l, h, count); 19 | 20 | else solve(root->left, l, h, count); 21 | } 22 | 23 | int getCount(Node *root, int l, int h) 24 | { 25 | int count=0; 26 | solve(root, l, h, count); 27 | return count; 28 | } 29 | -------------------------------------------------------------------------------- /Matrix/make_matrix_beautiful.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/make-matrix-beautiful-1587115620/1/?track=P100-Matrix&batchId=197# 2 | 3 | int findMinOpeartion(vector > matrix, int n) 4 | { 5 | int row[n]={0}, col[n]={0}; 6 | int maxi=0, ans=0; 7 | for(int i=0; i 1) // reducing until we find the repeating element 15 | { 16 | count[str[start]]--; 17 | start++; 18 | } 19 | ans=max(ans, end-start+1); // to calculate maximum length 20 | } 21 | 22 | return ans; 23 | } 24 | -------------------------------------------------------------------------------- /Sorting/merge_intervals.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://leetcode.com/problems/merge-intervals/submissions/ 2 | vector> merge(vector>& intervals) { 3 | sort(intervals.begin(),intervals.end()); 4 | vector>merged; 5 | 6 | int start=intervals[0][0],end=intervals[0][1]; 7 | // start and end keeps the track of merged intervals' range 8 | 9 | for(int i=1; i=start && intervals[i][0]<=end) // if the next interval merges with the previous one. 12 | { 13 | end=max(end,intervals[i][1]); // end of merged interval is maximum of end of previous interval and current interval 14 | } 15 | else 16 | { 17 | merged.push_back({start,end}); // once merging stops, we add the newly merged range to final answer 18 | start=intervals[i][0]; 19 | end=intervals[i][1]; 20 | } 21 | } 22 | 23 | merged.push_back({start,end}); 24 | return merged; 25 | } 26 | -------------------------------------------------------------------------------- /Sorting/sort_by_set_bit.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/sort-by-set-bit-count1153/1# 2 | // expected time complexity: O(n log n) and space complexity o(1) 3 | // naive approach: using an auxillary array and storing countbits value using bit manipulation = TLE 4 | // better approach: since we have a parameter(countbits) on the basis of which array has to be sorted therefore comparators in inbuilt sort is bestly suited 5 | // and using countbits by bit manipulation = TLE 6 | // efficient approach: using STL function __inbuilt_popcount which gives countbits and all this in a comparator function = ACCEPTED 7 | // checkout: STL functions repo -> bit manipulation -> countbits.cpp 8 | // to get more info on __inbuilt_popcount(int n) 9 | 10 | static bool comparator(int a,int b) // not using static here threw an error 11 | { 12 | return __builtin_popcount(a) > __builtin_popcount(b); 13 | } 14 | void sortBySetBitCount(int arr[], int n) 15 | { 16 | stable_sort(arr,arr+n,comparator); // by simply using sort gave an error so used stable_sort 17 | } 18 | -------------------------------------------------------------------------------- /Dynamic Progamming/10 coin change problem (minimum number of coins).cpp: -------------------------------------------------------------------------------- 1 | // refer notes pg: 29-32 2 | int coinChange(vector& coin, int sum) 3 | { 4 | int n = coin.size(); 5 | int dp[n + 1][sum + 1]; 6 | // initializing values 7 | for(int j=0; j<=sum; i++) 8 | { 9 | dp[0][j] = INT_MAX-1; 10 | if(j % arr[0] != 0) 11 | { 12 | dp[1][j] = INT_MAX-1; 13 | } 14 | else 15 | { 16 | dp[1][j] = j/arr[0]; 17 | } 18 | } 19 | for(int i=0; i<=n; i++) 20 | { 21 | dp[i][0] = 0; 22 | } 23 | // filing the matrix 24 | for(int i=2; i<=n; i++) 25 | { 26 | for(int j=1; j<=sum; j++) 27 | { 28 | if(coin[i-1] <= j) 29 | { 30 | dp[i][j] = min(dp[i][j - coin[i-1]] + 1, dp[i-1][j])); 31 | } 32 | else 33 | { 34 | dp[i][j] = dp[i - 1][j]; 35 | } 36 | } 37 | } 38 | return dp[n][sum]; 39 | } 40 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/odd even linked list.cpp: -------------------------------------------------------------------------------- 1 | // my approach: took 2 examples, one of odd number of elements and other of even 2 | // taking two nodes, one will run for odd numbered index and other for even numbered index 3 | // to handle the cases for both odd and even numbered elements a case of even->next = null has to be handled 4 | 5 | ListNode* oddEvenList(ListNode* head) { 6 | // to handle edge cases 7 | if(head == NULL || head->next == NULL) return head; 8 | // initializing two pointers 9 | ListNode *odd = head, *even = head->next; 10 | ListNode *firstEvenNode = head->next; 11 | 12 | while(even->next != NULL ) 13 | { 14 | odd->next = odd->next->next; 15 | even->next = even->next->next; 16 | 17 | odd = odd->next; 18 | if(even->next == NULL) // to handle odd numbered of elements 19 | { 20 | break; 21 | } 22 | even = even->next; 23 | } 24 | odd->next = firstEvenNode; // to connect odd and even linked lists 25 | 26 | return head; 27 | } 28 | -------------------------------------------------------------------------------- /Binary Tree/serialize_and_deserialize_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1 2 | // preorder traversal and using -1 for null 3 | 4 | void serialization(Node *root, vector &ans) 5 | { 6 | if(root == NULL) 7 | { 8 | ans.push_back(-1); 9 | return; 10 | } 11 | 12 | ans.push_back(root->data); 13 | serialization(root->left, ans); 14 | serialization(root->right, ans); 15 | } 16 | 17 | vector serialize(Node *root) 18 | { 19 | vector ans; 20 | serialization(root, ans); 21 | 22 | return ans; 23 | } 24 | 25 | //Function to deserialize a list and construct the tree. 26 | 27 | int idx = 0; 28 | Node * deSerialize(vector &arr) 29 | { 30 | if(idx == arr.size()) return NULL; 31 | int value = arr[idx++]; 32 | if(value == -1) return NULL; 33 | Node *root = new Node(value); 34 | root->left = deSerialize(arr); 35 | root->right = deSerialize(arr); 36 | return root; 37 | } 38 | -------------------------------------------------------------------------------- /Bit Manipulation/swap_all_odd_and_even_bits.cpp: -------------------------------------------------------------------------------- 1 | 2 | // problem link: https://practice.geeksforgeeks.org/problems/swap-all-odd-and-even-bits-1587115621/1/?track=P100-Bit%20Magic&batchId=197 3 | // approach: expression len = (int)(log2(n)+1) gives the numbers of bits required to represent that number 4 | // if len is odd than we add 1 to it since we need to swap pairs so we need even number 5 | // now we compare two consecutive bits in one iteration and if they are different, we toggle them 6 | 7 | 8 | int toggleBit(int n, int k) 9 | { 10 | return (n ^ (1 << (k - 1))); 11 | } 12 | 13 | int printKthBit(unsigned int n, unsigned int k) 14 | { 15 | return ((n & (1 << (k - 1))) >> (k - 1)); 16 | } 17 | unsigned int swapBits(unsigned int n) 18 | { 19 | int len; 20 | if(n % 2 == 0) len = (int)(log2(n)+1); 21 | else len = (int)(log2(n)+1) +1; 22 | for(int i=1; i<=len; i+=2) 23 | { 24 | if(printKthBit(n, i) != printKthBit(n, i+1)) 25 | { 26 | n = toggleBit(n, i); 27 | n = toggleBit(n, i+1); 28 | } 29 | } 30 | return n; 31 | } 32 | -------------------------------------------------------------------------------- /Hashing/longest_subarray_with_sum_k.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1# 2 | int lenOfLongSubarr(int arr[], int n, int x) 3 | { 4 | unordered_map mp; // this map stores array element as keys and first occurrence of that array element as value 5 | int sum = 0, ans = 0; 6 | 7 | for(int i=0; i prefix sum = 2 5 11 11 | { // so if this loop is not included then the above mentioned example proves out to be wrong 12 | ans = i+1; 13 | } 14 | if(mp.find(sum) == mp.end()) 15 | { 16 | mp.insert({sum, i}); // incase its the first occurrence of that element then we store its index 17 | } 18 | if(mp.find(sum - x) != mp.end()) // in case such array with x sum is available 19 | { 20 | ans = max(ans, i-mp[sum - x]); 21 | } 22 | 23 | } 24 | return ans; 25 | } 26 | -------------------------------------------------------------------------------- /Recursion and Backtracking/possible_words from phone_digits.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/possible-words-from-phone-digits-1587115620/1# 2 | void word_generator (int arr[], int n, string keypad[], vector &res, int index, string str) 3 | { 4 | // idea is whatever is returned by "faith" part of recursion is appended with each of the first character and that results in all possible outcomes 5 | if(index == n) 6 | { 7 | res.push_back(str); 8 | return; 9 | } 10 | string helper=keypad[arr[index]]; 11 | for(int i=0; i possibleWords(int arr[], int n) 18 | { 19 | string keypad[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; // to define the values as respective numbers 20 | vector res; 21 | string str=""; 22 | word_generator(arr, n, keypad, res, 0, str); 23 | sort(res.begin(), res.end()); 24 | return res; 25 | } 26 | -------------------------------------------------------------------------------- /Arrays/Number_of_subarrays_with maximum_values_in_given_range.cpp: -------------------------------------------------------------------------------- 1 | //Problem link: https://practice.geeksforgeeks.org/problems/number-of-subarrays-with-maximum-values-in-given-range5949/1 2 | //My YouTube Code Explanation video😎: https://www.youtube.com/watch?v=J1PauAVnVWI 3 | //Window Sliding Technique 4 | 5 | // l< Element< r ---> King 6 | // Element> r ---> Villian 7 | // Element< l ---> Aam Janta 8 | 9 | // Fact that will helping hand of this solution💡: Number of subarrays including last element of array 10 | // is always equal to size of array 😁 11 | class Solution{ 12 | public: 13 | long countSubarrays(int a[], int n, int L, int R) 14 | { 15 | long int start=0,end=0,ans=0,empire=0 16 | for(int end=0; end=l && arr[end]<=r) 19 | { // king 20 | empire=end-start+1; 21 | } 22 | 23 | if(arr[end]>r) 24 | { // villain 25 | empire=0; // king ka empire tut gaya 26 | start=end+1; // naya empire 27 | } 28 | ans = ans + empire; 29 | } 30 | return ans; 31 | } 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /Searching/common_elements_in_3_sorted_arrays.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/common-elements1132/1# 2 | 3 | vector commonElements (int a[], int b[], int c[], int n1, int n2, int n3) 4 | { 5 | vector ans; 6 | int i=0, j=0, k=0; 7 | // using three pointers 8 | while(i < n1 && j < n2 && k < n3) 9 | { 10 | int maximum = max(max(a[i], b[j]), c[k]); // searching for the maximum element from three of them 11 | 12 | while(a[i] <= maximum && i < n1) i++; // moving the first pointer until we reach a element either = or greater than maximum 13 | i--; 14 | while(b[j] <= maximum && j < n2) j++; // similarly moving second and third pointers 15 | j--; 16 | while(c[k] <= maximum && k < n3) k++; 17 | k--; 18 | 19 | if(a[i] == b[j] && b[j] == c[k]) ans.push_back(a[i]); // checking if they are same 20 | i++; 21 | j++; 22 | k++; 23 | } 24 | return ans; 25 | } 26 | -------------------------------------------------------------------------------- /Binary Tree/left_view_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | // problem link: https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1# 3 | // method 1: i simply used the code of level order traversal 4 | // but instead of adding all elements to ans vector, i simply add only the first element of every level 5 | vector leftView(Node *node) 6 | { 7 | vector ans; 8 | queue q; 9 | q.push(node); 10 | int idx=0; 11 | bool check = false; 12 | while(q.size() != 0) 13 | { 14 | int count = q.size(); 15 | check = true; 16 | for(int i=0; idata); 25 | check = false; 26 | } 27 | if(top -> left) q.push(top->left); 28 | if(top -> right) q.push(top->right); 29 | } 30 | } 31 | 32 | } 33 | return ans; 34 | } 35 | -------------------------------------------------------------------------------- /Strings/factorial_of_large_numbers.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers2508/1# 2 | // since large numbers' factorial cannot be stored in any data type and there will be an overflow rather 3 | // so we store every element of factorial as a single element of array and later print it 4 | vector factorial(int n){ 5 | // the solution is basically based on the multiplication which we used to do primary school 6 | vector vec; 7 | vec.push_back(1); 8 | 9 | for(int i=n; i>1; i--) 10 | { 11 | int ans=1; 12 | int carry=0; 13 | int len=vec.size(),temp; 14 | for(int j=0; j &s) 6 | { 7 | if(root == NULL) return; 8 | adding_elements_of_tree1(root->left, s); 9 | s.insert(root->data); 10 | adding_elements_of_tree1(root->right, s); 11 | } 12 | 13 | void tree2_traversal(Node* root, unordered_set &s, vector &common) 14 | { 15 | if(root == NULL) return; 16 | tree2_traversal(root->left, s, common); 17 | if(s.find(root->data) != s.end()) 18 | { 19 | common.push_back(root->data); 20 | } 21 | tree2_traversal(root->right, s, common); 22 | } 23 | 24 | vector findCommon(Node *root1, Node *root2) 25 | { 26 | unordered_set s; 27 | adding_elements_of_tree1(root1, s); 28 | vector common; 29 | tree2_traversal(root2, s, common); 30 | return common; 31 | } 32 | -------------------------------------------------------------------------------- /Codeforces/A-pizzaForces.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://codeforces.com/contest/1555/problem/A 2 | // logic: 3 | // 1. time taken to make one small slice = 15/6 = 2.5 4 | // medium slice = 20/8 = 2.5 5 | // large slice = 25/10 = 2.5 6 | // that means time taken by each slice is equivalent for all sizes 7 | // 2. ow we want a number extremely closest to n 8 | // so that koi extra slices mate time na apvo pde 9 | // and magic is that every even number will always be fitted into that equation 10 | // because we have 6s + 8m + 10 l 11 | // and we want this number to be extremely closest to n 12 | // since all even numbers are valid and will fir into above equation 13 | // and in case that's a odd number, we have to reach to exactly next even number 14 | 15 | 16 | #include 17 | using namespace std; 18 | 19 | int main() 20 | { 21 | long int t; 22 | cin>>t; 23 | for(int i=0; i>n; 27 | if(n <= 6) ans = 15; 28 | else if(n % 2 != 0) ans = 2.5 * (n+1); 29 | else ans = 2.5 * n; 30 | cout< 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | long int t; 11 | cin>>t; 12 | for(int i=0; i>n; 16 | long int a[n], b[n]; 17 | bool check = false; 18 | bool ans = true; 19 | long int diff; 20 | 21 | for(int j=0; j>a[j]; 24 | } 25 | for(int j=0; j>b[j]; 28 | } 29 | for(int j=0; j0) 32 | { 33 | // first different element 34 | check = true; 35 | diff = b[j]-a[j]; 36 | continue; 37 | } 38 | if((b[j] - a[j] < 0) || (check == true && b[j]-a[j] != diff && b[j]-a[j] != 0) || (j != 0 && check == true && b[j]-a[j] != 0 && (b[j]-a[j] != b[j-1]-a[j-1]))) 39 | { 40 | ans = false; 41 | // cout< printFirstNegativeInteger(long long int arr[], long long int n, long long int k) 10 | { 11 | deque dq; 12 | vector vec; 13 | for(int i=0; i AllPossibleStrings(string s) 17 | { 18 | vector ans; 19 | int len = s.length(); 20 | int subset = pow(2, len); 21 | 22 | for(int i=0; i= 1) ans.push_back(str); 30 | } 31 | sort(ans.begin(), ans.end()); 32 | return ans; 33 | } 34 | -------------------------------------------------------------------------------- /Hashing/second_most_repeated_string_in_a_subsequence.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/second-most-repeated-string-in-a-sequence0534/1# 2 | string secFrequent (string arr[], int n) 3 | { 4 | unordered_map mp; 5 | int max1=0, max2=0; 6 | string str1="", str2=""; 7 | // there are 3 possible cases: 8 | // 1. mp[arr[i]] > max1 as well mp[arr[i]] > max2 -> max2=max1, max1=cmp[arr[i]] 9 | // 2. mp[arr[i]] > max2 but mp[arr[i]] < max1 -> max2=mp[arr[i]] 10 | // also we use string variables to store the answers alongwith 11 | for(int i=0; i max1) 15 | { 16 | if(str1 != arr[i]) 17 | { 18 | max2 = max1; 19 | str2 = str1; 20 | } 21 | max1 = mp[arr[i]]; 22 | str1 = arr[i]; 23 | } 24 | else if(mp[arr[i]] > max2 && mp[arr[i]] <= max1 && str1 != arr[i]) 25 | { 26 | max2 = mp[arr[i]]; 27 | str2 = arr[i]; 28 | } 29 | } 30 | return str2; 31 | } 32 | -------------------------------------------------------------------------------- /Arrays/longest_substring_with_at_most_k_distinct_characters.cpp: -------------------------------------------------------------------------------- 1 | string longestSubstringWuthAtmostKDistinct(string s, int k) { 2 | int size = s.length(); 3 | int start = 0, end = 0; 4 | int len = 0, ans = 0; 5 | unordered_map mp; 6 | 7 | while(end < size) 8 | { 9 | if(mp[s[end]] == 0) // distinct 10 | { 11 | k--; 12 | } 13 | 14 | if(k >= 0) 15 | { 16 | len++; 17 | mp[s[end++]]; 18 | ans = max(ans, len); 19 | } 20 | 21 | else 22 | { 23 | mp[s[end]]++; 24 | while(k < 0) 25 | { 26 | if(mp[s[start]] == 1) 27 | { 28 | k++; 29 | } 30 | mp[s[start]]--; 31 | start++; 32 | len = end - start + 1; 33 | } 34 | } 35 | end++; 36 | } 37 | if(ans != 0) { 38 | return s.substr(start, end - start + 1); 39 | } 40 | return ""; 41 | } 42 | -------------------------------------------------------------------------------- /Binary Search Tree/brothers_from_different_roots.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/brothers-from-different-root/1 2 | // method: we can store elements of one the tree in a set and then 3 | // we can traverse second bst and check if sum-root->data is existing in set or not 4 | 5 | void storing_tree1_in_set(Node* root, unordered_set &s){ 6 | 7 | if(root == NULL) return; 8 | // inorder traversal 9 | storing_tree1_in_set(root->left, s); 10 | s.insert(root->data); 11 | storing_tree1_in_set(root->right, s); 12 | } 13 | 14 | void find_element_from_tree2(Node* root, unordered_set &s, int &count, int sum){ 15 | 16 | if(root == NULL) return; 17 | 18 | find_element_from_tree2(root->left, s, count, sum); 19 | if(s.find(sum - root->data) != s.end()) count++; 20 | find_element_from_tree2(root->right, s, count, sum); 21 | } 22 | 23 | int countPairs(Node* root1, Node* root2, int sum) 24 | { 25 | unordered_set s; 26 | storing_tree1_in_set(root1, s); 27 | int count=0; 28 | find_element_from_tree2(root2, s, count, sum); 29 | return count; 30 | } 31 | -------------------------------------------------------------------------------- /Arrays/subarray_with_given_sum.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1/?category[]=sliding-window# 2 | // window sliding technique 3 | vector subarraySum(int arr[], int n, int s) 4 | { 5 | // using window sliding technique 6 | long long int sum=arr[0],start; 7 | vector ans; 8 | start=0; 9 | 10 | for(int i=1; i<=n; i++) 11 | { 12 | 13 | while(sum > s && start < i-1) 14 | { 15 | sum-=arr[start]; // if sum is greater than the required sum than we decrement the starting elements 16 | start++; 17 | } 18 | if(sum == s) // if sum = required sum than returning the function back 19 | { 20 | ans.push_back(start+1); 21 | ans.push_back(i); 22 | return ans; 23 | 24 | } 25 | if(i < n) // if iterator has not reached to last element that expanding the window by adding new elements 26 | { 27 | sum+=arr[i]; 28 | } 29 | } 30 | ans.push_back(-1); 31 | return ans; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Codechef/total_correct_submissions.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://www.codechef.com/START5B/problems/TOTCRT/ 2 | #include 3 | using namespace std; 4 | 5 | bool cmp(pair& a, 6 | pair& b) 7 | { 8 | return a.second < b.second; 9 | } 10 | 11 | void sort(unordered_map& M) 12 | { 13 | 14 | // Declare vector of pairs 15 | vector > A; 16 | 17 | // Copy key-value pair from Map 18 | // to vector of pairs 19 | for (auto& it : M) { 20 | A.push_back(it); 21 | } 22 | 23 | // Sort using comparator function 24 | sort(A.begin(), A.end(), cmp); 25 | 26 | // Print the sorted value 27 | for (auto& it : A) { 28 | 29 | cout << it.second << " " ; 30 | } 31 | } 32 | int main() 33 | { 34 | long int t; 35 | cin>>t; 36 | for(int i=0; i mp; 40 | cin>>n; 41 | for(int j=0; j<3*n; j++) 42 | { 43 | string s; 44 | cin>>s; 45 | long int value; 46 | cin>>value; 47 | mp[s]+=value; 48 | } 49 | sort(mp); 50 | cout<<"\n"; 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Arrays/substring_of_length_k_with_k-1_distinct_elements.cpp: -------------------------------------------------------------------------------- 1 | // problem link: https://practice.geeksforgeeks.org/problems/substrings-of-length-k-with-k-1-distinct-elements/1/?category[]=sliding-window&category[]=sliding-window&difficulty[]=1&page=1&sortBy=submissions&query=category[]sliding-windowdifficulty[]1page1sortBysubmissionscategory[]sliding-window# 2 | int countOfSubstrings(string str, int k) { 3 | // window sliding technique 4 | // count array method 5 | long int count[26]={0}, distinct=0,ans=0,n=str.length(); 6 | for(int i=0; i