├── .DS_Store ├── .gitignore ├── 01-Arrays ├── 01-Reverse_array_string.cpp ├── 02-Maximum_minimum_element_array.cpp ├── 03-Sort_Array_of_0_1_2.cpp ├── 04-Seprate_Negative_postive_array.cpp ├── 05-Union_Intersection_Array.cpp ├── 06-Largest Sum Contiguous Subarray.cpp ├── 07-Minimize_maximum_difference.cpp ├── 08-Duplicate_in_Array.cpp ├── 09-Maximum_Non-negative_subarray.cpp ├── 10-Factorial_Large_Numbers_using Array.cpp ├── 11-Merge_two_sorted array in o(1)_space.cpp ├── 12-Pick_from_both_side.cpp ├── 13-Merge_Overlapping_Intervals.cpp ├── 14-Minimum_Steps_Infinite_grid.cpp ├── 15-Minimum_Number_bulbs_to_activate.cpp ├── 16-Maximum_contigous_triplet_sum.cpp ├── 17-Maximum_Triplet_Sum.cpp ├── 18-Add_one_to_number.cpp ├── 19-Next_Permutation.cpp ├── 20-Partition_into_three_equal_parts.cpp ├── 21-Count_Pairs_with_given_sum.cpp ├── 22-Common_Element_in_array.cpp ├── 23-Rearrange_Array.cpp ├── 24-Subarray_with_0_Sum.cpp ├── 25-Maximum_Product_Subarray.cpp ├── 26-Longest_Consecutive_Subsequence.cpp ├── 27-find all elements that appear more than n:k times.cpp ├── 28-Maximum_profit.cpp ├── 29-Array_Subset_of_another_array.cpp ├── 30-Triplet_Sum_in_Array.cpp ├── 31-Maximum_Water_Trapped.cpp ├── 32-Choclate_Distribution.cpp ├── 33-Smallest_subarray_with_sum_greater_than_x.cpp ├── 34-Three_way_partition.cpp ├── 35-Minimum_swaps_for_k_together.cpp ├── 36-Median_of_two_sorted_Array.cpp ├── 37-Perfect_Peak_Array.cpp ├── 38-Kth_Row_Pascal_Triangle.cpp ├── 39-Longest_Number.cpp ├── 40-First_missing_integer.cpp ├── 41-Maximum_Gap.cpp ├── 42-Maximum_Unsorted_Subarray.cpp ├── 43-Repeat_missing_number_array.cpp ├── 44-RepeatNumber.cpp ├── 45-Wave_Array.cpp ├── 46-Primes.cpp ├── 47-Subarray_with_given_sum.cpp ├── 48-Maximum_Sum_of_Longest_increasing_Subsequence.cpp ├── 49-Maximum_Sum_so_no_three_elements_consecutive.cpp └── 50_Minimum_Number_of_jumps.cpp ├── 02- Matrix ├── 01-Anti Diagonals.cpp ├── 02-Spirally_traversing_matrix.cpp ├── 03-Find_Element_in_Matrix.cpp ├── 04-Row_with_max_1s.cpp ├── 05-Set_Matrix_Zeros.cpp ├── 06-Rotate_Matrix_90_degree_clockwise.cpp ├── 07-Sorted_Matrix.cpp ├── 08-Common_Elements_in_all_rows_of_matrix.cpp └── 09-Find_in_row_column_sorted_matrix.cpp ├── 03-Strings ├── 01-Palindrome_check.cpp ├── 02-Duplicate_in_string.cpp ├── 03-Strings_rotation_each_other.cpp ├── 04-Count_and_Say.cpp ├── 05-KMP_Substring_Search.cpp ├── 06-Longest_Pallindromic_Substring.cpp ├── 07-Print_all_subsequence_strings.cpp ├── 08-Permutations_of_given_string.cpp ├── 09-Split_Binary_String.cpp ├── 10-Palindrome_String.cpp ├── 11-Vowels_Consonants_substring.cpp ├── 12-Remove_Consecutive_Characters.cpp ├── 13-Longest_Common_Prefix.cpp ├── 14-Minimum_character_added_in_Front_to_make_sting_pallindromic.cpp ├── 15-Covert_to_pallindrome.cpp ├── 16-Reverse_the strings.cpp ├── 17-length_of_last_word.cpp ├── 18-Edit_Distance.cpp ├── 19-Valid_Parenthesis.cpp ├── 20-Rabin_Carp_Algorithm_Pattern_Searching.cpp ├── 21-Mobile_keypad_sequence.cpp ├── 22-Generate_all_valid_IP_address.cpp ├── 23-Atoi.cpp ├── 24-Compare_Version_Number.cpp ├── 25-Integer_to_Roman.cpp ├── 26-Roman_to_Integer.cpp ├── 27-Add_Binary_Strings.cpp ├── 28-Count_Reversal.cpp ├── 29-Minimum_flips_to_make_binary_alternative.cpp ├── 30-second_most_repeated_word_sequence.cpp ├── 31-Minimum_swaps_for_bracket_balancing.cpp ├── 32-Smallest_window_contains_all_characters_string_itself.cpp ├── 33-Print_Anagrams_Together.cpp ├── 34-Remove_Consecutive_duplicate_characters.cpp ├── 35-Isomorphic_string.cpp └── 36-Duplicate_Letter.cpp ├── 04-Sorting and Searching ├── 01-First_last_occurence_of_x.cpp ├── 02-Search_Rotated_Sorted_Array.cpp ├── 03-Square_root_of_number.cpp ├── 04-Find_middle_element.cpp ├── 05-Missing_duplicate_number.cpp ├── 06-find_pair_with_given_difference.cpp ├── 07-maximum_sum_such_that_no_2_elements_are_adjacent.cpp ├── 08-Count_triplet_with_sum_smaller_x.cpp ├── 09-Majority_Element.cpp ├── 10-Merge_two_sorted_arrays.cpp ├── 11-Subarray_with_0_sum.cpp ├── 12-Product_array_puzzle.cpp ├── 13-Sort_by_Set_Bit_Count.cpp ├── 14-Min_swaps_to_make_array_sorted.py ├── 15-Search_in_Bitonic_Array.cpp ├── 16-Smallest_factorial_number.cpp ├── 17-Selection_sort_Algorithm.cpp ├── 18-Bubble_sort_algorithm.cpp ├── 19-Insertion_Sort.cpp ├── 20-Merge_Sort_Algorit.cpp └── 21-Quick_Sort_Algorithm.cpp ├── 05-Linked List ├── 01-Intro_Linked_list.cpp ├── 02-Insertion_at_specific_position_linked_list.cpp ├── 03-Delete_nth_node.cpp ├── 04-Length_linked_list.cpp ├── 05-Search_element_linked_list.cpp ├── 06-Detect_loop.cpp ├── 07-Reverse_a_linked_list.cpp ├── 08-Reverse_in_groups_ given_size.cpp ├── 09-Delete_loop_in_linked_list.cpp ├── 10-Remove_Duplicate_from_sorted_list.cpp ├── 11-Remove_duplicate_from_unsorted_list.cpp ├── 12-Move_last_node_front.cpp ├── 13-Intersection_two_sorted_linked_list.cpp ├── 14-Middle_element_linked_list.cpp ├── 15-Merge_sort_in_linked_list.cpp ├── 16-Check_Pallindrome.cpp ├── 17-Sort_binary_linked_list.cpp ├── 18-Partition_list.cpp ├── 19-Insertion_Sort.cpp ├── 20-Delete_node_circular_linked_list.cpp ├── 21-Revers_doubly_linked_list.cpp ├── 22-pairs_with_given_sum_doubly_linkedlist.cpp ├── 23-Add_two_numbers_as_list.cpp └── 24-Clone_Linked_List.cpp ├── 06-Stack ├── 01-Stack_Implementation_using_array.cpp ├── 02-Implement stack_using_linkedList.cpp ├── 03-Balanced Parantheses.cpp ├── 04-Find_middle_element_of_stack.cpp ├── 05-Implement_two_stacks_in_array.cpp ├── 06-Reverse_string_using_stack.cpp ├── 07-Minimum_element_from_stack.cpp ├── 08-Next_greater_element.cpp ├── 09-Evaluation_postfix_expression.cpp ├── 10-Reverse_stack_using_recursion.cpp ├── 11-Sort_a_Stack.cpp ├── 12-Find_maximum_Area_of_histogram.cpp ├── 13-Longest_valid_substring.cpp ├── 14-expression_contain_redundant_brackets.cpp ├── 15-Implement_kstacks_from_one_array.cpp └── 16-Nearest_Smaller_Element.cpp ├── 07-Queue ├── 01-Implementation_of_queue_using_array.cpp ├── 02-Stack_using_two_queues.cpp ├── 03-Implement_Queue_using_Linked_List.cpp ├── 04-Implement_Deque_as_Stack.cpp ├── 05-Implement_DEQUEUE_asqueue.cpp ├── 06-Implement_Queue_using_Stack.cpp ├── 07-Circular_Queue.cpp ├── 08-Reverse_a_queue.cpp ├── 09-Reverse_first_k_elements_of_Queue.cpp ├── 10-Interleaving_queue.cpp └── 11-Maximum_of_subarray_of_size_k.cpp ├── 08-Binary Trees ├── 01-Insertion_of_node_in_binary_tree.cpp ├── 02-Height_of_binary_tree.cpp ├── 03-Level_order_Traversal_in_binary_tree.cpp ├── 04-Reverse_level_order_traversal.cpp ├── 05-diameter_of_tree.cpp ├── 06-Create_mirror_of_given_tree.cpp ├── 07-Inorder_Traversal_of_tree.cpp ├── 08-PreOrder_Traversal_of_Tree_recursive_iterative.cpp ├── 09-PostOrder_Traversal_Recursive_Iterative.cpp ├── 10-Left_view_of_tree.cpp ├── 11-Right_view_of_tree.cpp ├── 12-Top_View_of_Tree.cpp ├── 13-Bottom_View_of_tree.cpp ├── 14-Zig_zag_Traversal_of_Tree.cpp ├── 15-Check_if_binary_tree_is_balanced.cpp ├── 16-Diagonal_View_of_binaryTree.cpp ├── 17-Sum_Tree.cpp ├── 18-LCA_of_Binary_Tree.cpp ├── 19-Minimum_distance_between_two_nodes.cpp ├── 20-Invert_Binary_Tree.cpp ├── 21-check_binary_tree_are_mirror_of_each_other.cpp ├── 22-Print_all_nodes_at_k_distance_from_given_node.cpp ├── 23-Check_if_two_binary_tree_is_subtree_of_another.cpp └── 24-Sum_to_leaf_numbers.cpp ├── 09-Binary Search Trees ├── 01-Insertion_of_nodes_in_BST.cpp ├── 02-Search_Key_in_BST.cpp ├── 03-Minimum_and_Maximum_Elemet_in_BST.cpp ├── 04-Delete_Node_inBST.cpp ├── 05-Check_for_BST.cpp ├── 06-Inorder_Successor_of_the_Node.cpp ├── 07-LCA_in_a_BST.cpp ├── 08-Binary_Tree_to_BST_Conversion.cpp ├── 09-Convert_BST_to_Balanced_Binary_Search_Tree.cpp ├── 10-Merge_two_binary_search_Trees.cpp ├── 11-kth_Largest_element_in_BST.cpp ├── 12-Kth_Smallest_Element_in+BST.cpp ├── 13-Find_Largest_Binary_Search_Tree_in_Binary_Tree.cpp ├── 14-Count_BST_that_lie_in_given_range.cpp ├── 15-Restore_Binary_Search_Tree.cpp └── Screenshot 2022-02-04 at 3.24.50 PM.png ├── 10-Heaps ├── 01-Building_heap_from_Array.cpp ├── 02-Heap_Sort_Algorithm.cpp ├── 03-Find_K_Largest_Elements_in_Array.cpp ├── 04-Merge_k_sorted_List.cpp ├── 05-Check_binary_Tree_is_aHeap_or_not.cpp ├── 06-Convert_BST_to_Min_HEAP.cpp ├── 07-Convert_MinHeap_to_MaxHeap.cpp ├── 08-Merge_two_MaxHeaps.cpp └── 09-K_most_frequent_elements_in_array.cpp ├── 11-Graphs ├── 01-Adjacency_LIst_Representation_of_Graph.cpp ├── 02-BFS_Traversal_of_GRAPH.cpp ├── 03-DFS_Traversal_of_Graph.cpp ├── 04-Check_cycle_in_Directed_Graph.cpp ├── 05-Check_cycle_in_Undirected_Graph.cpp ├── 06-Steps_by_Knight.cpp ├── 07-Flood_Fill.cpp ├── 08-Clone_a_Graph.cpp ├── 09-Number_of_operations_to_make_network_connected.cpp ├── 10-Topological_Sort.cpp ├── 11-Possible_to_finish_all_task.cpp ├── 12-Find_number_of_islands.cpp ├── 13-Disjoint_set_UNION_by_RANK_and_Path_Compression.cpp ├── 14-Kruskal's_Minimum_Spannig_Tree_Algorithm.cpp ├── 15-Check_cycle_in_undirectedGraph_using_DisjointSet.cpp ├── 16-Prim's_Minimum_Spanning_Tree.cpp ├── 17-Dijkstra_Algorithm.cpp ├── 18-Minimum_swaps_required_to_sort_array.cpp ├── 19-Strongly_Connected_components_in_Graph.cpp ├── 20-Euler_Graph.cpp ├── 21-Snake_Ladder_Problem.cpp └── NoFriendsinSameTeam.cpp ├── 12-BackTracking ├── 01-Rat_in_Maze.cpp ├── 02-Rat_in_Maze-II.cpp ├── 03-NQueenProblem.cpp ├── 04-Sodoku_Solver.cpp ├── 05-M_Coloring_Problem.cpp └── 06-Pallindromic_Partitioning.cpp ├── 13-Dynamic Programming ├── 01-Basic_Fibonaci_Example_to_understand_DP.cpp ├── 02-0:1_Knapsack.cpp ├── 03-SubsetSum_recursion_memoization_topDown.cpp ├── 04-Equal_Partition.cpp ├── 05-Count_all_subset_with_EqualSum.cpp ├── 06-Minimum_Sum_Subset_difference.cpp ├── 07-Count_subset_with_given_difference.cpp ├── 08-Unbounded_KnapSack_Basic.cpp ├── 09-Rod_Cutting_Problem.cpp ├── 10-Coin_Change_1.cpp ├── 11-Minimum_number_of_coins_to_given_Sum.cpp ├── 12-Longest_Common_Subsequrnce.cpp ├── 13-Longest_Common_Substring.cpp ├── 14-Print_Longest_Common_Subsequence.cpp ├── 15-Shortest_Common_SuperSequemce.cpp ├── 16-Min_Insertion_deletion_to_make_another_string.cpp ├── 17-Longest_Pallindromic_Subsequence.cpp ├── 18-Minimimum_number_insertions_to_make_pallindrome.cpp ├── 19-Matrix_Chain_Multiplication.cpp ├── 20-Pallindromic_Partitioning.cpp ├── 21-Edit_Distance.cpp ├── 22-Egg_Dropping.cpp ├── 23-Binomial_Coefficient.cpp ├── 24-Friend_Pair_Problem.cpp ├── 25-Longest_Repeating_Subsequence.cpp ├── 26-Longest_Increasing_Subsequence.cpp └── 27-Word_Break.cpp └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshay-varshney/Data-Strcutures-and-Algorithms-Questions/173b57e23ef94aceeaa8079c73e9bf315167abb2/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /01-Arrays/01-Reverse_array_string.cpp: -------------------------------------------------------------------------------- 1 | //Array: program to reverse an array 2 | //Q. https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/# 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Method1: Recurisve way to swap array 9 | void recursive_reversed(int arr[], int start, int end){ 10 | if(start>=end){ 11 | return; 12 | } 13 | swap(arr[start],arr[end]); 14 | recursive_reversed(arr, start+1, end-1); 15 | } 16 | 17 | // Method2: Generalizing the function for both the string and array 18 | template 19 | t reversed(t value, int start, int end){ 20 | while(start<=end){ 21 | swap(value[start], value[end]); 22 | start++; 23 | end--; 24 | } 25 | return value; 26 | } 27 | int main() { 28 | cout<<"Enter the size of the array: "; 29 | int n; 30 | cin>>n; 31 | int arr[n]; 32 | int temp; 33 | for(int i=0;i>temp; 36 | arr[i]=temp; 37 | } 38 | int start=0; 39 | int end=n-1; 40 | 41 | recursive_reversed(arr, start, end); 42 | for(int i=0;i>n; 47 | cout<<"Enter the string: "; 48 | std::string name; 49 | cin>>name; 50 | std::cout< 6 | 7 | using namespace std; 8 | 9 | // Seprate the numbers 10 | int seprate(int arr[], int n){ 11 | if (n<=0) return -1; 12 | if(n==1) return 0; 13 | int start=0, mid=n-1; 14 | 15 | while(start<=mid ){ 16 | if(arr[start]>0 && arr[mid]>0){ 17 | mid--; 18 | } 19 | else if(arr[start]<0 && arr[mid]<0){ 20 | start++; 21 | 22 | } 23 | else if(arr[start]>0 && arr[mid]<0){ 24 | swap(arr[start],arr[mid]); 25 | start++; 26 | mid--; 27 | } 28 | else{ 29 | start++; 30 | mid--; 31 | } 32 | } 33 | return 0; 34 | } 35 | 36 | int main(){ 37 | int arr[]={-1,2,3,4,-6,-4,-11,13}; 38 | int n=sizeof(arr)/sizeof(arr[0]); 39 | seprate(arr, n); 40 | for(int i=0;i 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | // Uninon of Array using set 12 | int _union(int arr1[], int n1, int arr2[], int n2 ){ 13 | set s1; 14 | for(int i=0;i m1; 31 | pair p1; 32 | for(int i=0;i 7 | 8 | using namespace std; 9 | 10 | // Kadane’s Algorithm 11 | int maximum_subarray(int arr[], int n){ 12 | if (n<=0) return -1; 13 | int max_sum=INT_MIN; 14 | int summed=0; 15 | for(int i=0;i 5 | 6 | using namespace std; 7 | 8 | // Modified Kadane’s Algorithm 9 | int maximum_subarray(int arr[], int n, int k){ 10 | sort(arr,arr+n); 11 | 12 | if (n<=0) return -1; 13 | int maxi=arr[n-1]-k; 14 | int mini=arr[0]+k; 15 | int val=arr[n-1]-arr[0]; 16 | int x,y; 17 | for(int i=0;i 5 | #include 6 | 7 | using namespace std; 8 | 9 | // Method 1: If the array contains any element then use this one 10 | // Time: O(n) and Space: O(n) 11 | int duplicate_num(int arr[], int n){ 12 | unordered_map m1; 13 | for(int i=0;i 5 | #include 6 | 7 | using namespace std; 8 | 9 | vector maximu_subarray(int arr[], int n){ 10 | int start=0, mid=0,val1=0,val2=0; 11 | double ans=-1; 12 | double su=0; 13 | while(mid=0){ 15 | su+=arr[mid]; 16 | mid++; 17 | } 18 | else if(arr[mid]<0){ 19 | if(su>=ans){ 20 | val1=start; 21 | val2=mid; 22 | ans=su; 23 | } 24 | start=mid+1; 25 | mid+=1; 26 | su=0; 27 | } 28 | } 29 | if(su>ans){ 30 | val1=start; 31 | val2=mid; 32 | } 33 | vector v1; 34 | for(int i=val1;i v2; 44 | v2=maximu_subarray(arr, n); 45 | for(auto it:v2){ 46 | cout< 6 | 7 | using namespace std; 8 | 9 | // This is not a very efficient way to do this. Efficient way is to use linked list. 10 | int _multiply(int arr[], int ind, int val){ 11 | int _carry=0; 12 | for(int i=0;i=0;i--){ 35 | ans+=to_string(arr[i]); 36 | } 37 | return ans; 38 | } 39 | 40 | int main(){ 41 | cout<<_factorial(105)< 6 | 7 | using namespace std; 8 | // Method : Here we have to focus on eliminating the pair of size (n-B) which have minimum value. The remaining contigous elemnet will have a maximum sum 9 | int max_sum(int arr[], int n, int B){ 10 | int _sum=0; 11 | //overall sum of array 12 | for(int i=0;i 5 | #include 6 | 7 | using namespace std; 8 | 9 | // The total Time complexity is O(nlogn) and space complexity is O(n) 10 | vector> merge_overlap(vector>& values){ 11 | int n=values.size(); 12 | // Sort the vector 13 | sort(values.begin(),values.end()); 14 | vector> final; 15 | int start=0, end=0; 16 | start=values[0][0]; 17 | end=values[0][1]; 18 | // comparing the end of current with the start of the next if end becomes greater than replace end otherwise push back in answer and change start and end values to current value 19 | 20 | for(int i=1;i=values[i][0]){ 22 | end=max(end,values[i][1]); 23 | } 24 | else{ 25 | final.push_back({start,end}); 26 | start=values[i][0]; 27 | end=values[i][1]; 28 | } 29 | } 30 | final.push_back({start,end}); 31 | return final; 32 | } 33 | 34 | int main(){ 35 | vector> v1={{1,3},{2,6},{8,10},{15,18}}; 36 | vector> ans= merge_overlap(v1); 37 | for(int i=0;i 5 | #include 6 | 7 | using namespace std; 8 | 9 | //minimum number of steps to reach the end of the array 10 | int steps(vector &A, vector &B){ 11 | int steps=0; 12 | int first, second; 13 | for(int i=0;i v1={1,-2,4,5}; 23 | vector v2={1,1,3,2}; 24 | cout<<"Minimum Steps: "< 15 | #include 16 | 17 | using namespace std; 18 | 19 | 20 | int steps(vector &A, int B){ 21 | int bulb=0; 22 | bool flag=false; 23 | int n=A.size(); 24 | int val; 25 | int i=0; 26 | while(i=i-B+1){ 30 | if(A[j]==1){ 31 | flag=true; 32 | val=j; 33 | bulb++; 34 | i=val+B; 35 | break; 36 | } 37 | j--; 38 | } 39 | if(flag==false){ 40 | return -1; 41 | } 42 | } 43 | return bulb; 44 | } 45 | 46 | int main(){ 47 | vector v1={0, 0, 1, 1, 1, 0, 0, 1}; 48 | int B=3; 49 | cout< 4 | #include 5 | 6 | using namespace std; 7 | 8 | int max_triplet(vector v1){ 9 | int i=0; 10 | int n=v1.size(); 11 | int j=i+2; 12 | int max_sum=INT_MIN; 13 | int _summ=0; 14 | if (n<3) return -1; 15 | _summ+=(v1[i]+v1[i+1]+v1[j]); 16 | max_sum=max(max_sum,_summ); 17 | 18 | j++; 19 | while(j v1={2, 5, 3, 1, 4, 9}; 37 | cout< 8 | #include 9 | 10 | using namespace std; 11 | 12 | // Method 1: Finding maximum in left and right side of the array. 13 | // Time Complexity: O(n^2) and space is O(1) 14 | int max_sum(vector & A){ 15 | int ans=0; 16 | int n=A.size(); 17 | int max_1=INT_MIN; 18 | int max_2=INT_MIN; 19 | for(int i=1;iA[i]){ 29 | max_2=max(max_2,A[j]); 30 | } 31 | } 32 | if(max_1 && max_2){ 33 | ans=max(ans,A[i]+max_1+max_2); 34 | } 35 | } 36 | return ans; 37 | } 38 | 39 | 40 | int main(){ 41 | vector v1={2, 5, 3, 1, 4, 9}; 42 | cout< 8 | #include 9 | 10 | using namespace std; 11 | 12 | // Method 13 | vector plusOne(vector &A) { 14 | // Eliminate 0 from start if present any 15 | reverse(A.begin(), A.end()); 16 | for(int i=A.size()-1;i>=0;i--){ 17 | if(A[i]==0) A.pop_back(); 18 | else break; 19 | } 20 | reverse(A.begin(), A.end()); 21 | //count all the 9's in the array 22 | int n=A.size(); 23 | int count=0; 24 | for(int i=0;i v1; 30 | // If count is same as size of array then all values should be 0 except first one. 31 | if(count==n){ 32 | v1.push_back(1); 33 | for(int i=0;i=0;i--){ 38 | if(A[i]==9) A[i]=0; 39 | else{ 40 | A[i]++; 41 | break; 42 | } 43 | } 44 | } 45 | else A[n-1]++; 46 | return A; 47 | } 48 | // Time Complexity: O(n) and Space Complexity O(n) 49 | int main(){ 50 | vector v1={ 3, 0, 6, 4, 0}; 51 | vector v2; 52 | v2=plusOne(v1); 53 | for(auto it=v2.begin();it!=v2.end();it++){ 54 | cout<<*it<<" "; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /01-Arrays/19-Next_Permutation.cpp: -------------------------------------------------------------------------------- 1 | // Array: Find the next permutation 2 | // https://leetcode.com/problems/next-permutation/submissions/ 3 | 4 | // Input: nums = [3,2,1] 5 | //Output: [1,2,3] 6 | 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | // 3 steps: 1. Find the first point which is having decreasing value in a subarray. 12 | //2. swap this with the value greater than element in subarray. 13 | //3. sort the subarray 14 | vector next_permutation(vector &v1){ 15 | int n=v1.size(); 16 | if(n<=1) return v1; 17 | int val=n-2; 18 | while(val>=0 && v1[val]>= v1[val+1]){ 19 | val--; 20 | } 21 | if (val<0){ 22 | sort(v1.begin(),v1.end()); 23 | return v1; 24 | } 25 | for(int i=n-1;i>val;i--){ 26 | if(v1[i]>v1[val]){ 27 | swap(v1[i],v1[val]); 28 | break; 29 | } 30 | } 31 | sort(v1.begin()+val+1,v1.end()); 32 | return v1; 33 | } 34 | // time complexity: O(nlogn) 35 | //space O(1) 36 | 37 | int main(){ 38 | vector v1={1,2,3,2,1}; 39 | vector v2; 40 | v2=next_permutation(v1); 41 | for(auto it=v2.begin();it!=v2.end();it++){ 42 | cout<<*it<<" "; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /01-Arrays/21-Count_Pairs_with_given_sum.cpp: -------------------------------------------------------------------------------- 1 | // Array: Count pairs with given sum 2 | 3 | // https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1# 4 | /* 5 | Input: 6 | N = 4, K = 6 7 | arr[] = {1, 5, 7, 1} 8 | Output: 2 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | // Using Unordered map to store the count of the variable. 17 | int getpair_count(vector A,int n, int x){ 18 | unordered_map m1; 19 | for(int i=0;i::iterator it = m1.find(A[i]); 21 | if (it != m1.end()) { 22 | it->second++; 23 | } 24 | else { 25 | m1.insert(std::make_pair(A[i], 1)); 26 | } 27 | } 28 | int count=0; 29 | bool flag=false; 30 | for(int i=0;i::iterator it = m1.find(x-A[i]); 33 | 34 | if (it != m1.end()) { 35 | // If element is pointing to itself then decremenet the count by 1, as element cannot make pair with itself. 36 | if(A[i]==it->first){ 37 | it->second--; 38 | flag=true; 39 | } 40 | count+=it->second; 41 | } 42 | if(flag==true){ 43 | it->second++; 44 | } 45 | } 46 | return count/2; 47 | } 48 | // Time : O(n) and Space: O(n) 49 | 50 | int main(){ 51 | vector v1={1,1, 1, 1}; 52 | vector v2; 53 | cout< 13 | #include 14 | #include 15 | using namespace std; 16 | vector _common_element(vector A, vector B, vector C, int n1, int n2, int n3){ 17 | if(n1==0 || n2==0 || n3==0) return {}; 18 | int i=0,j=0, k=0; 19 | vector v; 20 | while(i0 && v[n-1]==A[i] ){ 25 | i++; 26 | j++; 27 | k++; 28 | continue; 29 | } 30 | v.push_back(A[i]); 31 | i++; 32 | j++; 33 | k++; 34 | } 35 | else if(A[i] v1={1, 5, 10, 20, 40, 80}; 44 | vector v2={6, 7, 20, 80, 100}; 45 | vector v3={3, 4, 15, 20, 30, 70, 80, 120}; 46 | 47 | vector v4; 48 | v4=_common_element(v1, v2, v3, v1.size(), v2.size(), v3.size()); 49 | for(auto it=v4.begin();it!=v4.end();it++){ 50 | cout<<*it<<" "; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /01-Arrays/23-Rearrange_Array.cpp: -------------------------------------------------------------------------------- 1 | // Array: Rearrange array in alternating positive & negative items with O(1) extra space 2 | 3 | // https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/ 4 | /* 5 | 6 | Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8} 7 | output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0} 8 | 9 | */ 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | void rearrange(vector &A){ 16 | int n=A.size(); 17 | int start=0; 18 | int mid=0; 19 | while(mid0){ 24 | if(A[mid]<0){ 25 | int temp=A[mid]; 26 | for(int j=mid;j>start;j--){ 27 | A[j]=A[j-1]; 28 | } 29 | A[start]=temp; 30 | } 31 | mid++; 32 | } 33 | } 34 | } 35 | else{ 36 | if(A[start]<0){ 37 | swap(A[start],A[start+1]); 38 | mid++; 39 | } 40 | } 41 | start++; 42 | } 43 | } 44 | // Time Complexity: O(nlogn) and Space: O(1) 45 | int main(){ 46 | vector v1={-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}; 47 | rearrange(v1); 48 | for(auto it=v1.begin();it!=v1.end();it++){ 49 | cout<<*it<<" "; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /01-Arrays/24-Subarray_with_0_Sum.cpp: -------------------------------------------------------------------------------- 1 | // Array: Subarray with 0 sum 2 | 3 | // https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1# 4 | /* 5 | 6 | Input: arr[] = {4 2 -3 1 6} 7 | output: True 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | bool subarray(vector &A){ 17 | unordered_map m1; 18 | int summed=0; 19 | int n=A.size(); 20 | for(int i=0;i::iterator iter=m1.find(summed); 23 | if (iter != m1.end() || summed==0){ 24 | return true; 25 | } 26 | else{ 27 | m1.insert(std::make_pair(summed, 1)); 28 | } 29 | } 30 | return false; 31 | } 32 | 33 | // Time Complexity: O(n) and Space: O(n) 34 | int main(){ 35 | vector v1={-21, 21, 30, -7, 45, 49, -26, 38, 4, 36, 19, -18, 19, -40, 23, -20, -17, 13}; 36 | cout< 6 | #include 7 | 8 | using namespace std; 9 | // Using Kadens Algorithm 10 | int max_product(vector &arr){ 11 | int n=arr.size(); 12 | int mini= arr[0]; 13 | int maxi = arr[0]; 14 | int prod = arr[0]; 15 | for (int i = 1; i < n; i++) { 16 | //if value of array is -ve that means that maxi and mini value interchanged 17 | if (arr[i] < 0) 18 | swap(maxi, mini); 19 | // These two keep track of maximum and minimum value in array all the time 20 | maxi = max(arr[i], maxi * arr[i]); 21 | mini= min(arr[i], mini* arr[i]); 22 | 23 | prod = max(prod, maxi); 24 | } 25 | return prod; 26 | } 27 | 28 | 29 | int main(){ 30 | vector v1={-2,4,6,2,4,-1,-9}; 31 | cout< 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | // Using Kadens Algorithm 18 | int longest_consecutive(vector &arr){ 19 | int n=arr.size(); 20 | if(n<=1) return 1; 21 | set s1; 22 | for(int i=0;i::iterator iter1=s1.begin(); 28 | auto it=iter1; 29 | it++; 30 | for(auto i=it;i!=s1.end();i++){ 31 | if(*i-*iter1==1){ 32 | count++; 33 | } 34 | else{ 35 | count=1; 36 | } 37 | iter1=i; 38 | longest_count=max(longest_count,count); 39 | } 40 | return longest_count; 41 | } 42 | // Time:O(n) and Space:O(n) 43 | 44 | int main(){ 45 | vector v1={2,6,1,9,4,5,3}; 46 | cout< 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | vector occurence(vector &arr, int k){ 11 | unordered_map m1; 12 | int n=arr.size(); 13 | for(int i=0;i::iterator iter1=m1.find(arr[i]); 15 | if(iter1!=m1.end()){ 16 | iter1->second++; 17 | } 18 | else{ 19 | m1.insert(std::make_pair(arr[i], 1)); 20 | } 21 | } 22 | vector ans; 23 | int val=n/k; 24 | for(auto it=m1.begin();it!=m1.end();it++){ 25 | if((it->second)>val){ 26 | ans.push_back(it->first); 27 | } 28 | } 29 | return ans; 30 | } 31 | //Time:O(n) and Space: O(n) 32 | 33 | int main(){ 34 | vector v1={3, 1, 2, 2, 1, 2, 3, 3}; 35 | int k=4; 36 | vector v11; 37 | v11=occurence(v1,k); 38 | for(auto i=v11.begin();i!=v11.end();i++){ 39 | cout<<*i<<" "; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /01-Arrays/28-Maximum_profit.cpp: -------------------------------------------------------------------------------- 1 | // Array: Maximum profit by buying and selling a share at most twice 2 | // https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-twice/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | int maximum_profit(vector A){ 9 | int n=A.size(); 10 | if (n<=1) return 0; 11 | int mini=A[0]; 12 | int mini2=A[1]; 13 | int ind1=0; 14 | int ind2=1; 15 | //finding the first and second minimum in array and capturing their indices 16 | for(int i=1;imini)] 21 | { 22 | mini2=mini; 23 | ind2=ind1; 24 | } 25 | mini=A[i]; 26 | ind1=i; 27 | } 28 | else if(A[i] v1={2, 30, 15, 10, 8, 25, 80}; 53 | cout< 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | std::string subset(vector &A, vector B){ 9 | int m=B.size(); 10 | int n=A.size(); 11 | unordered_map m1; 12 | for(int i=0;i::iterator iter=m1.find(B[i]); 17 | if(iter!=m1.end()){ 18 | continue; 19 | } 20 | else{ 21 | return "NO"; 22 | } 23 | } 24 | return "YES"; 25 | } 26 | //Time: O(n+m) and Space:O(n) 27 | 28 | int main(){ 29 | vector v1={11, 1, 13, 21, 3, 7}; 30 | vector v2={11, 3, 7, 1}; 31 | cout< 4 | #include 5 | 6 | using namespace std; 7 | 8 | bool triplet_sum(vector &A, int val){ 9 | int n=A.size(); 10 | if(n<3) return false; 11 | sort(A.begin(),A.end()); 12 | int mid,end; 13 | for(int i=0;i v1={1, 2, 4, 3, 6}; 28 | int x=10; 29 | cout< 12 | #include 13 | 14 | using namespace std; 15 | 16 | int minimum_difference(vector &A, int m){ 17 | int n=A.size(); 18 | if (n v1={7, 3, 2, 4, 9, 12, 56}; 34 | cout< 12 | #include 13 | 14 | using namespace std; 15 | 16 | int smallest_subaaray(vector &A, int x){ 17 | int n=A.size(); 18 | if(xx){ 26 | max_count=min(max_count,(k-i+1)); 27 | summed-=A[i]; 28 | i++; 29 | } 30 | else{ 31 | k++; 32 | summed+=A[k]; 33 | } 34 | } 35 | return max_count; 36 | } 37 | // Time: O(n) Space:O(1) 38 | 39 | int main(){ 40 | vector v1={1, 10, 5, 2, 7}; 41 | cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | void threeway(vector &A, int a, int b){ 10 | int start=0; 11 | int mid=0; 12 | int n=A.size(); 13 | int end=n-1; 14 | while(mid<=end){ 15 | if(A[mid]b){ 22 | swap(A[end], A[mid]); 23 | end--; 24 | } 25 | } 26 | } 27 | //Time: O(n) and Space: O(1) 28 | 29 | int main(){ 30 | vector v1={76, 8, 75, 22, 59, 96, 30, 38, 36}; 31 | int a=44; 32 | int b=62; 33 | threeway(v1, a, b); 34 | } 35 | -------------------------------------------------------------------------------- /01-Arrays/37-Perfect_Peak_Array.cpp: -------------------------------------------------------------------------------- 1 | // Array: Perfect Peak of Array 2 | // https://www.interviewbit.com/problems/perfect-peak-of-array/ 3 | /* 4 | Input>A = [5, 1, 4, 3, 6, 8, 10, 7, 9] 5 | O/p: 1 6 | */ 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | // Creating a Prefix array of maximum elements till now 13 | // Creating a suffix array of minimum element till now 14 | bool perfect_peak(vector &A){ 15 | int n=A.size(); 16 | vector Maxi(n); 17 | vector Mini(n); 18 | int maxi=INT_MIN; 19 | int mini=INT_MAX; 20 | for(int i=0;i=0;i--){ 25 | mini=min(mini,A[i]); 26 | Mini[i]=mini; 27 | } 28 | for(int i=1;i<=n-2;i++){ 29 | if(Maxi[i-1] v1={5,4,3,1,6,1,7,10}; 40 | cout<k=3 5 | 1 6 | 1 1 7 | 1 2 1 8 | 1 3 3 1 9 | O/p: 1 3 3 1 10 | */ 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | vector pascal_traingle(int n){ 17 | vector result; 18 | vector temp; 19 | if (n<0) return {}; 20 | result.push_back(1); 21 | if (n==0) return result; 22 | result.push_back(1); 23 | if(n==1) return result; 24 | temp=result; 25 | result={}; 26 | for(int i=1;i v1={5,4,3,1,6,1,7,10}; 41 | vector v2; 42 | v2=pascal_traingle(5); 43 | for(auto it=v2.begin();it!=v2.end();it++){ 44 | cout<<*it< 8 | #include 9 | 10 | using namespace std; 11 | bool comparision(string a, string b){ 12 | string ab=a.append(b); //creating a AB string 13 | string ba=b.append(a); 14 | return ab.compare(ba)>0 ?1:0; // compare on basis of ascii value if ab>ba then it will return greater than 0 15 | } 16 | 17 | string largest_num(vector &arr){ 18 | int n=arr.size(); 19 | vector A; 20 | string value=""; 21 | int _count0=0; 22 | for(int i=0;i v1={472, 663, 964 }; 36 | cout< 9 | #include 10 | 11 | using namespace std; 12 | int first_poitive(vector &A){ 13 | int n=A.size(); 14 | int start=0; 15 | while(start0 && A[start]<=n){ 17 | if(A[start]==A[A[start]-1]){ 18 | start++; 19 | } 20 | else swap(A[start],A[A[start]-1]); 21 | } 22 | else start++; 23 | } 24 | for(int i=0;i v1={1,1,1}; 33 | cout<=i 8 | */ 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | // using suffix and prefix array. Prefix will store the minimum till now and suffix will store the maximum till now 15 | int maximum_gap(vector &A){ 16 | int n=A.size(); 17 | int start=0; 18 | int end=n-1; 19 | vector min_left(n); 20 | vector max_right(n); 21 | min_left[0]=A[0]; 22 | for(int i=1;i=0;i--){ 27 | max_right[i]=max(max_right[i+1],A[i]); 28 | } 29 | int i=0, j=0, max_diff=-1; 30 | while(i=0){ 32 | max_diff=max(max_diff,j-i); 33 | j++; 34 | } 35 | else i++; 36 | } 37 | return max_diff; 38 | } 39 | // Time: O(n) and Space: O(n) 40 | 41 | int main(){ 42 | vector v1={6,2,5,4,1,1,1,3}; 43 | cout<<"Maximum Gap: "<< maximum_gap(v1)< 9 | #include 10 | 11 | using namespace std; 12 | vector first_poitive(vector &A){ 13 | int n=A.size(); 14 | int start=0; 15 | vector ans={}; 16 | while(start0 && A[start]<=n){ 18 | if(A[start]==A[A[start]-1]){ 19 | start++; 20 | } 21 | else swap(A[start],A[A[start]-1]); 22 | } 23 | else start++; 24 | } 25 | for(int i=0;i v1={3, 1, 2, 5, 3}; 36 | vector v2; 37 | v2=first_poitive(v1); 38 | for(auto it=v2.begin();it!=v2.end();it++){ 39 | cout<<*it< 8 | #include 9 | 10 | 11 | using namespace std; 12 | 13 | vector wave(vector &A){ 14 | int n=A.size(); 15 | sort(A.begin(),A.end()); 16 | vector ans; 17 | int i=0; 18 | while(i & arr, int n) 32 | { 33 | // Traverse all even elements 34 | for (int i = 0; i < n; i+=2) 35 | { 36 | // If current even element is smaller than previous 37 | if (i>0 && arr[i-1] > arr[i] ) 38 | swap(arr[i], arr[i-1]); 39 | 40 | // If current even element is smaller than next 41 | if (i v1={6,4,3,1,2}; 50 | vector v2; 51 | v2=wave(v1); 52 | for(auto it=v2.begin();it!=v2.end();it++){ 53 | cout<<*it<<" "; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /01-Arrays/46-Primes.cpp: -------------------------------------------------------------------------------- 1 | // Array: Prime Numbers 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | vector primes(int A) { 9 | vector ans={}; 10 | if(A<2) return ans; 11 | for(int i=2;i<=A;i++){ 12 | int upper=sqrt(i); 13 | bool flag=false; 14 | for(int j=2;j<=upper;j++) 15 | { 16 | if(i%j==0) 17 | { 18 | flag=true; 19 | break; 20 | } 21 | else flag=false; 22 | } 23 | if(flag==false) ans.push_back(i); 24 | } 25 | return ans; 26 | } 27 | //Time: O(nlogn(n)) and Space:O(n) 28 | 29 | int main(){ 30 | vector v2; 31 | v2=primes(20); 32 | for(auto it=v2.begin();it!=v2.end();it++){ 33 | cout<<*it<<" "; 34 | } 35 | cout< 8 | #include 9 | 10 | using namespace std; 11 | 12 | //Time: O(n) and Space:O(1) 13 | vector givensum(vector &A, int req){ 14 | int summed=0; 15 | int n=A.size(); 16 | vector ans; 17 | int j=0; 18 | int i=0; 19 | while(ireq){ 27 | summed-=(A[i]+A[j]); 28 | j++; 29 | } 30 | else i++; 31 | } 32 | ans.push_back(-1); 33 | return ans; 34 | } 35 | 36 | int main(){ 37 | vector v1={1,2,3,4,5,6,7,8,9,10}; 38 | int value=15; 39 | vector v2; 40 | v2=givensum(v1, value); 41 | for(auto it=v2.begin();it!=v2.end();it++){ 42 | cout<<*it<<" "; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /01-Arrays/48-Maximum_Sum_of_Longest_increasing_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | // Array: Maximum Sum of Longest Increasing Subsequence 2 | //https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/ 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Method 1: By using another vector and storing the previous count of longest increasing Subsequence 10 | int longestIncreasingSubse(vector& A){ 11 | int n=A.size(); 12 | vector SubsequenceVal(n); 13 | for(int i=0;i A[j] && SubsequenceVal[i]< SubsequenceVal[j]+ A[i]) 19 | SubsequenceVal[i]= SubsequenceVal[j]+A[i]; 20 | } 21 | } 22 | int maxi= SubsequenceVal[0]; 23 | for(int i=1;i A= {1, 101, 2, 3, 100}; 33 | cout<<"Sum of Longest Increasing Subsequence is: "< 5 | #include 6 | /* 7 | sum[0] = arr[0] 8 | 9 | // Note : All elements are positive 10 | sum[1] = arr[0] + arr[1] 11 | 12 | // We have three cases 13 | // 1) Exclude arr[2], i.e., sum[2] = sum[1] 14 | // 2) Exclude arr[1], i.e., sum[2] = sum[0] + arr[2] 15 | // 3) Exclude arr[0], i.e., sum[2] = arr[1] + arr[2] 16 | sum[2] = max(sum[1], arr[0] + arr[2], arr[1] + arr[2]) 17 | 18 | In general, 19 | // We have three cases 20 | // 1) Exclude arr[i], i.e., sum[i] = sum[i-1] 21 | // 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i] 22 | // 3) Exclude arr[i-2], i.e., sum[i-3] + arr[i] + arr[i-1] 23 | sum[i] = max(sum[i-1], sum[i-2] + arr[i], 24 | sum[i-3] + arr[i] + arr[i-1]) 25 | */ 26 | using namespace std; 27 | 28 | 29 | int maxSum(vector& A, vector& Sum){ 30 | int n=A.size(); 31 | if(n>=1) 32 | Sum[0]=A[0]; 33 | if(n>=2) 34 | Sum[1]= A[0]+ A[1]; 35 | if(n>2) 36 | Sum[2] = max(Sum[1], max(A[1]+ A[2] , A[0] + A[2])); 37 | for(int i=3;i A= {100, 1000, 100, 1000, 1}; 46 | vector Sum(A.size()); 47 | cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | int minJumps(int arr[], int n) 10 | { 11 | if (n <= 1) 12 | return 0; 13 | if (arr[0] == 0) 14 | return -1; 15 | 16 | int maxReach = arr[0]; 17 | 18 | int step = arr[0]; 19 | int jump = 1; 20 | int i = 1; 21 | for (i = 1; i < n; i++) { 22 | // Check if we have reached the end of the array 23 | if (i == n - 1) 24 | return jump; 25 | 26 | // updating maxReach 27 | maxReach = max(maxReach, i + arr[i]); 28 | 29 | // we use a step to get to the current index 30 | step--; 31 | 32 | // If no further steps left 33 | if (step == 0) { 34 | // we must have used a jump 35 | jump++; 36 | 37 | // Check if the current index/position or lesser index 38 | // is the maximum reach point from the previous indexes 39 | if (i >= maxReach) 40 | return -1; 41 | 42 | // re-initialize the steps to the amount 43 | // of steps to reach maxReach from position i. 44 | step = maxReach - i; 45 | } 46 | } 47 | 48 | return -1; 49 | } 50 | 51 | 52 | int main() 53 | { 54 | int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; 55 | int size = sizeof(arr) / sizeof(int); 56 | cout < 5 | 1 2 3 6 | 4 5 6 7 | 7 8 9 8 | 9 | O/p: 10 | [ 11 | [1], 12 | [2, 4], 13 | [3, 5, 7], 14 | [6, 8], 15 | [9] 16 | ] 17 | */ 18 | #include 19 | #include 20 | 21 | using namespace std; 22 | 23 | vector> diagonal(vector> &A ){ 24 | int n=A.size(); 25 | vector> ans; 26 | vector temp; 27 | //upper triangle traversal 28 | for(int i=0;i=0){ 31 | temp.push_back(A[r][c]); 32 | r++; 33 | c--; 34 | } 35 | ans.push_back(temp); 36 | temp={}; 37 | } 38 | //lower triangle traversal 39 | for(int i=1;i> v1={{1,2,3},{4,5,6},{7,8,9}}; 55 | vector> v2; 56 | v2=diagonal(v1); 57 | for(auto i=0;i 8 | #include 9 | 10 | using namespace std; 11 | 12 | // Using Binary Search in Matrix 13 | bool searchMatrix(vector>& A, int val) 14 | { 15 | int n=A.size(); 16 | int m=A[0].size(); 17 | bool value=false; 18 | for(int i=0;ival) continue; 21 | else{ 22 | int start=0; 23 | int end=m; 24 | while(start<=end){ 25 | int mid=(start+end)/2; 26 | if(A[i][mid]==val) return true; 27 | else if(A[i][mid]>val) end=mid-1; 28 | else start=mid+1; 29 | } 30 | } 31 | } 32 | return value; 33 | } 34 | 35 | 36 | int main(){ 37 | vector> v1={{1,3,5,7},{10,11,16,20},{23,30,34,60}}; 38 | cout< 11 | #include 12 | 13 | using namespace std; 14 | 15 | // Using Binary Search in Matrix 16 | int Max_zero(vector>& A) 17 | { 18 | int n=A.size(); 19 | int m=A[0].size(); 20 | int val; 21 | int max_0=0; 22 | for(int i=0;imax_0){ 34 | max_0=m-start; 35 | val=i; 36 | } 37 | } 38 | } 39 | return val; 40 | } 41 | // Time: O(n*log(m)) and Space: O(1) 42 | 43 | 44 | int main(){ 45 | vector> v1={{0, 1, 1, 1},{0, 0, 1, 1},{1, 1, 1, 1},{0, 0, 0, 0}}; 46 | cout< 16 | #include 17 | 18 | using namespace std; 19 | 20 | void set_zero(vector> &A){ 21 | int n=A.size(); 22 | int m=A[0].size(); 23 | bool Column=false; 24 | bool Row=false; 25 | for(int i=0;i> v1={{1,0},{1, 1}}; 59 | set_zero(v1); 60 | for(auto it=0;it 16 | #include 17 | 18 | using namespace std; 19 | 20 | void Rotate_Matrix(vector> &A){ 21 | int n=A.size(); 22 | int m=A[0].size(); 23 | // Taking the transpose of the matrix 24 | for(int i=0;i> v1={{1,2},{3,4}}; 45 | Rotate_Matrix(v1); 46 | for(auto it=0;it 15 | #include 16 | 17 | using namespace std; 18 | 19 | vector> sortedArix(int n, vector> &A) { 20 | vector temp; 21 | for (int i = 0; i < n; i++){ 22 | for (int j = 0; j < n; j++){ 23 | temp.push_back(A[i][j]); 24 | } 25 | } 26 | std::sort(temp.begin(), temp.end()); 27 | int k=0; 28 | for (int i = 0; i < n; i++){ 29 | for (int j = 0; j < n; j++){ 30 | A[i][j] = temp[k++]; 31 | } 32 | } 33 | return A; 34 | } 35 | 36 | int main(){ 37 | vector> v1={{10,20,30,40},{15,25,35,45},{27,29,37,48},{32,33,39,50}}; 38 | vector> v2; 39 | v2=sortedArix(v1.size(), v1); 40 | for(auto it=0;it 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | vector common_element(vector> &A){ 18 | int n=A.size(); 19 | int m=A[0].size(); 20 | unordered_map m1; 21 | vector ans; 22 | for(int i=0;i::iterator iter=m1.find(A[i][j]); 28 | if(iter!=m1.end()){ 29 | if(iter->second == i){ 30 | iter->second=i+1; 31 | if(i==n-1 && iter->second== n){ 32 | ans.push_back(A[i][j]); 33 | } 34 | } 35 | } 36 | } 37 | } 38 | return ans; 39 | } 40 | //Time: O(m*n) and Space:O(m) 41 | 42 | int main(){ 43 | vector> v1={ 44 | {1, 2, 1, 4, 8}, 45 | {3, 7, 8, 5, 1}, 46 | {8, 7, 7, 3, 1}, 47 | {8, 1, 2, 7, 9}, 48 | }; 49 | vector v2; 50 | v2=common_element(v1); 51 | for(auto it=v2.begin();it!=v2.end();it++){ 52 | cout<<*it< 4 | #include 5 | 6 | using namespace std; 7 | 8 | //Time: O(nlogn(n)) and Space:O(1) 9 | int matSearch (vector> &A, int x){ 10 | int n=A.size(); 11 | int m=A[0].size(); 12 | for(int i=0;i=x && A[i][0]<=x){ 14 | int start=0; 15 | int end=m; 16 | while(start<=end){ 17 | int mid=(start+end)/2; 18 | if(A[i][mid]==x){ 19 | return 1; 20 | } 21 | else if(A[i][mid]>x){ 22 | end=mid-1; 23 | } 24 | else{ 25 | start=mid+1; 26 | } 27 | } 28 | } 29 | } 30 | return 0; 31 | } 32 | 33 | 34 | int main(){ 35 | vector> v1={{3, 30, 38},{44, 52, 54},{57, 60, 69}}; 36 | int value=54; 37 | cout< 4 | 5 | using namespace std; 6 | 7 | int palindrome(std::string original){ 8 | int n=original.size(); 9 | int start=0; 10 | int end=n-1; 11 | while(start<=end){ 12 | if(original[start]!=original[end]){ 13 | return 0; 14 | } 15 | start++; 16 | end--; 17 | } 18 | return 1; 19 | } 20 | 21 | int main(){ 22 | string val="CABAC"; 23 | cout< 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | void duplicate_string(std::string A){ 9 | int n=A.size(); 10 | unordered_map m1; 11 | for(int i=0;i::iterator iter=m1.find(A[i]); 13 | if(iter!=m1.end()){ 14 | iter->second++; 15 | } 16 | else{ 17 | m1.insert(std::make_pair(A[i], 1)); 18 | } 19 | } 20 | for(auto it=m1.begin();it!=m1.end();it++){ 21 | if(it->second>1){ 22 | std::cout<first<<" "; 23 | } 24 | } 25 | } 26 | // Time: O(n) and space:O(n) 27 | 28 | int main(){ 29 | string val="CABAC"; 30 | duplicate_string(val); 31 | } 32 | -------------------------------------------------------------------------------- /03-Strings/03-Strings_rotation_each_other.cpp: -------------------------------------------------------------------------------- 1 | // String: Check if two strings are rotation of each other 2 | //https://www.geeksforgeeks.org/a-program-to-check-if-strings-are-rotations-of-each-other/ 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Time:O(n) and space: O(1) 10 | bool rotation(string A, string B){ 11 | int n=A.size(); 12 | int m=B.size(); 13 | if(m!=n) return false; 14 | string temp=A+B; 15 | int x=n-1; 16 | string value=A; 17 | while(x<2*n){ 18 | if(value==B){ 19 | return true; 20 | } 21 | x++; 22 | value=value.substr(1); 23 | value+=temp[x]; 24 | } 25 | return false; 26 | } 27 | 28 | int main(){ 29 | string val="AACD"; 30 | string val2 = "ACDA"; 31 | cout< 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | string count_say(int n){ 17 | string x="1"; 18 | if(n<1) return ""; 19 | for(int i=1;i 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Program to find if there is siffix which is also a prefix 8 | vectorsuffix_prefix(string B){ 9 | int n=B.size(); 10 | vector ans(n); 11 | int val=0; 12 | int i=1; 13 | while(i temp(B.size()); 33 | temp=suffix_prefix(B); 34 | int n=A.size(); 35 | int m=B.size(); 36 | int i=0,j=0; 37 | while(i 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | // Taking two pointers if both are equal then we'll be iterating it towards left and right part of the array. 13 | string longest_palindrome(string A){ 14 | int n=A.size(); 15 | if(n<=1) return A; 16 | int start=0; 17 | int end=0; 18 | int max_len=1; 19 | // If pallindrome of odd length 20 | for(int i=0;i=0 && highmax_len) 32 | { 33 | max_len=value; 34 | start=low+1; 35 | end=high-1; 36 | } 37 | } 38 | // If pallindrome of even length 39 | for(int i=0;i=0 && highmax_len){ 51 | max_len=value; 52 | start=low+1; 53 | end=high-1; 54 | } 55 | } 56 | return A.substr(start,max_len); 57 | } 58 | // Time: O(n^2) and Space: O(1) 59 | 60 | int main(){ 61 | string v1="bbc"; 62 | cout< 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | void print_subsequence(string Inp, string Out){ 9 | if(Inp.size()==0){ 10 | std::cout< 5 | #include 6 | using namespace std; 7 | 8 | void permutation (string a, int low, int high){ 9 | if (low == high){ 10 | cout< 5 | #include 6 | using namespace std; 7 | 8 | int split_binary(string A){ 9 | int count_0=0; 10 | int count_1=0; 11 | int n=A.size(); 12 | if(n<2) return -1; 13 | for(int i=0;i 5 | #include 6 | using namespace std; 7 | 8 | int isPalindrome(string A) { 9 | int n=A.size(); 10 | string a=""; 11 | string rev=""; 12 | int j=n-1; 13 | for(int i=0;i 5 | #include 6 | using namespace std; 7 | 8 | int vowel_consonant(string A){ 9 | long long vowel=0; 10 | long long consonant=0; 11 | long long mode=1000000007; 12 | int n=A.size(); 13 | for(int i=0;i 5 | #include 6 | using namespace std; 7 | 8 | string remove_consecutive(string A, int B){ 9 | int n=A.size(); 10 | if (B>n) return ""; 11 | string ans=""; 12 | int i=0; 13 | while(i 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | string prefix_check(string A, string B){ 13 | string result=""; 14 | int i=0,j=0; 15 | int n=A.size(); 16 | int m=B.size(); 17 | while(i A){ 29 | int n=A.size(); 30 | string B=A[0]; 31 | for(int i=1;i A = {"abab", "ab", "abcd"}; 39 | cout< 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | // LPS Array: Longest Suffix which is also prefix 14 | vectorsuffix_prefix(string B, int n){ 15 | vector ans(n); 16 | int val=0; 17 | int i=1; 18 | while(iv2=suffix_prefix(str,str.size()); 43 | cout< 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | int convert_palindrome(string A){ 14 | int start=0; 15 | int end=A.size()-1; 16 | int mid=(start+end)/2; 17 | int count=1; 18 | while(start<=end && count>=0){ 19 | if(A[start]==A[end]){ 20 | if(start==end){ 21 | break; 22 | } 23 | start++; 24 | end--; 25 | } 26 | else{ 27 | start++; 28 | count--; 29 | } 30 | } 31 | if(start==end && count>=0) return 1; 32 | return 0; 33 | } 34 | //Time: O(n) and Space:O(1) 35 | 36 | int main(){ 37 | string A="gdd"; 38 | cout< 9 | #include 10 | 11 | using namespace std; 12 | 13 | string reverse_string(string A){ 14 | int n=A.size(); 15 | string result=""; 16 | int end=n-1; 17 | string temp=""; 18 | while(end>=0){ 19 | if(A[end]==' ' && A[end+1]!=' '){ 20 | reverse(temp.begin(), temp.end()); 21 | result+=temp; 22 | result+=' '; 23 | temp=""; 24 | } 25 | else if(A[end]==' ' && A[end+1]==' '){ 26 | end--; 27 | continue; 28 | } 29 | else{ 30 | temp+=A[end]; 31 | } 32 | end--; 33 | } 34 | reverse(temp.begin(), temp.end()); 35 | result+=temp; 36 | return result; 37 | } 38 | //Time: O(n) and Space:O(1) 39 | 40 | int main(){ 41 | string A=" abc def"; 42 | cout< 9 | #include 10 | 11 | using namespace std; 12 | 13 | int lengthOfLastWord(const string A) { 14 | int len=0; 15 | int n=A.size(); 16 | for(int i=n-1;i>=0;i--){ 17 | if(A[i]==' ' && len!=0){ 18 | return len; 19 | } 20 | else if(isalpha(A[i])){ 21 | len++; 22 | } 23 | } 24 | return len; 25 | } 26 | 27 | //Time: O(n) and Space:O(1) 28 | 29 | int main(){ 30 | string A="Hello World "; 31 | cout< 12 | #include 13 | 14 | using namespace std; 15 | 16 | int edit_distance(string A, string B){ 17 | int n=A.size(); 18 | int m=B.size(); 19 | int count=0; 20 | if(n==m){ 21 | int i=0; 22 | while(in){ 31 | swap(A,B); 32 | swap(n,m); 33 | } 34 | int i=0; int j=0; 35 | while(i 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | bool balanced_parenthesis(string A){ 16 | int n=A.size(); 17 | std::vector para1; 18 | for(int i=0;i 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | int pattern_matching(string A, string B, int primes){ 11 | int ch=256; 12 | int n=A.size(); 13 | int m=B.size(); 14 | int pat=0; 15 | int text=0; 16 | int hash=1; 17 | // calculating the power of n-1 to subtract the first value from hash if not matched 18 | for(int i=0;i 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | string mobile_sequence(string A[], string B){ 11 | int n=B.size(); 12 | string output=""; 13 | for(int i=0;i 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | bool Isvalid(string B){ 9 | value=stoi(B); 10 | if(B.size()>1 && B[0]=='0'){ 11 | return false; 12 | } 13 | if(value<=0 || value>255){ 14 | return false; 15 | } 16 | return true; 17 | } 18 | 19 | vector valid_IP(string A){ 20 | int n=A.size(); 21 | if(n<4 || n>12) return {}; 22 | vector ans; 23 | for(int i=1;i<4;i++){ 24 | string first=A.substr(0,i); 25 | if(!Isvalid(first)){ 26 | continue; 27 | } 28 | int j=1; 29 | while(i+j v2; 54 | v2=valid_IP(A); 55 | for(auto it=v2.begin();it!=v2.end();it++){ 56 | cout<<*it< 8 | #include 9 | 10 | using namespace std; 11 | int atoi(string str){ 12 | int result=0; 13 | int i=0; 14 | int sign = 1; 15 | // checking the sign of the string 16 | if(str[i]=='-') 17 | { 18 | sign = -1; 19 | i++; 20 | } 21 | else if(str[i]=='+'){ 22 | sign=1; 23 | i++; 24 | } 25 | int count=0; 26 | while(str[i]) 27 | { 28 | if(!(str[i]-'0'>=0 && str[i]-'0'<=9)){ 29 | break; 30 | } 31 | result = result*10 + str[i]-'0'; // return the actual value by subtracting the ascii value of 0 32 | i++; 33 | count++; 34 | } 35 | // handling maximum and minimum case when it exceeds range of integers 36 | if(count>9 && sign==-1){ 37 | result=INT_MIN; 38 | } 39 | if(count>9 && sign==1){ 40 | result=INT_MAX; 41 | } 42 | return result*sign; 43 | } 44 | // time: O(n) and space: O(1) 45 | 46 | int main(){ 47 | string A="5121478262 8070067M75 X199R 547 8C0A11 93I630 4P4071 029W433619 M3 5 14703818 776366059B9O43393"; 48 | cout< 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | int comparision(string A, string B){ 11 | int i = 0 , j = 0 , m = A.length() , n = B.length(); 12 | int val1, val2; 13 | while(i < m || j < n){ 14 | val1 = val2 = 0; 15 | while(i < m && isdigit(A[i])){ 16 | val1 = val1*10+(A[i]-'0'); 17 | i++; 18 | } 19 | while(j < n && isdigit(B[j])){ 20 | val2 = val2*10+(B[j]-'0'); 21 | j++; 22 | } 23 | if(j < n && B[j] == '.') ++j; 24 | if(i < m && A[i] == '.') ++i; 25 | if(val1 > val2) return 1; 26 | else if(val1 < val2) return -1; 27 | } 28 | return 0; 29 | 30 | } 31 | 32 | int main(){ 33 | string A="1.13"; 34 | string B="1.13.4"; 35 | cout< 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | string integer_ToRoman(int num){ 11 | string m[] = { "", "M", "MM", "MMM" }; 12 | string c[] = { "", "C", "CC", "CCC", "CD", 13 | "D", "DC", "DCC", "DCCC", "CM" }; 14 | string x[] = { "", "X", "XX", "XXX", "XL", 15 | "L", "LX", "LXX", "LXXX", "XC" }; 16 | string i[] = { "", "I", "II", "III", "IV", 17 | "V", "VI", "VII", "VIII", "IX" }; 18 | 19 | 20 | string thousands = m[num / 1000]; 21 | string hundereds = c[(num % 1000) / 100]; 22 | string tens = x[(num % 100) / 10]; 23 | string ones = i[num % 10]; 24 | 25 | string ans = thousands + hundereds + tens + ones; 26 | 27 | return ans; 28 | } 29 | 30 | int main(){ 31 | int A=3114; 32 | cout< 5 | #include 6 | #include 7 | 8 | 9 | using namespace std; 10 | 11 | int roman_to_integer(string A){ 12 | unordered_mapm1; 13 | m1.insert(std::make_pair('I',1)); 14 | m1.insert(std::make_pair('V',5)); 15 | m1.insert(std::make_pair('X',10)); 16 | m1.insert(std::make_pair('L',50)); 17 | m1.insert(std::make_pair('C',100)); 18 | m1.insert(std::make_pair('D',500)); 19 | m1.insert(std::make_pair('M',1000)); 20 | int n=A.size(); 21 | int result=m1[A[n-1]]; 22 | for(int i=n-2;i>=0;i--){ 23 | if(m1[A[i]] 5 | #include 6 | using namespace std; 7 | 8 | string add_binary(string A, string B){ 9 | if(B.size()>A.size()){ 10 | swap(A,B); 11 | } 12 | int n=A.size(); 13 | int m=B.size(); 14 | int i=n-1; 15 | int j=m-1; 16 | int carry=0; 17 | string ans=""; 18 | while(i>=0 && j>=0 ){ 19 | int val=(A[i]-'0')+(B[j]-'0'); 20 | val+=carry; 21 | int next=val; 22 | carry=next/2; 23 | val=val%2; 24 | ans+=to_string(val); 25 | i--; 26 | j--; 27 | } 28 | while(i>=0){ 29 | int val=(A[i]-'0'); 30 | val+=carry; 31 | int next=val; 32 | carry=next/2; 33 | val=val%2; 34 | ans+=to_string(val); 35 | i--; 36 | } 37 | if(carry!=0){ 38 | ans+='1'; 39 | } 40 | reverse(ans.begin(), ans.end()); 41 | return ans; 42 | } 43 | //Time: O(m+n) space: O(1) 44 | 45 | 46 | int main(){ 47 | string A="110"; 48 | string B="111"; 49 | cout< 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int count_reversal(string A){ 15 | int n=A.size(); 16 | if(n%2!=0){ 17 | return -1; 18 | } 19 | vector temp; 20 | for(int i=0;i0){ 22 | char first=temp.back(); 23 | if(A[i]=='}' && first=='{'){ 24 | temp.pop_back(); 25 | } 26 | else{ 27 | temp.push_back(A[i]); 28 | } 29 | } 30 | else{ 31 | temp.push_back(A[i]); 32 | } 33 | } 34 | int end=temp.size(); 35 | int mid=end/2; 36 | int count=0; 37 | int i=0; 38 | while(i 9 | #include 10 | 11 | using namespace std; 12 | 13 | // Checking the indexes of the odd position and even position 14 | // Example: 0 1 0 either even index can have all 0 and odd index can have all 1 and vice versa. 15 | //seq 1: 0 1 0 ( even: 0 and odd :1 other than this we'll increment the count) 16 | //seq 2: 1 0 1 ( even: 1 and odd :0 other than this we'll increment the count) 17 | int minimum_flips(string A){ 18 | int n=A.size(); 19 | int count1=0; 20 | int count2=0; 21 | for(int i=0;i 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | string second_consecutive(string A[], int n){ 16 | unordered_map m1; 17 | for(int i=0;i::iterator iter=m1.find(A[i]); 19 | if(iter!=m1.end()){ 20 | iter->second++; 21 | } 22 | else{ 23 | m1.insert(std::make_pair(A[i], 1)); 24 | } 25 | } 26 | int first=INT_MIN; 27 | int second=INT_MIN; 28 | string find=""; 29 | string a=""; 30 | for(auto it=m1.begin();it!=m1.end();it++){ 31 | bool flag=false; 32 | if(firstsecond){ 33 | if(secondsecond; 38 | a=it->first; 39 | } 40 | else if (it->second > second && it->second != first){ 41 | second = it->second; 42 | find=it->first; 43 | } 44 | } 45 | return find; 46 | } 47 | 48 | 49 | int main(){ 50 | string arr[] = {"geek", "for", "geek", "for", "geek", "aaa"}; 51 | int n=sizeof(arr)/sizeof(arr[0]); 52 | cout< 9 | #include 10 | 11 | 12 | using namespace std; 13 | 14 | int minimum_swaps(string A){ 15 | int open=0; 16 | int close=0; 17 | int n=A.size(); 18 | int defect=0; 19 | int ans=0; 20 | //Taken defect count when we get unbalancing the defect count will increase we'll add the defect count in answer and that will be counted as adjacent swap. 21 | for(int i=0;i0){ 29 | ans+=defect; 30 | defect--; // decreasing count by 1 as one defect is fixed with the swap. 31 | } 32 | } 33 | } 34 | return ans; 35 | } 36 | //Time: O(n) and space:O(1) 37 | 38 | 39 | int main(){ 40 | string A="[[][]]"; 41 | cout< 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | string smallest_substring(string A){ 14 | unordered_set s1; 15 | int n=A.size(); 16 | for(int i=0;i s2; 27 | s2.insert(A[start]); 28 | while(end(end-start)){ 42 | s=start; 43 | e=end; 44 | } 45 | break; 46 | } 47 | end++; 48 | } 49 | } 50 | i=start+1; 51 | } 52 | return A.substr(s,e-s+1); 53 | } 54 | // Time: O(n2) and space: O(n) 55 | 56 | int main(){ 57 | string A="CCABBAbBCABB"; 58 | cout< 9 | #include 10 | using namespace std; 11 | 12 | string remove_dupliate(string A){ 13 | int n=A.size(); 14 | string ans=""; 15 | for(int i=0;i 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | bool areIsomorphic(string str1, string str2){ 15 | unordered_map m1; 16 | int n=str1.size(); 17 | int m=str2.size(); 18 | if(m!=n) return false; 19 | for(int i=0;i m2; 23 | for(int i=0;i::iterator iter=m1.find(str2[i]); 25 | if(iter!=m1.end()){ 26 | return false; 27 | } 28 | m2[str2[i]]++; 29 | } 30 | if(m1.size()!=m2.size()) return false; 31 | return true; 32 | 33 | } 34 | int main(){ 35 | string A="aab"; 36 | string B="xxy"; 37 | cout< 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | 12 | string duplicateletter(string s) 13 | { 14 | vector lastIndex(26, 0); 15 | for (int i = 0; i < s.length(); i++) 16 | { 17 | lastIndex[s[i] - 'a'] = i; // track the lastIndex of character presence 18 | } 19 | 20 | vector seen(26, false); // keep track seen 21 | stack st; 22 | 23 | for (int i = 0; i < s.size(); i++) { 24 | int curr = s[i] - 'a'; 25 | if (seen[curr]) continue; // if seen continue as we need to pick one char only 26 | while(st.size() > 0 && st.top() > s[i] && i < lastIndex[st.top() - 'a']){ 27 | seen[st.top() - 'a'] = false; // pop out and mark unseen 28 | st.pop(); 29 | } 30 | st.push(s[i]); // add into stack 31 | seen[curr] = true; // mark seen 32 | } 33 | 34 | string ans = ""; 35 | while (st.size() > 0){ 36 | ans += st.top(); 37 | st.pop(); 38 | } 39 | reverse(ans.begin(), ans.end()); 40 | return ans; 41 | } 42 | 43 | int main() 44 | { 45 | string a="cbacdcbc"; 46 | cout< 4 | #include 5 | 6 | using namespace std; 7 | 8 | vector first_last_occurence(vector A, int x){ 9 | int n=A.size(); 10 | vector ans; 11 | int value=-1; 12 | int start=0; 13 | int end=n-1; 14 | int i=0; 15 | while(start<=end){ 16 | int mid=(start+end)/2; 17 | if(A[mid]==x){ 18 | value=mid; 19 | end=mid-1; 20 | } 21 | else if( A[mid]>x){ 22 | end=mid-1; 23 | } 24 | else{ 25 | start=mid+1; 26 | } 27 | } 28 | ans.push_back(value); 29 | start=0; 30 | end=n-1; 31 | while(start<=end){ 32 | int mid=(start+end)/2; 33 | if(A[mid]==x){ 34 | value=mid; 35 | start=mid+1; 36 | } 37 | else if( A[mid]>x){ 38 | end=mid-1; 39 | } 40 | else{ 41 | start=mid+1; 42 | } 43 | } 44 | ans.push_back(value); 45 | return ans; 46 | } 47 | 48 | int main(){ 49 | vector A={ 1, 3, 5, 5, 5, 5, 67, 123, 125 }; 50 | vector v2; 51 | v2=first_last_occurence(A, 5); 52 | for(auto it=v2.begin();it!=v2.end();it++){ 53 | cout<<*it<<" "; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /04-Sorting and Searching/02-Search_Rotated_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | // Searching:Search in a rotated sorted array 2 | //https://leetcode.com/problems/search-in-rotated-sorted-array/submissions/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int rotated_search(vector A, int x){ 10 | int inv=1; 11 | int n=A.size(); 12 | if(n<3){ 13 | for(int i=0;ix){ 43 | end1=mid-1; 44 | } 45 | else{ 46 | start1=mid+1; 47 | } 48 | } 49 | while(start2<=end2){ 50 | int mid=(start2+end2)/2; 51 | if(A[mid]==x){ 52 | return mid; 53 | } 54 | else if(A[mid]>x){ 55 | end2=mid-1; 56 | } 57 | else{ 58 | start2=mid+1; 59 | } 60 | } 61 | return -1; 62 | } 63 | //Time: O(nlogn) and Space:O(1) 64 | 65 | int main(){ 66 | vector A={5,1,3}; 67 | cout< 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | int squareroot(int A) 10 | { 11 | if (A == 0 || A == 1) 12 | return A; 13 | int start = 1, end = A/2, ans; 14 | while (start <= end) { 15 | int mid = (start + end) / 2; 16 | int sqr = mid * mid; 17 | if (sqr == A){ 18 | return mid; 19 | } 20 | else if(sqr <= A) { 21 | start = mid + 1; 22 | ans = mid; 23 | } 24 | else{ 25 | end = mid - 1; 26 | } 27 | } 28 | return ans; 29 | } 30 | //Time: O(logn) space: O(1) 31 | 32 | int main(){ 33 | int A=15; 34 | cout< 5 | using namespace std; 6 | 7 | int middle_element(int A, int B, int C){ 8 | if((A>C && AB && AA && CB && C 8 | #include 9 | using namespace std; 10 | 11 | vector duplicate_nissing(vector &A){ 12 | vector ans; 13 | int n=A.size(); 14 | int i=0; 15 | while(i v1= {4,3,6,2,1,1}; 40 | vector v2; 41 | v2=duplicate_nissing(v1); 42 | for(auto it=v2.begin();it!=v2.end();it++){ 43 | cout<<*it< 9 | #include 10 | using namespace std; 11 | 12 | // Need to find a pair without using extra space. 13 | // 2 steps: 14 | // 1. Sort the array 15 | //2. Start finding difference if less increment end pointer otherwise increment start pointer. 16 | bool pair_diff(vector &A, int x){ 17 | int n=A.size(); 18 | int start=0; 19 | int end=1; 20 | sort(A.begin(),A.end()); 21 | while(start v1= {5, 20, 3, 2, 5, 80}; 38 | cout< 9 | #include 10 | using namespace std; 11 | 12 | // Taking two pointers include will take the current element included in the maximum sum so far while exclude will not take the current element in the maximum sum so far 13 | int maximum_sum(vector &arr){ 14 | int n=arr.size(); 15 | int include = arr[0]; 16 | int exclude = 0; 17 | int exclude_new; 18 | int i; 19 | 20 | for (i = 1; i < n; i++) 21 | { 22 | exclude_new = max(include,exclude); 23 | include = exclude + arr[i]; 24 | exclude = exclude_new; 25 | } 26 | 27 | 28 | return max(include,exclude); 29 | } 30 | 31 | 32 | int main(){ 33 | vector v1= {1,21,200,4,8,61,7}; 34 | cout< 5 | #include 6 | using namespace std; 7 | 8 | int counttriplets(vector &A, int x){ 9 | int n=A.size(); 10 | int count=0; 11 | if(n<3) return 0; 12 | sort(A.begin(),A.end()); 13 | for(int i=0;i=x ){ 18 | k--; 19 | } 20 | else 21 | { 22 | count += (k - j); 23 | j++; 24 | } 25 | } 26 | } 27 | return count; 28 | } 29 | //Time: O(n2) and Space: O(1) 30 | 31 | int main(){ 32 | vector v1= {5, 1, 3, 4, 7}; 33 | cout< 5 | #include 6 | using namespace std; 7 | 8 | // Taking two variable and checking the occurence of that element in entire array and keep on updating the majority element if the value of the count becomes 0 9 | int majority_element(vector &A){ 10 | int n=A.size(); 11 | int count=1; 12 | int majority=A[0]; 13 | for(int i=1;in/2){ 33 | return majority; 34 | } 35 | // if count is less than n/2 return -1 36 | return -1; 37 | } 38 | // Time: O(n) and Space: O(1) 39 | 40 | 41 | int main(){ 42 | vector v1= {3, 1, 3, 3, 2}; 43 | cout< 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int zero_sum_subarray(vector &A){ 10 | int n=A.size(); 11 | int sumeed=0; 12 | int count=0; 13 | unordered_map m1; 14 | for(int i=0;i::iterator iter=m1.find(sumeed); 20 | if(iter!=m1.end()){ 21 | count+=(iter->second); 22 | iter->second++; 23 | } 24 | else{ 25 | m1.insert(std::make_pair(sumeed, 1)); 26 | } 27 | } 28 | return count; 29 | } 30 | //Time: O(n) and Space: O(n) 31 | 32 | 33 | int main(){ 34 | vector v1= {0,0,5,5,0,0}; 35 | cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | vector product_puzzle(vector &A){ 10 | int n=A.size(); 11 | int value=0; 12 | long long int prod=1; 13 | for(int i=0;i ans; 22 | for(int i=0;i 1) { 24 | ans.push_back(0); 25 | } 26 | else if (value == 0){ 27 | ans.push_back(prod / A[i]); 28 | } 29 | 30 | else if (value == 1 && A[i] != 0) { 31 | ans.push_back(0); 32 | } 33 | else{ 34 | ans.push_back(prod); 35 | } 36 | } 37 | return ans; 38 | } 39 | // Time: O(n) and Space: O(n) 40 | 41 | int main(){ 42 | vector v1= {12,0,12}; 43 | vector v2; 44 | v2=product_puzzle(v1); 45 | for(auto it=v2.begin();it!=v2.end();it++){ 46 | cout<<*it<<" "; 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /04-Sorting and Searching/13-Sort_by_Set_Bit_Count.cpp: -------------------------------------------------------------------------------- 1 | // Searching & Sorting: Sort by Set Bit Coun 2 | //https://practice.geeksforgeeks.org/problems/sort-by-set-bit-count1153/1# 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | int convert_binary(int A){ 9 | string ans=""; 10 | int count=0; 11 | while(A>0){ 12 | ans+=to_string(A%2); 13 | if(A%2==1){ 14 | count++; 15 | } 16 | A=A/2; 17 | } 18 | cout<countB){ 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | void sort_bits(vector &A){ 32 | int n=A.size(); 33 | sort(A.begin(),A.end(),compare); 34 | } 35 | int main(){ 36 | vector v1= {1, 2, 3, 4, 5, 6}; 37 | sort_bits(v1); 38 | for(auto it=v1.begin();it!=v1.end();it++){ 39 | cout<<*it<<" "; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /04-Sorting and Searching/14-Min_swaps_to_make_array_sorted.py: -------------------------------------------------------------------------------- 1 | def minSwaps(arr): 2 | ans = 0 3 | n=len(arr) 4 | temp = arr.copy() 5 | h = {} 6 | temp.sort() 7 | for i in range(n): 8 | h[arr[i]] = i 9 | init = 0 10 | 11 | for i in range(n): 12 | if (arr[i] != temp[i]): 13 | ans += 1 14 | init = arr[i] 15 | arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i] 16 | h[init] = h[temp[i]] 17 | h[temp[i]] = i 18 | 19 | return ans 20 | arr=[2, 8, 5, 4] 21 | print(minSwaps(arr)) 22 | -------------------------------------------------------------------------------- /04-Sorting and Searching/15-Search_in_Bitonic_Array.cpp: -------------------------------------------------------------------------------- 1 | // Searching & Sorting: Search in Bitonic Array! 2 | //https://www.interviewbit.com/problems/search-in-bitonic-array/ 3 | /* 4 | A = [3, 9, 10, 20, 17, 5, 1] 5 | B = 20 6 | o/p: 3 7 | */ 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | int bitonic(vector &A, int x){ 13 | int inv=1; 14 | int n=A.size(); 15 | if(n<3){ 16 | for(int i=0;iA[i+1]){ 27 | inv=i; 28 | flag=true; 29 | break; 30 | } 31 | } 32 | if(A[n-1]x){ 46 | end1=mid-1; 47 | } 48 | else{ 49 | start1=mid+1; 50 | } 51 | } 52 | while(start2<=end2){ 53 | int mid=(start2+end2)/2; 54 | if(A[mid]==x){ 55 | return mid; 56 | } 57 | else if(A[mid] v1= {3, 9, 10, 20, 17, 5, 1}; 68 | cout< 9 | #include 10 | 11 | using namespace std; 12 | 13 | /// Calculatiung all the trailing zero by counting all the 5 in an number 14 | // formula: (n/5)+(n/25) +(n/125).... 15 | 16 | bool check_count(int n, int p){ 17 | int count=0; 18 | int k=1; 19 | while((n/pow(5,k))>=1){ 20 | // cout<<(n/pow(5,k))< 4 | #include 5 | using namespace std; 6 | 7 | void selectionsort(vector &A){ 8 | int n=A.size(); 9 | int mini=INT_MAX; 10 | int index=0; 11 | for(int i=0;iA[j]){ 16 | index=j; 17 | } 18 | } 19 | swap(A[i],A[index]); 20 | } 21 | } 22 | 23 | //Time: O(n2) 24 | 25 | int main(){ 26 | vector A={64, 25, 12, 22, 11}; 27 | selectionsort(A); 28 | for(int i=0;i 4 | #include 5 | using namespace std; 6 | 7 | void bubblesort(vector &A){ 8 | int n=A.size(); 9 | for(int i=0;iA[j+1]) 13 | swap(A[j+1],A[j]); 14 | } 15 | } 16 | } 17 | 18 | //Time: O(n2) 19 | 20 | //Method 2: By using Recursion 21 | void recursive_bubble_sort(vector &A, int n){ 22 | if(n==1){ 23 | return; 24 | } 25 | for(int i=0;iA[i+1]){ 27 | swap(A[i], A[i+1]); 28 | } 29 | } 30 | recursive_bubble_sort(A, n-1); 31 | } 32 | 33 | int main(){ 34 | vector A={19,1,4,2,8,9}; 35 | vector B={19,1,4,2,8,9}; 36 | bubblesort(A); 37 | recursive_bubble_sort(B, B.size()); 38 | for(int i=0;i 4 | #include 5 | using namespace std; 6 | 7 | void insertionsort(vector &A){ 8 | bool flag=false; 9 | int n=A.size(); 10 | for(int i=1;i=0 && A[j]>key){ 14 | A[j+1]=A[j]; 15 | j--; 16 | } 17 | A[j+1]=key; 18 | } 19 | } 20 | 21 | 22 | //Time: O(n2) 23 | 24 | //Method 2: By using Recursion 25 | void recursive_insertion_sort(vector &A, int n){ 26 | if (n <= 1){ 27 | return; 28 | } 29 | recursive_insertion_sort(A, n-1); 30 | int last =A[n-1]; 31 | int j = n-2; 32 | while (j >= 0 && A[j] > last) 33 | { 34 | A[j+1] = A[j]; 35 | j--; 36 | } 37 | A[j+1] = last; 38 | } 39 | 40 | int main(){ 41 | vector A={19,1,4,2,8,9}; 42 | vector B={19,1,4,2,8,9}; 43 | insertionsort(A); 44 | recursive_insertion_sort(B, B.size()); 45 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | 6 | void merge(int* A, int* L, int left_length, int* R, int right_length) { 7 | int l = 0; 8 | int r = 0; 9 | int i=0; 10 | while(l 4 | 5 | using namespace std; 6 | 7 | int partition(int *A, int start, int end){ 8 | int i=start; 9 | int pindex=start; 10 | int pivot=A[end]; 11 | while(i 4 | 5 | using namespace std; 6 | 7 | // A Node class which has two values data and pointer to next node 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | //Printing elements of the linked list 14 | void Print_Linked_list(Node *n){ 15 | while(n!=nullptr){ 16 | cout<data<<" "; 17 | n=n->next; 18 | } 19 | } 20 | 21 | // Creating nodes, adding data and printing nodes. 22 | int main(){ 23 | Node *head=nullptr; 24 | Node *first=nullptr; 25 | Node *second=nullptr; 26 | head=new Node(); 27 | first=new Node(); 28 | second= new Node(); 29 | head->data=1; 30 | head->next=first; 31 | first->data=2; 32 | first->next=second; 33 | second->data=3; 34 | Print_Linked_list(head); 35 | } 36 | -------------------------------------------------------------------------------- /05-Linked List/02-Insertion_at_specific_position_linked_list.cpp: -------------------------------------------------------------------------------- 1 | //Linked List: Insertion of node at head, Insertion of node at a position 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // A Node class which has two values data and pointer to next node 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | //Printing elements of the linked list 15 | void Print_Linked_list(Node *n){ 16 | while(n!=nullptr){ 17 | cout<data<<"->"; 18 | n=n->next; 19 | } 20 | cout<data=data; 26 | newhead->next=head; 27 | head=newhead; 28 | return head; 29 | } 30 | // Insertion of node at a specific position 31 | void Insert_after(int position, int data, Node *head){ 32 | Node *next_node= new Node(); 33 | next_node->data=data; 34 | // If position is 1 then we need to update the head pointer 35 | if(position==1){ 36 | next_node->next=head; 37 | head=next_node; 38 | Print_Linked_list(head); 39 | return ; 40 | } 41 | Node *temp=head; 42 | int i=0; 43 | while(inext!=NULL){ 44 | temp=temp->next; 45 | i++; 46 | } 47 | next_node->next=temp->next; 48 | temp->next=next_node; 49 | Print_Linked_list(head); 50 | return ; 51 | } 52 | 53 | // Creating nodes, adding data and printing nodes. 54 | int main(){ 55 | Node *head=new Node(); 56 | head=nullptr; 57 | head=Insert_start(head, 1); 58 | head=Insert_start(head, 2); 59 | head=Insert_start(head, 4); 60 | head=Insert_start(head, 6); 61 | Print_Linked_list(head); 62 | Insert_after(3, 130, head); 63 | } 64 | -------------------------------------------------------------------------------- /05-Linked List/03-Delete_nth_node.cpp: -------------------------------------------------------------------------------- 1 | //Linked List: Deletion of Node at nth position 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // A Node class which has two values data and pointer to next node 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | //Printing elements of the linked list 15 | void Print_Linked_list(Node *n){ 16 | while(n!=nullptr){ 17 | cout<data<<"->"; 18 | n=n->next; 19 | } 20 | cout<data=data; 26 | newhead->next=head; 27 | head=newhead; 28 | return head; 29 | } 30 | 31 | // Deleting Node at particular position 32 | Node * delete_node(Node *head, int position){ 33 | Node *temp=new Node(); 34 | temp=head; 35 | int i=0; 36 | if(position<1) return head; 37 | if (position==1){ 38 | head=temp->next; 39 | delete temp; 40 | return head; 41 | } 42 | while(inext!=NULL){ 43 | temp=temp->next; 44 | i++; 45 | } 46 | temp->next=(temp->next)->next; 47 | delete temp; 48 | return head; 49 | } 50 | 51 | // Creating nodes, adding data and printing nodes. 52 | int main(){ 53 | Node *head=new Node(); 54 | head=nullptr; 55 | head=Insert_start(head, 1); 56 | head=Insert_start(head, 2); 57 | head=Insert_start(head, 4); 58 | head=Insert_start(head, 6); 59 | Print_Linked_list(head); 60 | head=delete_node(head, 1); 61 | Print_Linked_list(head); 62 | delete_node(head, 2); 63 | Print_Linked_list(head); 64 | } 65 | -------------------------------------------------------------------------------- /05-Linked List/04-Length_linked_list.cpp: -------------------------------------------------------------------------------- 1 | //Linked List:Length of Linked List using Iterative and Recursive approach 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // A Node class which has two values data and pointer to next node 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | //Printing elements of the linked list 15 | void Print_Linked_list(Node *n){ 16 | while(n!=nullptr){ 17 | cout<data<<"->"; 18 | n=n->next; 19 | } 20 | cout<data=data; 26 | newhead->next=head; 27 | head=newhead; 28 | return head; 29 | } 30 | //Lenght of linked List using iterative way 31 | int length_linked(Node *head){ 32 | Node *temp=new Node(); 33 | temp=head; 34 | int count=1; 35 | while(temp->next!=NULL){ 36 | count++; 37 | temp=temp->next; 38 | } 39 | return count; 40 | } 41 | // Length of linked list using recursive way 42 | int recursive_length(Node *node){ 43 | if(node->next==NULL){ 44 | return 1; 45 | } 46 | else{ 47 | return 1+ recursive_length(node->next); 48 | } 49 | } 50 | 51 | // Creating nodes, adding data and printing nodes. 52 | int main(){ 53 | Node *head=new Node(); 54 | head=nullptr; 55 | head=Insert_start(head, 1); 56 | head=Insert_start(head, 2); 57 | head=Insert_start(head, 4); 58 | head=Insert_start(head, 6); 59 | Print_Linked_list(head); 60 | cout< 4 | 5 | using namespace std; 6 | 7 | // A Node class which has three values data and pointer to next node and flag to know if node is traversed earlier or not 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | int flag; 13 | }; 14 | 15 | //Printing elements of the linked list 16 | void Print_Linked_list(Node *n){ 17 | while(n!=nullptr){ 18 | cout<data<<"->"; 19 | n=n->next; 20 | } 21 | cout<data=data; 27 | newhead->next=head; 28 | newhead->flag=0; 29 | head=newhead; 30 | return head; 31 | } 32 | 33 | // Checking the loop by checking if linked list is already traversed or not. 34 | bool detect_loop(Node *head){ 35 | Node *temp=new Node(); 36 | temp=head; 37 | while(temp->next!=NULL){ 38 | if(temp->flag==1){ 39 | return true; 40 | } 41 | temp->flag=1; 42 | temp=temp->next; 43 | } 44 | return false; 45 | } 46 | 47 | // Creating nodes, adding data and printing nodes. 48 | int main(){ 49 | Node *head=new Node(); 50 | head=nullptr; 51 | head=Insert_start(head, 1); 52 | head=Insert_start(head, 2); 53 | head=Insert_start(head, 4); 54 | head=Insert_start(head, 6); 55 | Print_Linked_list(head); 56 | cout<next->next->next->next = head; 58 | cout< 5 | 6 | using namespace std; 7 | 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | int flag; 13 | }; 14 | void Print_Linked_list(Node *n){ 15 | while(n!=nullptr){ 16 | cout<data<<"->"; 17 | n=n->next; 18 | } 19 | cout<data=data; 25 | temp->next = head; 26 | temp->flag=0; 27 | head = temp; 28 | return head; 29 | } 30 | 31 | void remove_duplicate(Node *&head){ 32 | Node *temp=head; 33 | // if(hea) 34 | while(temp->next!=NULL){ 35 | if(temp->data==temp->next->data){ 36 | temp->next=temp->next->next; 37 | } 38 | else{ 39 | temp=temp->next; 40 | } 41 | } 42 | } 43 | // Time: O(n) and Space: O(1) 44 | 45 | int main() { 46 | Node *head=new Node(); 47 | head=NULL; 48 | // head=Insert_start(head, 6); 49 | head=Insert_start(head, 3); 50 | head=Insert_start(head, 3); 51 | head=Insert_start(head, 3); 52 | head=Insert_start(head, 2); 53 | head=Insert_start(head, 2); 54 | Print_Linked_list(head); 55 | remove_duplicate(head); 56 | Print_Linked_list(head); 57 | } 58 | -------------------------------------------------------------------------------- /05-Linked List/12-Move_last_node_front.cpp: -------------------------------------------------------------------------------- 1 | // Linked List: Move last element to front of a given Linked List 2 | //https://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Node{ 10 | public: 11 | int data; 12 | Node *next; 13 | int flag; 14 | }; 15 | void Print_Linked_list(Node *n){ 16 | while(n!=nullptr){ 17 | cout<data<<"->"; 18 | n=n->next; 19 | } 20 | cout<data=data; 26 | temp->next = head; 27 | temp->flag=0; 28 | head = temp; 29 | return head; 30 | } 31 | 32 | void move_last_front(Node *&head){ 33 | Node *temp=head; 34 | while(temp->next->next!=NULL){ 35 | temp=temp->next; 36 | } 37 | Node *first=temp->next; 38 | temp->next=NULL; 39 | Node *second=head; 40 | head=first; 41 | head->next=second; 42 | } 43 | 44 | int main() { 45 | Node *head=new Node(); 46 | head=NULL; 47 | head=Insert_start(head, 6); 48 | head=Insert_start(head, 5); 49 | head=Insert_start(head, 4); 50 | head=Insert_start(head, 3); 51 | head=Insert_start(head, 2); 52 | head=Insert_start(head, 1); 53 | Print_Linked_list(head); 54 | move_last_front(head); 55 | Print_Linked_list(head); 56 | } 57 | -------------------------------------------------------------------------------- /05-Linked List/17-Sort_binary_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // Linked List:Sort Binary Linked List 2 | //https://www.interviewbit.com/problems/sort-binary-linked-list/ 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | int flag; 13 | }; 14 | void Print_Linked_list(Node *n){ 15 | while(n!=nullptr){ 16 | cout<data<<"->"; 17 | n=n->next; 18 | } 19 | cout<next=NULL; 26 | newnode->data=data; 27 | Node *last=head; 28 | if(head==NULL){ 29 | head=newnode; 30 | return; 31 | } 32 | while(last->next!=NULL){ 33 | last=last->next; 34 | } 35 | last->next=newnode; 36 | return; 37 | } 38 | void sort_binary(Node * &head){ 39 | Node *temp=head; 40 | int count_0=0; 41 | int count_1=0; 42 | while(temp!=NULL){ 43 | if(temp->data==0){ 44 | count_0++; 45 | } 46 | else{ 47 | count_1++; 48 | } 49 | temp=temp->next; 50 | } 51 | temp=head; 52 | while(count_0>0){ 53 | temp->data=0; 54 | count_0--; 55 | temp=temp->next; 56 | } 57 | while(count_1>0){ 58 | temp->data=1; 59 | count_1--; 60 | temp=temp->next; 61 | } 62 | } 63 | //Time : O(n) and space: O(1) 64 | 65 | int main() { 66 | Node *head=new Node(); 67 | head=NULL; 68 | append(head, 0); 69 | append(head, 1); 70 | append(head, 1); 71 | append(head, 1); 72 | append(head, 0); 73 | Print_Linked_list(head); 74 | sort_binary(head); 75 | Print_Linked_list(head); 76 | 77 | } 78 | 79 | -------------------------------------------------------------------------------- /05-Linked List/20-Delete_node_circular_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // Deletion of node in circular Linked List. 2 | 3 | //Psedo code from GFG. https://www.geeksforgeeks.org/deletion-circular-linked-list/ 4 | void deleteNode(Node** head, int key) 5 | { 6 | 7 | // If linked list is empty 8 | if (*head == NULL) 9 | return; 10 | 11 | // If the list contains only a single node 12 | if((*head)->data==key && (*head)->next==*head) 13 | { 14 | free(*head); 15 | *head=NULL; 16 | return; 17 | } 18 | 19 | Node *last=*head,*d; 20 | 21 | // If head is to be deleted 22 | if((*head)->data==key) 23 | { 24 | 25 | // Find the last node of the list 26 | while(last->next!=*head) 27 | last=last->next; 28 | 29 | // Point last node to the next of head i.e. 30 | // the second node of the list 31 | last->next=(*head)->next; 32 | free(*head); 33 | *head=last->next; 34 | return; 35 | } 36 | 37 | // Either the node to be deleted is not found 38 | // or the end of list is not reached 39 | while(last->next!=*head&&last->next->data!=key) 40 | { 41 | last=last->next; 42 | } 43 | 44 | // If node to be deleted was found 45 | if(last->next->data==key) 46 | { 47 | d=last->next; 48 | last->next=d->next; 49 | free(d); 50 | } 51 | else 52 | cout<<"no such keyfound"; 53 | } 54 | -------------------------------------------------------------------------------- /05-Linked List/21-Revers_doubly_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // Linked List: Reversal of Doubly Linked List 2 | //https://www.geeksforgeeks.org/reverse-a-doubly-linked-list/ 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | Node *prev; 13 | }; 14 | void Print_Linked_list(Node *n){ 15 | Node *PREV=n; 16 | while(n!=nullptr){ 17 | cout<data<<"-><-"; 18 | PREV=n; 19 | n=n->next; 20 | } 21 | cout<prev; 28 | current->prev=current->next; 29 | current->next=temp; 30 | current=current->prev; 31 | } 32 | head=temp->prev; 33 | } 34 | void Insert_start(Node *&head, int data){ 35 | Node *newnode=new Node(); 36 | newnode->data=data; 37 | newnode->next=head; 38 | newnode->prev=NULL; 39 | if(head!=NULL){ 40 | head->prev=newnode; 41 | } 42 | } 43 | 44 | 45 | // Append nodes at the end of the linked list. 46 | void append(Node *&head, int data){ 47 | Node *newnode=new Node(); 48 | newnode->next=NULL; 49 | newnode->data=data; 50 | Node *last=head; 51 | if(head==NULL){ 52 | head=newnode; 53 | newnode->prev=NULL; 54 | return; 55 | } 56 | while(last->next!=NULL){ 57 | last=last->next; 58 | } 59 | last->next=newnode; 60 | newnode->prev=last; 61 | return; 62 | } 63 | 64 | 65 | int main() { 66 | Node *head=new Node(); 67 | head=NULL; 68 | append(head, 11); 69 | append(head, 2); 70 | append(head, 3); 71 | append(head, 14); 72 | append(head, 4); 73 | Print_Linked_list(head); 74 | reverse(head); 75 | Print_Linked_list(head); 76 | } 77 | -------------------------------------------------------------------------------- /06-Stack/01-Stack_Implementation_using_array.cpp: -------------------------------------------------------------------------------- 1 | // Stack: Implementing Stack using Arrays 2 | 3 | #include 4 | 5 | using namespace std; 6 | #define MAX_LIMIT 100 7 | 8 | class Stack{ 9 | int top; 10 | public: 11 | int A[MAX_LIMIT]; 12 | Stack(){ 13 | top=-1; 14 | } 15 | bool push(int x); 16 | int pop(); 17 | int peek(); 18 | bool isEmpty(); 19 | }; 20 | 21 | bool Stack::push(int x){ 22 | if(top>=MAX_LIMIT){ 23 | cout<<"Stack is Full "< 6 | using namespace std; 7 | 8 | class Node{ 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | Node *New_node(int data){ 15 | Node *new_node=new Node(); 16 | new_node->data=data; 17 | new_node->next=NULL; 18 | return new_node; 19 | } 20 | 21 | int isEmpty(Node *head){ 22 | return !head; 23 | } 24 | 25 | void push(Node* &head, int data){ 26 | Node *temp=New_node(data); 27 | temp->next=head; 28 | head=temp; 29 | } 30 | 31 | int pop(Node* &head){ 32 | if(isEmpty(head)){ 33 | return NULL; 34 | } 35 | Node *temp=head; 36 | head=head->next; 37 | int value=temp->data; 38 | delete temp; 39 | return value; 40 | } 41 | 42 | int peek(Node *head){ 43 | if(isEmpty(head)){ 44 | return NULL; 45 | } 46 | return head->data; 47 | } 48 | 49 | int main(){ 50 | Node *head=new Node(); 51 | head=NULL; 52 | push(head, 1); 53 | push(head, 2); 54 | push(head, 3); 55 | push(head, 4); 56 | cout< 6 | 7 | using namespace std; 8 | #define MAX_LIMIT 100 9 | 10 | class Stack{ 11 | int top; 12 | public: 13 | string A[MAX_LIMIT]; 14 | Stack(){ 15 | top=-1; 16 | } 17 | bool push(char x); 18 | string pop(); 19 | string peek(); 20 | bool isEmpty(); 21 | }; 22 | 23 | bool Stack::push(char x){ 24 | if(top>=MAX_LIMIT){ 25 | cout<<"Stack is Full "< 4 | 5 | using namespace std; 6 | 7 | class Stack{ 8 | 9 | int top; 10 | public: 11 | string arr[100]; 12 | Stack(){ 13 | top=-1; 14 | } 15 | void push(char value){ 16 | arr[++top]=value; 17 | } 18 | string pop(){ 19 | return arr[top--]; 20 | } 21 | }; 22 | 23 | int main(){ 24 | string A="Akshay"; 25 | Stack S1; 26 | for(int i=0;i 6 | #include 7 | using namespace std; 8 | 9 | struct MyStack 10 | { 11 | stack s; 12 | int minEle; 13 | 14 | void getMin() 15 | { 16 | if (s.empty()) 17 | cout << "Stack is empty\n"; 18 | else 19 | cout <<"Minimum element: "< 11 | #include 12 | using namespace std; 13 | 14 | class Stack{ 15 | int top; 16 | public: 17 | int A[100]; 18 | Stack(){ 19 | top=-1; 20 | } 21 | bool push(int x); 22 | int pop(); 23 | int peek(); 24 | bool isEmpty(); 25 | }; 26 | 27 | bool Stack::push(int x){ 28 | if(top>=100){ 29 | cout<<"Stack is Full "< next_greater(vector &A){ 61 | int n=A.size(); 62 | Stack S; 63 | vector greater(n,-1); 64 | int i=0; 65 | while(iA[i]){ 71 | S.push(i); 72 | i++; 73 | } 74 | else{ 75 | greater[S.pop()]=A[i]; 76 | } 77 | } 78 | return greater; 79 | } 80 | 81 | int main(){ 82 | vector v1={11, 13, 21, 3}; 83 | vector v2=next_greater(v1); 84 | for(auto it=v2.begin();it!=v2.end();it++){ 85 | cout<<*it<<" "; 86 | } 87 | cout< 6 | #include 7 | 8 | using namespace std; 9 | 10 | stack st; 11 | 12 | string ns; 13 | 14 | void insert_at_bottom(char x) 15 | { 16 | if(st.size() == 0) 17 | st.push(x); 18 | 19 | else 20 | { 21 | char a = st.top(); 22 | st.pop(); 23 | insert_at_bottom(x); 24 | st.push(a); 25 | } 26 | } 27 | 28 | void reverse() 29 | { 30 | if(st.size()>0) 31 | { 32 | char x = st.top(); 33 | st.pop(); 34 | reverse(); 35 | insert_at_bottom(x); 36 | } 37 | } 38 | 39 | int main() 40 | { 41 | st.push('1'); 42 | st.push('2'); 43 | st.push('3'); 44 | st.push('4'); 45 | 46 | cout<<"Original Stack"< 5 | #include 6 | 7 | using namespace std; 8 | 9 | stack st; 10 | 11 | string ns; 12 | 13 | void insert_at_bottom(int x) 14 | { 15 | if(st.size() == 0) 16 | st.push(x); 17 | 18 | else 19 | { 20 | int a = st.top(); 21 | st.pop(); 22 | int p,z; 23 | if(a>x){ 24 | p=a; 25 | z=x; 26 | } 27 | else{ 28 | p=x; 29 | z=a; 30 | } 31 | insert_at_bottom(z); 32 | st.push(p); 33 | } 34 | } 35 | 36 | void reverse() 37 | { 38 | if(st.size()>0) 39 | { 40 | int x = st.top(); 41 | st.pop(); 42 | reverse(); 43 | insert_at_bottom(x); 44 | } 45 | } 46 | 47 | int main() 48 | { 49 | st.push(11); 50 | st.push(2); 51 | st.push(32); 52 | st.push(3); 53 | st.push(41); 54 | reverse(); 55 | cout<<"Sorted Stack"< 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | stack S; 16 | 17 | int maximum_Area(vector &A){ 18 | int n=A.size(); 19 | int area=-1; 20 | int max_Area=-1; 21 | int i=0; 22 | while(i=A[S.top()]){ 24 | S.push(i); 25 | i++; 26 | } 27 | else{ 28 | int top=S.top(); 29 | S.pop(); 30 | if(S.empty()){ 31 | area=A[top]*i; 32 | } 33 | else{ 34 | area=A[top]*(i-S.top()-1); 35 | } 36 | max_Area=max(area,max_Area); 37 | } 38 | } 39 | while(!S.empty()){ 40 | int top=S.top(); 41 | S.pop(); 42 | if(S.empty()){ 43 | area=A[top]*i; 44 | } 45 | else{ 46 | area=A[top]*(i-S.top()-1); 47 | } 48 | max_Area=max(max_Area,area); 49 | } 50 | return max_Area; 51 | } 52 | 53 | 54 | 55 | int main() 56 | { 57 | vector v1={6,2,5,4,5,1,6}; 58 | cout< 5 | #include 6 | using namespace std; 7 | 8 | 9 | // Method 1: By using Stack : 10 | // Time :O(n) and Space O(n) 11 | int findMaxLen(string str) 12 | { 13 | int n = str.length(); 14 | stack S; 15 | S.push(-1); 16 | int result = 0; 17 | for (int i = 0; i < n; i++) 18 | { 19 | if (str[i] == '('){ 20 | S.push(i); 21 | } 22 | else{ 23 | if (!S.empty()) S.pop(); 24 | if (!S.empty()) result = max(result, i - S.top()); 25 | else S.push(i); 26 | } 27 | } 28 | return result; 29 | } 30 | 31 | // Method 2: By taking two pointers left and right and traversing first from left to right and then from right to left. 32 | int MaximumLengthSubs(string s) 33 | { 34 | int n=s.size(); 35 | int left = 0, right = 0, maxlength = 0; 36 | for (int i = 0; i < n; i++) 37 | { 38 | 39 | if (s[i] == '(') 40 | left++; 41 | else 42 | right++; 43 | 44 | if (left == right) 45 | maxlength = max(maxlength, 2 * right); 46 | else if (right > left) 47 | left = right = 0; 48 | } 49 | 50 | left = right = 0; 51 | for (int i = n - 1; i >= 0; i--) { 52 | if (s[i] == '(') 53 | left++; 54 | else 55 | right++; 56 | if (left == right) 57 | maxlength = max(maxlength, 2 * left); 58 | else if (left > right) 59 | left = right = 0; 60 | } 61 | return maxlength; 62 | } 63 | 64 | int main() 65 | { 66 | string str = "()))()()"; 67 | cout << findMaxLen(str) << endl; 68 | cout << MaximumLengthSubs("()))()()()"); 69 | return 0; 70 | } 71 | 72 | 73 | -------------------------------------------------------------------------------- /06-Stack/14-expression_contain_redundant_brackets.cpp: -------------------------------------------------------------------------------- 1 | // Stack: Expression contains redundant bracket or not 2 | // https://www.geeksforgeeks.org/expression-contains-redundant-bracket-not/ 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | bool FindRedundant(string A){ 10 | int n=A.size(); 11 | stack S; 12 | for(int i=0;i 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | vector prevSmaller(vector &A) { 18 | int n=A.size(); 19 | stack S; 20 | vector smaller(n,-1); 21 | int i=0; 22 | while(iA[i]) 30 | S.pop(); 31 | else 32 | { 33 | int x = S.top(); 34 | smaller[i]=A[x]; 35 | S.push(i); 36 | i++; 37 | } 38 | } 39 | return smaller; 40 | } 41 | 42 | int main(){ 43 | vector v1={34, 35, 27, 42, 5, 28, 39, 20, 28}; 44 | auto v2= prevSmaller(v1); 45 | for(auto it=v2.begin();it!=v2.end();it++){ 46 | cout<<*it<<" "; 47 | } 48 | cout< 4 | 5 | using namespace std; 6 | class Queue{ 7 | public: 8 | int front, rear, size; 9 | int capacity; 10 | int *arr; 11 | }; 12 | 13 | Queue* Create_Queue(int capacity){ 14 | Queue* queue= new Queue(); 15 | queue->capacity= capacity; 16 | queue->front=queue->size=0; 17 | queue->rear=capacity-1; 18 | queue->arr= new int[queue->capacity]; 19 | return queue; 20 | } 21 | 22 | int isFull(Queue* queue){ 23 | return (queue->size==queue->capacity); 24 | } 25 | 26 | int isEmpty(Queue* queue){ 27 | return (queue->size==0); 28 | } 29 | 30 | void enqueue(Queue* queue, int value){ 31 | if(isFull(queue)) 32 | return; 33 | queue->rear=(queue->rear+1)%queue->capacity; 34 | queue->arr[queue->rear]=value; 35 | cout<<"ENQUE: "<< value<size++; 37 | } 38 | 39 | int dequeue(Queue* queue){ 40 | if(isEmpty(queue)) 41 | return NULL; 42 | int value=queue->arr[queue->front]; 43 | queue->front=(queue->front+1)%queue->capacity; 44 | queue->size=queue->size-1; 45 | return value; 46 | } 47 | 48 | int front(Queue* queue){ 49 | if(isEmpty(queue)){ 50 | return NULL; 51 | } 52 | return queue->arr[queue->front]; 53 | } 54 | 55 | int rear (Queue* queue){ 56 | if(isEmpty(queue)) 57 | return NULL; 58 | return queue->arr[queue->rear]; 59 | } 60 | 61 | 62 | int main(){ 63 | Queue* queue= Create_Queue(100); 64 | enqueue(queue, 1); 65 | enqueue(queue, 2); 66 | enqueue(queue, 3); 67 | cout<<"DEQUED: "< 5 | #include 6 | 7 | using namespace std; 8 | class Stack{ 9 | int n; 10 | queue q1; 11 | queue q2; 12 | public: 13 | void push(int value); 14 | int pop(); 15 | int top(){ 16 | return q1.front(); 17 | } 18 | int size(){ 19 | return n; 20 | } 21 | }; 22 | 23 | void Stack::push(int value){ 24 | q2.push(value); 25 | n++; 26 | while(!q1.empty()){ 27 | q2.push(q1.front()); 28 | q1.pop(); 29 | } 30 | queue temp=q1; 31 | q1=q2; 32 | q2=temp; 33 | cout<<"Value is pushed :"< 5 | //#include 6 | using namespace std; 7 | class Node{ 8 | public: 9 | int data; 10 | Node *next; 11 | }; 12 | class Queue: public Node{ 13 | public: 14 | Node* front=NULL; 15 | Node* rear=NULL; 16 | void Enqueue(int x); 17 | void Dequeue(); 18 | int Front(){ 19 | return front->data; 20 | } 21 | void Print(); 22 | }; 23 | 24 | void Queue::Enqueue(int x){ 25 | Node *temp=new Node(); 26 | temp->data=x; 27 | temp->next=NULL; 28 | if(front==NULL && rear==NULL){ 29 | front=rear=temp; 30 | return; 31 | } 32 | rear->next=temp; // storing the address of the next pointer to be attached 33 | rear=rear->next; // moving rear to the newly created Node 34 | delete temp; 35 | } 36 | 37 | void Queue::Dequeue(){ 38 | Node *temp=front; 39 | if(front==NULL){ 40 | return ; 41 | } 42 | if(front==rear){ 43 | front=rear=NULL; 44 | } 45 | else{ 46 | front=front->next; 47 | } 48 | delete temp; 49 | } 50 | void Queue::Print() { 51 | Node* temp = front; 52 | while(temp != NULL) { 53 | cout<data<<" "; 54 | temp = temp->next; 55 | } 56 | cout< 4 | #include 5 | 6 | using namespace std; 7 | class Queue{ 8 | int n; 9 | stack S1; 10 | stack S2; 11 | public: 12 | void Enque(int value); 13 | int Deque(); 14 | int front(){ 15 | return S1.top(); 16 | } 17 | int size(){ 18 | return n; 19 | } 20 | }; 21 | 22 | void Queue::Enque(int value){ 23 | cout<<"Value Pushed Inside the Queue: "< temp=S2; 37 | S2=S1; 38 | S1=temp; 39 | return value; 40 | } 41 | 42 | int main(){ 43 | Queue Q1; 44 | Q1.Enque(1); 45 | Q1.Enque(2); 46 | Q1.Enque(3); 47 | Q1.Enque(4); 48 | cout<<"DeQUED: "< 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | queue reverse(queue Q){ 12 | stack ans; 13 | while(!Q.empty()){ 14 | int data=Q.front(); 15 | Q.pop(); 16 | ans.push(data); 17 | } 18 | while(!ans.empty()){ 19 | int data=ans.top(); 20 | ans.pop(); 21 | Q.push(data); 22 | } 23 | return Q; 24 | } 25 | 26 | 27 | int main(){ 28 | queue Q1; 29 | Q1.push(1); 30 | Q1.push(2); 31 | Q1.push(3); 32 | queue V1=reverse(Q1); 33 | cout<<"Reversed Queue "<<" "; 34 | while (!V1.empty()) { 35 | cout< 15 | #include 16 | #include 17 | 18 | using namespace std; 19 | 20 | queue reverse(queue Q, int count){ 21 | stack ans; 22 | queue Final; 23 | int val=0; 24 | while(!Q.empty() && val Q1; 46 | Q1.push(1); 47 | Q1.push(2); 48 | Q1.push(3); 49 | Q1.push(4); 50 | Q1.push(5); 51 | queue V1=reverse(Q1,3); 52 | cout<<"Reversed Queue "<<" "; 53 | while (!V1.empty()) { 54 | cout< 16 | #include 17 | #include 18 | 19 | using namespace std; 20 | 21 | queue interleave(queue Q){ 22 | queue Q1; 23 | queue Q2; 24 | int count=0; 25 | int n=Q.size(); 26 | while(count Q1; 52 | Q1.push(11); 53 | Q1.push(12); 54 | Q1.push(13); 55 | Q1.push(14); 56 | Q1.push(15); 57 | Q1.push(16); 58 | Q1.push(17); 59 | Q1.push(18); 60 | Q1.push(19); 61 | Q1.push(20); 62 | // Q1.push(5); 63 | queue V1=interleave(Q1); 64 | cout<<"Interleaved Queue is "<<" "; 65 | while (!V1.empty()) { 66 | cout< 5 | #include 6 | using namespace std; 7 | 8 | class Node { 9 | public: 10 | int data; 11 | Node* left; 12 | Node* right; 13 | Node *CreateNode(int data); 14 | Node *InsertNode(Node* root, int data); 15 | void print_Node(Node *root); 16 | int height(Node* root); 17 | }; 18 | 19 | Node* Node::CreateNode(int data) 20 | { 21 | Node* newNode = new Node(); 22 | if (!newNode) { 23 | return NULL; 24 | } 25 | newNode->data = data; 26 | newNode->left = newNode->right = NULL; 27 | return newNode; 28 | } 29 | 30 | 31 | 32 | void Node::print_Node(Node *temp) 33 | { 34 | if (temp == NULL) 35 | return; 36 | 37 | print_Node(temp->left); 38 | cout << temp->data << " "; 39 | print_Node(temp->right); 40 | } 41 | 42 | int Node::height(Node* root){ 43 | if(root==NULL){ 44 | return 0; 45 | } 46 | else{ 47 | int leftHeight=height(root->left); 48 | int rightHeight=height(root->right); 49 | return 1 + max(leftHeight, rightHeight); 50 | } 51 | } 52 | 53 | int main() 54 | { 55 | /* 56 | Binary Tree 57 | 1 58 | / \ 59 | 2 3 60 | / / \ 61 | 4 5 6 62 | 63 | */ 64 | Node BT; 65 | Node* root = BT.CreateNode(1); 66 | root->left = BT.CreateNode(2); 67 | root->left->left = BT.CreateNode(3); 68 | root->right = BT.CreateNode(4); 69 | root->right->left = BT.CreateNode(5); 70 | root->right->right = BT.CreateNode(6); 71 | cout<<"Tree :"; 72 | BT.print_Node(root); 73 | cout << endl; 74 | cout<<"height of Tree: "< 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | class Node { 11 | 12 | public: 13 | int data; 14 | Node* left; 15 | Node* right; 16 | Node *CreateNode(int data); 17 | Node *InsertNode(Node* root, int data); 18 | void leftView(Node* root, int level, int &last_level); 19 | void leftView(Node* root); 20 | }; 21 | 22 | Node* Node::CreateNode(int data) 23 | { 24 | Node* newNode = new Node(); 25 | if (!newNode) { 26 | return NULL; 27 | } 28 | newNode->data = data; 29 | newNode->left = newNode->right = NULL; 30 | return newNode; 31 | } 32 | 33 | void Node::leftView(Node* root, int level, int &last_level) 34 | { 35 | if (root == nullptr) { 36 | return; 37 | } 38 | if (last_level < level) 39 | { 40 | cout << root->data << " "; 41 | last_level = level; 42 | } 43 | leftView(root->left, level + 1, last_level); 44 | leftView(root->right, level + 1, last_level); 45 | } 46 | 47 | void Node::leftView(Node* root) 48 | { 49 | int last_level = 0; 50 | leftView(root, 1, last_level); 51 | } 52 | 53 | int main() 54 | { 55 | /* 56 | Binary Tree 57 | 1 58 | / \ 59 | 2 3 60 | / \ / \ 61 | 4 5 6 7 62 | 63 | */ 64 | 65 | Node BT; 66 | Node* root = BT.CreateNode(1); 67 | root->left = BT.CreateNode(2); 68 | root->right = BT.CreateNode(3); 69 | root->left->right = BT.CreateNode(4); 70 | root->left->right->right = BT.CreateNode(5); 71 | root->left->right->right->right=BT.CreateNode(6); 72 | cout<<"Left View of Tree: "; 73 | BT.leftView(root); 74 | cout< 4 | 5 | using namespace std; 6 | 7 | class Node { 8 | 9 | public: 10 | int data; 11 | Node* left; 12 | Node* right; 13 | Node *CreateNode(int data); 14 | Node *InsertNode(Node* root, int data); 15 | void invert(Node* &root); 16 | void inorder(Node* root); 17 | }; 18 | 19 | Node *temp=NULL; 20 | Node* Node::CreateNode(int data) 21 | { 22 | Node* newNode = new Node(); 23 | if (!newNode) { 24 | return NULL; 25 | } 26 | newNode->data = data; 27 | newNode->left = newNode->right = NULL; 28 | return newNode; 29 | } 30 | 31 | void Node::invert(Node* &root){ 32 | if(root==NULL){ 33 | return; 34 | } 35 | invert(root->left); 36 | invert(root->right); 37 | Node* temp=root->left; 38 | root->left=root->right; 39 | root->right=temp; 40 | } 41 | 42 | void Node::inorder(Node* root) 43 | { 44 | if (root == NULL) 45 | return; 46 | inorder(root->left); 47 | cout <<" "<< root->data; 48 | inorder(root->right); 49 | } 50 | 51 | 52 | int main() 53 | { 54 | /* 55 | 1 56 | / \ 57 | 2 3 58 | / \ / \ 59 | 4 5 6 7 60 | 61 | 62 | */ 63 | Node BT; 64 | Node* root = BT.CreateNode(1); 65 | root->left = BT.CreateNode(2); 66 | root->right = BT.CreateNode(3); 67 | root->left->left = BT.CreateNode(4); 68 | root->left->right= BT.CreateNode(5); 69 | root->right->left=BT.CreateNode(6); 70 | root->right->right=BT.CreateNode(7); 71 | BT.inorder(root); 72 | BT.invert(root); 73 | cout< 5 | 6 | using namespace std; 7 | 8 | class BST { 9 | 10 | public: 11 | int data; 12 | BST* left; 13 | BST* right; 14 | BST(){}; 15 | BST(int value){ 16 | data=value; 17 | left=right=NULL; 18 | } 19 | BST *CreateBST(int data); 20 | BST *InsertBST(BST* root, int data); 21 | void inorder(BST* root); 22 | 23 | }; 24 | 25 | BST* BST::InsertBST(BST* root, int data) 26 | { 27 | if(root==NULL){ 28 | return new BST(data); 29 | } 30 | if(data>root->data){ 31 | root->right=InsertBST(root->right, data); 32 | } 33 | else{ 34 | root->left=InsertBST(root->left, data); 35 | } 36 | return root; 37 | } 38 | 39 | void BST::inorder(BST *root){ 40 | if(root==NULL){ 41 | return; 42 | } 43 | inorder(root->left); 44 | cout<data<right); 46 | } 47 | 48 | int main() 49 | { 50 | /* 51 | 100 52 | / \ 53 | 50 120 54 | / \ / \ 55 | 30 60 110 160 56 | 57 | 58 | */ 59 | BST BT; 60 | BST* root = BT.InsertBST(root, 100); 61 | BT.InsertBST(root, 50); 62 | BT.InsertBST(root, 30); 63 | BT.InsertBST(root, 60); 64 | BT.InsertBST(root, 120); 65 | BT.InsertBST(root, 160); 66 | BT.InsertBST(root, 110); 67 | BT.inorder(root); 68 | } 69 | -------------------------------------------------------------------------------- /09-Binary Search Trees/Screenshot 2022-02-04 at 3.24.50 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshay-varshney/Data-Strcutures-and-Algorithms-Questions/173b57e23ef94aceeaa8079c73e9bf315167abb2/09-Binary Search Trees/Screenshot 2022-02-04 at 3.24.50 PM.png -------------------------------------------------------------------------------- /10-Heaps/01-Building_heap_from_Array.cpp: -------------------------------------------------------------------------------- 1 | // Heap: Max heap Implementation (Heapify) 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // 8 | //Parent=i 9 | //leftchild= 2*i+1 10 | //rightchild= 2*i+2 11 | 12 | 13 | void heapify(int arr[], int n, int i){ 14 | int largest=i; 15 | int left= 2*i+1; 16 | int right= 2*i+2; 17 | // Find the largest from the left 18 | if(left< n && arr[left] > arr[largest]){ 19 | largest=left; 20 | } 21 | // finding the largest from the right 22 | if(right arr[largest]){ 23 | largest=right; 24 | } 25 | // if we found the largest then swap the elements and call the heapify property recrsively. 26 | if(largest != i){ 27 | swap(arr[i], arr[largest]); 28 | heapify(arr, n, largest); 29 | } 30 | } 31 | 32 | void buildHeap(int arr[], int n){ 33 | int start= (n/2)-1; 34 | //Perform reverse level order traversal from last non-leaf node and heapify each node 35 | for(int i=start; i>=0;i--){ 36 | heapify(arr, n, i); 37 | } 38 | } 39 | 40 | void Print(int arr[], int n){ 41 | for(int i=0; i 5 | #include 6 | 7 | using namespace std; 8 | 9 | void heapify(vector &A, int n, int current){ 10 | int largest=current; 11 | int left= 2*current+1; 12 | int right= 2*current+2; 13 | if(left< n && A[left] > A[largest]) 14 | largest=left; 15 | 16 | if(right A[largest]) 17 | largest=right; 18 | 19 | if(largest != current) 20 | { 21 | swap(A[current], A[largest]); 22 | heapify(A, n, largest); 23 | } 24 | } 25 | 26 | void buildHeap(vector &A, int n){ 27 | int start= (n/2)-1; 28 | for(int i=start; i>=0;i--){ 29 | heapify(A, n, i); 30 | } 31 | } 32 | 33 | void heapSort(vector &A, int n) { 34 | buildHeap(A, n); 35 | for(int i=n-1; i>0;i--){ 36 | swap(A[0], A[i]); 37 | heapify(A, i, 0); 38 | } 39 | } 40 | 41 | void Print(vector &A, int n){ 42 | for(int i=0; i A = { 1, 3, 4, 14, 15, 16, 7}; 59 | int n = sizeof(A) / sizeof(A[0]); 60 | cout<<"Array is "; 61 | Print(A, n); 62 | cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | void MaxHeapify(vector &A, int i, int n) 10 | { 11 | int l = 2*i + 1; 12 | int r = 2*i + 2; 13 | int largest = i; 14 | if (l < n && A[l] > A[i]) 15 | largest = l; 16 | if (r < n && A[r] > A[largest]) 17 | largest = r; 18 | if (largest != i) 19 | { 20 | swap(A[i], A[largest]); 21 | MaxHeapify(A, largest, n); 22 | } 23 | } 24 | 25 | void convertmintomaxHeap(vector &A, int n){ 26 | int start= (n/2)-1; 27 | for(int i=start; i>=0;i--){ 28 | MaxHeapify(A, i, n); 29 | } 30 | } 31 | 32 | void Print(vector &A, int n){ 33 | for(int i=0; i A = { 3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; 42 | int n = A.size(); 43 | cout<<"Min Heap is: "; 44 | Print(A, n); 45 | convertmintomaxHeap(A, n); 46 | cout<<"Max Heap is: "; 47 | Print(A, n); 48 | } 49 | -------------------------------------------------------------------------------- /10-Heaps/08-Merge_two_MaxHeaps.cpp: -------------------------------------------------------------------------------- 1 | // Heap: Merge two Binary Max Heaps 2 | //https://www.geeksforgeeks.org/merge-two-binary-max-heaps/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | void MaxHeapify(std::vector &A, int i, int n) 10 | { 11 | int l = 2*i + 1; 12 | int r = 2*i + 2; 13 | int largest = i; 14 | if (l < n && A[l] > A[i]) 15 | largest = l; 16 | if (r < n && A[r] > A[largest]) 17 | largest = r; 18 | if (largest != i) 19 | { 20 | std::swap(A[i], A[largest]); 21 | MaxHeapify(A, largest, n); 22 | } 23 | } 24 | 25 | void Print(std::vector &A, int n){ 26 | for(int i=0; i mergeHeaps(std::vector &a, std::vector &b, int n, int m) 33 | { 34 | std::vector ans; 35 | for(int i=0; i=0;i--){ 43 | MaxHeapify(ans, i, m+n); 44 | } 45 | return ans; 46 | } 47 | 48 | int main() 49 | { 50 | std::vector A = { 10,5,6,2}; 51 | int n = A.size(); 52 | std::cout<<"Max Heap1 is: "; 53 | Print(A, n); 54 | std::vector B = { 12,7,9}; 55 | int m = B.size(); 56 | std::cout<<"Max Heap2 is: "; 57 | Print(B, m); 58 | auto V2=mergeHeaps(A, B, n, m); 59 | std::cout<<"Merged Max Heap is: "; 60 | Print(V2, m+n); 61 | } 62 | 63 | 64 | -------------------------------------------------------------------------------- /11-Graphs/01-Adjacency_LIst_Representation_of_Graph.cpp: -------------------------------------------------------------------------------- 1 | // Graph: Graph representation using Adjacency List 2 | // https://www.geeksforgeeks.org/graph-and-its-representations/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // A utility function to add an edge in an 10 | // undirected graph. 11 | void addEdge(vector adj[], int u, int v) 12 | { 13 | adj[u].push_back(v); 14 | adj[v].push_back(u); 15 | } 16 | 17 | // A utility function to print the adjacency list 18 | // representation of graph 19 | void printGraph(vector adj[], int V) 20 | { 21 | for (int v = 0; v < V; ++v) { 22 | cout << "\n Adjacency list of vertex " << v 23 | << "\n head "; 24 | for (auto x : adj[v]) 25 | cout << "-> " << x; 26 | printf("\n"); 27 | } 28 | } 29 | 30 | // Driver code 31 | int main() 32 | { 33 | int V = 5; 34 | vector adj[V]; 35 | addEdge(adj, 0, 1); 36 | addEdge(adj, 0, 4); 37 | addEdge(adj, 1, 2); 38 | addEdge(adj, 1, 13); 39 | addEdge(adj, 1, 4); 40 | addEdge(adj, 2, 13); 41 | addEdge(adj, 13, 4); 42 | printGraph(adj, V); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /11-Graphs/02-BFS_Traversal_of_GRAPH.cpp: -------------------------------------------------------------------------------- 1 | // Graphs: BFS Traversal of Graph 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Graph 9 | { 10 | int V; 11 | vector *adj; 12 | public: 13 | Graph(int v); 14 | void addEdge(int v, int w); 15 | void BFS(int s); 16 | }; 17 | 18 | Graph::Graph(int v) 19 | { 20 | V = v; 21 | adj = new vector[V]; 22 | } 23 | 24 | void Graph::addEdge(int v, int w) 25 | { 26 | adj[v].push_back(w); 27 | } 28 | 29 | void Graph::BFS(int s) 30 | { 31 | vector visited{V}; 32 | for(int i = 0; i < V; i++) 33 | visited[i] = false; 34 | queue Q; 35 | visited[s] = true; 36 | Q.push(s); 37 | while(!Q.empty()) 38 | { 39 | s = Q.front(); 40 | cout << s << " "; 41 | Q.pop(); 42 | 43 | // Get all adjacent vertices of the dequeued 44 | // vertex s. If a adjacent has not been visited, 45 | // then mark it visited and enqueue it 46 | for (auto i = adj[s].begin(); i != adj[s].end(); ++i) 47 | { 48 | if (visited[*i]==false) 49 | { 50 | visited[*i] = true; 51 | Q.push(*i); 52 | } 53 | } 54 | } 55 | } 56 | 57 | 58 | int main() 59 | { 60 | /* 61 | 0 62 | / \ 63 | 1 2 64 | | \ | 65 | 3 - 4 66 | \ / 67 | 5 68 | */ 69 | Graph g(6); 70 | g.addEdge(0, 1); 71 | g.addEdge(0, 2); 72 | g.addEdge(1, 3); 73 | g.addEdge(1, 4); 74 | g.addEdge(3, 4); 75 | g.addEdge(3, 5); 76 | g.addEdge(4, 5); 77 | cout << " Breadth First Traversal starting from vertex 0): "; 78 | g.BFS(0); 79 | cout< 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Graph 11 | { 12 | int V; 13 | vector *adj; 14 | vector visited{V}; 15 | public: 16 | Graph(int v); 17 | void addEdge(int v, int w); 18 | void DFS(int s); 19 | }; 20 | 21 | Graph::Graph(int v) 22 | { 23 | V = v; 24 | adj = new vector[V]; 25 | for(int i = 0; i < V; i++) 26 | visited[i] = false; 27 | } 28 | 29 | void Graph::addEdge(int v, int w) 30 | { 31 | adj[v].push_back(w); 32 | } 33 | 34 | void Graph::DFS(int s) 35 | { 36 | visited[s] = true; 37 | cout << s << " "; 38 | for (auto i = adj[s].begin(); i != adj[s].end(); ++i) 39 | { 40 | if (visited[*i]==false) 41 | { 42 | visited[*i] = true; 43 | DFS(*i); 44 | } 45 | } 46 | } 47 | 48 | 49 | 50 | int main() 51 | { 52 | /* 53 | 0 54 | / \ 55 | 1 2 56 | | \ | 57 | 3 - 4 58 | \ / 59 | 5 60 | */ 61 | Graph g(6); 62 | g.addEdge(0, 1); 63 | g.addEdge(0, 2); 64 | g.addEdge(1, 3); 65 | g.addEdge(1, 4); 66 | g.addEdge(3, 4); 67 | g.addEdge(3, 5); 68 | g.addEdge(4, 5); 69 | cout << " Depth First Traversal starting from vertex 0: "; 70 | g.DFS(0); 71 | cout< 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | //Definition for a Node. 11 | class Node { 12 | public: 13 | int val; 14 | vector neighbors; 15 | Node() { 16 | val = 0; 17 | neighbors = vector(); 18 | } 19 | Node(int _val) { 20 | val = _val; 21 | neighbors = vector(); 22 | } 23 | Node(int _val, vector _neighbors) { 24 | val = _val; 25 | neighbors = _neighbors; 26 | } 27 | }; 28 | 29 | 30 | class Solution { 31 | public: 32 | public: 33 | Node* dfs(Node* cur,unordered_map& mp) 34 | { 35 | vector neighbour; 36 | Node* clone=new Node(cur->val); 37 | mp[cur]=clone; 38 | for(auto it:cur->neighbors) 39 | { 40 | if(mp.find(it)!=mp.end()) //already clone and stored in map 41 | { 42 | neighbour.push_back(mp[it]); //directly push back the clone node from map to neigh 43 | } 44 | else 45 | neighbour.push_back(dfs(it,mp)); 46 | } 47 | clone->neighbors=neighbour; 48 | return clone; 49 | } 50 | Node* cloneGraph(Node* node) { 51 | unordered_map mp; 52 | if(node==NULL) 53 | return NULL; 54 | if(node->neighbors.size()==0) //if only one node present no neighbors 55 | { 56 | Node* clone= new Node(node->val); 57 | return clone; 58 | } 59 | return dfs(node,mp); 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /11-Graphs/09-Number_of_operations_to_make_network_connected.cpp: -------------------------------------------------------------------------------- 1 | // Graphs:Number of Operations to Make Network Connected 2 | //https://leetcode.com/problems/number-of-operations-to-make-network-connected/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | //Definition for a Node. 10 | void dfs(vector>& graph, int i,vector& visited) 11 | { 12 | visited[i]=1; 13 | for(auto it:graph[i]){ 14 | if(!visited[it]) { 15 | dfs(graph,it,visited); 16 | } 17 | } 18 | } 19 | 20 | int makeConnected(int n, vector>& connections) { 21 | if(connections.size()> graph(n); 24 | 25 | for(auto &c: connections){ 26 | graph[c[0]].push_back(c[1]); 27 | graph[c[1]].push_back(c[0]); 28 | } 29 | 30 | int cnt=0; 31 | vector visited(n,0); 32 | for(int i=0;i> connections= {{0,1},{0,2},{1,2}}; 45 | cout<<"Number of Operations to Make Network Connected: "< 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Graph 11 | { 12 | int V=0; 13 | vector *adj; 14 | public: 15 | Graph(int v); 16 | void addEdge(int v, int w); 17 | bool dfs_cycle(vector *adj, int node, vector& visited); 18 | bool canFinish(int numTasks); 19 | }; 20 | 21 | Graph::Graph(int v) 22 | { 23 | V = v; 24 | adj = new vector[V]; 25 | } 26 | 27 | void Graph::addEdge(int v, int w) 28 | { 29 | adj[v].push_back(w); 30 | } 31 | 32 | 33 | bool Graph::dfs_cycle(vector *adj, int node, vector& visited) 34 | { 35 | if (visited[node]) 36 | return false; 37 | visited[node] = true; 38 | for (int it : adj[node]) 39 | if (visited[it] || dfs_cycle(adj, it, visited)) 40 | return true; 41 | return visited[node] = false; 42 | } 43 | 44 | 45 | bool Graph::canFinish(int numTasks) 46 | { 47 | vector onpath(numTasks, false); 48 | vector visited(numTasks, false); 49 | for (int i = 0; i < numTasks; i++) 50 | if (!visited[i] && dfs_cycle(adj, i, visited)) 51 | return false; 52 | return true; 53 | } 54 | 55 | //Time: O(V+E) 56 | 57 | int main() 58 | { 59 | 60 | Graph g1(4); 61 | g1.addEdge(1, 0); 62 | g1.addEdge(2, 1); 63 | g1.addEdge(3, 2); 64 | cout<<"This can Finish the Work: "< 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | void mark_current_island(vector> &A,int x,int y,int r,int c) 11 | { 12 | if(x<0 || x>=r || y<0 || y>=c || A[x][y]!=1) 13 | return; 14 | 15 | A[x][y] = 2; 16 | mark_current_island(A,x+1,y,r,c); //DOWN 17 | mark_current_island(A,x,y+1,r,c); //RIGHT 18 | mark_current_island(A,x-1,y,r,c); //TOP 19 | mark_current_island(A,x,y-1,r,c); //LEFT 20 | } 21 | 22 | int numIslands(vector>& A) { 23 | 24 | int rows = A.size(); 25 | int cols = A[0].size(); 26 | int count = 0; 27 | for(int i=0;i> A={{1,1,0,0,0},{0,1,0,0,1},{1,0,0,1,1},{0,0,0,0,0},{1,0,1,0,1}}; 47 | cout< 4 | #include 5 | using namespace std; 6 | 7 | struct node { 8 | int parent; 9 | int rank; 10 | }; 11 | 12 | vector disjoint; 13 | 14 | int find(int v) 15 | { 16 | if(disjoint[v].parent==-1) 17 | return v; 18 | return disjoint[v].parent=find(disjoint[v].parent); //Path Compression 19 | } 20 | 21 | void union_op(int first,int second) 22 | { 23 | // if rank is different then we'll not change the rank 24 | if(disjoint[first].rank > disjoint[second].rank) //first has higher rank 25 | disjoint[second].parent = first; 26 | else if(disjoint[first].rank < disjoint[second].rank) //second has higher rank 27 | disjoint[first].parent = second; 28 | else 29 | { 30 | //Both have same rank and so anyone can be made as parent 31 | disjoint[first].parent = second; 32 | disjoint[second].rank +=1; //Increase rank of parent 33 | } 34 | } 35 | 36 | bool isCyclic(vector>& edge_List) 37 | { 38 | for(auto it= edge_List.begin(); it!=edge_List.end(); it++) 39 | { 40 | int first = find(it->first); //FIND absolute parent of subset 41 | int second = find(it->second); 42 | 43 | if(first == second) 44 | return true; 45 | 46 | //UNION operation 47 | union_op(first,second); //UNION of 2 sets 48 | } 49 | return false; 50 | } 51 | -------------------------------------------------------------------------------- /11-Graphs/16-Prim's_Minimum_Spanning_Tree.cpp: -------------------------------------------------------------------------------- 1 | // Graph: Prim's Minimum Spanning Tree Algorithm 2 | //https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int V; 10 | class Graph { 11 | vector > *edgelist; 12 | public: 13 | Graph(int V) { 14 | 15 | edgelist= new vector>(V); 16 | } 17 | void addEdge(int x, int y, int w) 18 | { 19 | (*edgelist)[x]={y, w }; 20 | (*edgelist)[y]={x, w}; 21 | } 22 | void primsMst(); 23 | }; 24 | 25 | void Graph::primsMst(){ 26 | vector key(V,INT_MAX); 27 | vector mstSet(V,false); 28 | vector parent(V); 29 | key[0]=0; 30 | parent[0]=-1; 31 | int ans=0; 32 | for(int i=0;i 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | 12 | int minSwaps1(vector arr, int n) 13 | { 14 | pair arrPos[n]; 15 | for (int i = 0; i < n; i++) 16 | { 17 | arrPos[i].first = arr[i]; 18 | arrPos[i].second = i; 19 | } 20 | // sort the pair according to the their values 21 | std::sort(arrPos, arrPos + n); 22 | // visited array to keep track of which elements are visited in array 23 | vector visited(n, false); 24 | 25 | // Initialize result 26 | int ans = 0; 27 | 28 | for (int i = 0; i < n; i++) 29 | { 30 | if (visited[i] || arrPos[i].second == i) 31 | continue; 32 | 33 | int value = 0; 34 | int j = i; 35 | // If elemenet is not visited then keep moving towards those unvisited indexes whose and find the cycle 36 | while (!visited[j]) 37 | { 38 | visited[j] = 1; 39 | 40 | j = arrPos[j].second; 41 | value++; 42 | } 43 | 44 | if (value > 0) 45 | { 46 | ans += (value - 1); 47 | } 48 | } 49 | return ans; 50 | } 51 | // Time: O(nlogn) 52 | // space: O(n) 53 | 54 | int main() 55 | { 56 | vector a = {2,8,5,4}; 57 | int n = a.size(); 58 | cout << minSwaps1(a, n); 59 | } 60 | 61 | -------------------------------------------------------------------------------- /11-Graphs/21-Snake_Ladder_Problem.cpp: -------------------------------------------------------------------------------- 1 | //Graph: Snake Ladder Problems 2 | //https://www.geeksforgeeks.org/snake-ladder-problem-2/ 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | struct Queue{ 12 | int V; 13 | int distance; 14 | }; 15 | 16 | int getMinthrow(vector & board){ 17 | int n=board.size(); 18 | vector visited(n,false); 19 | queue Q; 20 | visited[0]= true; 21 | Q.push({0,0}); 22 | while(!Q.empty()){ 23 | auto it=Q.front(); 24 | int vertex= it.V; 25 | if(vertex==n-1) 26 | break; 27 | Q.pop(); 28 | for(int i=vertex+1;i<=(vertex+6);i++){ 29 | if(visited[i]==false){ 30 | Queue temp; 31 | temp.distance = it.distance +1; 32 | visited[i]= true; 33 | if(board[i]!=-1) 34 | temp.V=board[i]; 35 | else 36 | temp.V= i; 37 | Q.push(temp); 38 | 39 | } 40 | } 41 | } 42 | return Q.front().distance ; 43 | } 44 | 45 | 46 | int main(){ 47 | int n=30; 48 | vector board(n,-1); 49 | board[2]=21; 50 | board[4]=7; 51 | board[10]=25; 52 | board[19]=28; 53 | board[26]=0; 54 | board[20]=8; 55 | board[16]=3; 56 | board[18]=6; 57 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | bool DFS(vector>& adj, int start, vector& visited, int last) 10 | { 11 | 12 | visited[start] = last; 13 | for(auto it: adj[start]) 14 | { 15 | if(visited[it] == -1) 16 | { 17 | int team = (last == 1? 2:1); 18 | DFS(adj, it, visited, team); 19 | } 20 | else 21 | { 22 | if(visited[it] == last) 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | void createTeams(vector> & A, int n, int size) // 5 30 | { 31 | vector> adj(n+1); 32 | for(int i = 0; i visited(n+1, -1); 38 | 39 | for(int i = 1; i<=n; i++) 40 | { 41 | if(visited[i] == -1) 42 | if(!DFS(adj, i, visited, 1)) 43 | { 44 | std::cout<<"Impossible"<> A = {{1, 2}, {1, 3}, {4, 5}}; 59 | createTeams(A, 5, 3); 60 | } 61 | -------------------------------------------------------------------------------- /12-BackTracking/01-Rat_in_Maze.cpp: -------------------------------------------------------------------------------- 1 | // BackTracking: Rat in Maze 2 | //https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/ 3 | 4 | 5 | #include 6 | #include 7 | 8 | 9 | using namespace std; 10 | 11 | bool isSafe(vector> A, int x, int y, int n){ 12 | if(x> A, int x, int y, int n, vector> &sol){ 18 | if(x==n-1 && y==n-1){ 19 | sol[x][y]=1; 20 | return true; 21 | } 22 | if(isSafe(A, x, y, n)){ 23 | sol[x][y]=1; 24 | if(ratinMaze(A, x+1, y, n, sol)) 25 | return true; 26 | if(ratinMaze(A, x, y+1, n, sol)) 27 | return true; 28 | sol[x][y]=0; 29 | return false; 30 | } 31 | else 32 | return false; 33 | } 34 | 35 | 36 | 37 | int main() 38 | { 39 | 40 | vector> A={{1, 0, 0, 0},{1, 1, 0, 1},{0, 1, 0, 0},{1, 1, 1, 1}}; 41 | vector> Solution={{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0}}; 42 | int n=A.size(); 43 | cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | bool isSafe(vector> &A, int x, int y, int n){ 11 | // check the row wise 12 | for(int r=0; r=0 && c>=0){ 20 | if(A[r][c]==1) 21 | return false; 22 | r--; 23 | c--; 24 | } 25 | r=x; 26 | c=y; 27 | // right diagonal 28 | while(r>=0 && c>=0){ 29 | if(A[r][c]==1) 30 | return false; 31 | r--; 32 | c++; 33 | } 34 | return true; 35 | } 36 | 37 | bool nQueen(vector>& A, int x, int n){ 38 | if(x>=n) 39 | return true; 40 | for(int i=0;i> A = {{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}}; 56 | int n=A.size(); 57 | if(nQueen(A, 0, A.size())){ 58 | for(int i=0;i 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | class Graph { 11 | int V; 12 | 13 | public: 14 | Graph(int V) { this->V = V; } 15 | void addEdge(vector> &graph, int u, int v){ 16 | graph[u].push_back(v); 17 | graph[v].push_back(u); 18 | } 19 | bool isSafe(vector>& graph, vector& color, int colorValue, int current); 20 | bool mColor(vector>& graph, vector& color, int m, int src); 21 | }; 22 | 23 | // check the current value is safe to place, just check the adjacent vertices 24 | bool Graph::isSafe(vector > &graph, vector &color, int colorValue, int current){ 25 | for(auto i:graph[current]){ 26 | if(color[i]==colorValue) 27 | return false; 28 | } 29 | return true; 30 | } 31 | 32 | bool Graph::mColor(vector > &graph, vector &color, int m, int src){ 33 | if(src==V) 34 | return true; 35 | 36 | for(int i=1;i<=m;i++){ 37 | if(isSafe(graph, color, i, src)){ 38 | color[src]=i; 39 | if(mColor(graph, color, m, src+1)==true) 40 | return true; 41 | color[src]=0; 42 | } 43 | } 44 | return false; 45 | } 46 | 47 | int main() 48 | { 49 | int V=5; 50 | vector> graph (V); 51 | Graph g(V); 52 | g.addEdge(graph, 0, 1); 53 | g.addEdge(graph, 1, 2); 54 | g.addEdge(graph, 2, 3); 55 | g.addEdge(graph, 3, 0); 56 | g.addEdge(graph, 0, 2); 57 | int m=2; 58 | vector color(V, 0); 59 | cout< 9 | #include 10 | using namespace std; 11 | 12 | // function to check palindrome 13 | bool checkPallindrome(string A, int start, int end){ 14 | while(start<=end){ 15 | if(A[start]!=A[end]) 16 | return false; 17 | start++; 18 | end--; 19 | } 20 | return true; 21 | } 22 | 23 | // Now 24 | void printAllPalindrome(string A, vector> &ans, vector &path, int ind){ 25 | // If this is the last partition and it comes out pallindrome then return 26 | if(ind==A.size()){ 27 | ans.push_back(path); 28 | return; 29 | } 30 | // from index till end of string, make partition and check if that partition makes the string pallindrome 31 | for(int i=ind; i> S; 45 | vector path; 46 | string A="NITIN"; 47 | printAllPalindrome(A, S, path, 0); 48 | for(int i=0;i 9 | #include 10 | using namespace std; 11 | 12 | // Method 1: Normal recurssion. 13 | int recurssionFibo(int n){ 14 | if(n<=1) 15 | return n; 16 | else 17 | return recurssionFibo(n-1)+ recurssionFibo(n-2); 18 | } 19 | 20 | 21 | // Method 2: by using Dynamic Programming and reusing the last result apart from calculating it again. 22 | int dpFibo(int n){ 23 | vector dp(n); 24 | dp[0]=0; 25 | dp[1]=1; 26 | for(int i=2; i<=n;i++){ 27 | dp[i]=dp[i-1]+dp[i-2]; 28 | } 29 | return dp[n]; 30 | } 31 | 32 | int main(){ 33 | int n=4; 34 | cout< 6 | #include 7 | using namespace std; 8 | 9 | // Finding the subset array 10 | void SubsetSumArray(vector& A, int Sum, int n, vector>& dp){ 11 | for(int i=0;i<=n;i++){ 12 | for(int j=0;j<=Sum;j++){ 13 | if(j==0) 14 | dp[i][j]=true; 15 | else if(i==0) 16 | dp[i][j]= false; 17 | else if(A[i-1]>j) 18 | dp[i][j]=dp[i-1][j]; 19 | else 20 | dp[i][j] = (dp[i-1][j] || dp[i-1][j-A[i-1]]); 21 | } 22 | } 23 | } 24 | 25 | // Steps: 26 | /* 27 | 1. Finding the Sum Range 28 | 2. Invalidating all the values from DP table whose subset is not possible. 29 | 3. If athe value of the subset is false then we'll not consider that as the subset array 30 | 4. Finding the mini in only Sum/2 and finding the minimum from (0 to sum/2) 31 | */ 32 | int minimumSubsetDiff(vector& A){ 33 | int n=A.size(); 34 | int Sum=0; 35 | for(int i=0; i> dp(n+1, vector (Sum+1)); 39 | SubsetSumArray(A, Sum, n, dp); 40 | int mini=INT_MAX; 41 | for(int i=0;i<=Sum/2; i++){ 42 | if(dp[n][i]==true) 43 | mini=min(mini, Sum- 2*i); 44 | } 45 | return mini; 46 | } 47 | 48 | int main(){ 49 | vector A={3, 1, 4, 2, 2, 1}; 50 | cout< 4 | #include 5 | using namespace std; 6 | 7 | 8 | int topDownSubset(vector& A, int n, int Sum, vector>& dp){ 9 | 10 | for(int i=0;i<=n;i++){ 11 | for(int j=0;j<=Sum;j++){ 12 | if(j==0 && i==0) 13 | dp[i][j]=1; 14 | else if(i==0 && j!=0) 15 | dp[i][j]=0; 16 | else if(j==0 && i!=0) 17 | dp[i][j]=1; 18 | else if(A[i-1]>j) 19 | dp[i][j]=dp[i-1][j]; 20 | else 21 | dp[i][j]=(dp[i-1][j] + dp[i-1][j-A[i-1]]); 22 | } 23 | } 24 | return dp[n][Sum]; 25 | } 26 | 27 | /* 28 | s1 - s2 = diff given 29 | s1 + s2=sum of array 30 | Adding both 31 | 2s1= diff + sum of array 32 | s1= (diff + sum of array)/2; 33 | 34 | */ 35 | int countWithGivenSum(vector& A, int n, int diff) 36 | { 37 | int Sum=0; 38 | for(int i=0;i> dp2(n+1, vector (Sum+1)); 45 | for(int i=0; i A={1,1,2,3}; 54 | int n=A.size(); 55 | int diff=1; 56 | cout< 7 | #include 8 | using namespace std; 9 | 10 | 11 | int topDownLCS(string A, string B, int n, int m, vector>& dp){ 12 | int re=0; 13 | for(int i=0;i<=n;i++){ 14 | for(int j=0;j<=m;j++){ 15 | if(j==0 || i==0) 16 | dp[i][j]=0; 17 | else if(A[i-1]==B[j-1]){ 18 | dp[i][j]=1+dp[i-1][j-1]; 19 | re= max(re, dp[i][j]); 20 | } 21 | else 22 | dp[i][j]=0; 23 | } 24 | } 25 | return re; 26 | } 27 | 28 | 29 | int main(){ 30 | string A= "abcdxyz"; 31 | string B= "abcd"; 32 | int n=A.size(); 33 | int m=B.size(); 34 | vector> dp2(n+1, vector (m+1)); 35 | for(int i=0; i<=n; i++){ 36 | for(int j=0;j<=m;j++){ 37 | dp2[i][j]=-1; 38 | } 39 | } 40 | cout< 5 | #include 6 | using namespace std; 7 | 8 | // Method 1: By using Recurssion, 9 | int matrixMultiplication(vector& A, int i, int j){ 10 | if(i>=j) 11 | return 0; 12 | int mini= INT_MAX; 13 | for(int k=i;k& A, int i, int j, vector>& dp){ 26 | if(i>=j) 27 | return 0; 28 | if(dp[i][j]!=-1) 29 | return dp[i][j]; 30 | int mini= INT_MAX; 31 | for(int k=i;k A={1,2,3,4}; 40 | int n=A.size(); 41 | cout<> dp(n+1, vector (n+1)); 44 | for(int i=0; i<=n; i++){ 45 | for(int j=0;j<=n;j++){ 46 | dp[i][j]=-1; 47 | } 48 | } 49 | cout< 17 | #include 18 | using namespace std; 19 | 20 | 21 | // Method 1: Recursive 22 | int recursivepair(int n){ 23 | if(n<=2) 24 | return n; 25 | return recursivepair(n-1)+ (n-1)*recursivepair(n-2); 26 | } 27 | // Time: (2^n) 28 | 29 | 30 | // Method 2: Memoization 31 | int memoization_pair(int n, vector& dp){ 32 | if(n<=2) 33 | return dp[n]=n; 34 | return dp[n]= memoization_pair(n-1, dp) + (n-1)*memoization_pair(n-2, dp); 35 | } 36 | 37 | // Method 3: Top Down 38 | int topdown_pair(int n, vector& dp){ 39 | for(int i=0;i<=n;i++) 40 | { 41 | if(i<=2) 42 | dp[i]=i; 43 | else 44 | dp[i]= dp[i-1]+(i-1)*dp[i-2]; 45 | } 46 | return dp[n]; 47 | } 48 | 49 | int main() { 50 | int n=4; 51 | cout<<"Recursive Value of pair: "< dp(n+1); 54 | for(int i=0; i dp2(n+1); 63 | for(int i=0; i