├── .github └── ISSUE_TEMPLATE │ └── feature_request.md ├── .gitignore ├── 2D Arrays (Matrix) ├── 2D_sorted.go ├── 2D_sorted_array.java ├── binary_search.cpp ├── count_negatives_in_sorted_matrix.cpp ├── matrix_diagonal_sum.cpp ├── matrix_wave_print.cpp ├── rotate_matrix.cpp ├── rotate_matrix.go ├── rotate_matrix.java ├── rotate_matrix.js ├── rotate_matrix.py ├── search_element.cpp ├── searching_in_sorted_array.cpp ├── searching_in_sorted_array.java ├── searching_in_sorted_array.js ├── searching_in_sorted_array.py ├── set_matrix_0.cpp ├── set_matrix_0.go ├── set_matrix_0.java ├── spiral_traverse.cpp ├── spiral_traverse.go ├── spiral_traverse.java ├── spiral_traverse.py ├── zigzag_traversal.cpp ├── zigzag_traversal.go ├── zigzag_traversal.java ├── zigzag_traversal.js └── zigzag_traversal.py ├── Arrays ├── Jobassign.cpp ├── Maximum_freq.py ├── Rotatedarr.cpp ├── array_of_products.cpp ├── array_of_products.go ├── array_of_products.java ├── array_of_products.js ├── array_of_products.py ├── ceaser_cipher.cpp ├── ceaser_cipher.go ├── ceaser_cipher.java ├── ceaser_cipher.js ├── ceaser_cipher.py ├── dutch_national_flag.cpp ├── dutch_national_flag.go ├── dutch_national_flag.java ├── dutch_national_flag.js ├── dutch_national_flag.py ├── find_three_largest_integers.js ├── find_three_largest_number.cpp ├── find_three_largest_numbers.go ├── find_three_largest_numbers.java ├── find_three_largest_numbers.py ├── first_duplicate_value.cpp ├── first_duplicate_value.go ├── first_duplicate_value.java ├── first_duplicate_value.js ├── first_duplicate_value.py ├── four_sum.py ├── insert_interval.cpp ├── insert_interval.go ├── insert_interval.java ├── insert_interval.js ├── insert_interval.py ├── insert_intervals.cpp ├── insert_intervals.go ├── is_monotonic.cpp ├── is_monotonic.go ├── is_monotonic.java ├── is_monotonic.js ├── is_monotonic.py ├── longest_peak.cpp ├── longest_peak.go ├── longest_peak.java ├── longest_peak.js ├── longest_peak.py ├── majority_element.go ├── majority_element.java ├── maximum_subarray_sum.cpp ├── maximum_subarray_sum.go ├── maximum_subarray_sum.py ├── merge_intervals.cpp ├── merge_intervals.go ├── merge_intervals.java ├── merge_intervals.js ├── merge_intervals.py ├── merge_sorted_array.cpp ├── merge_sorted_array.java ├── merge_sorted_arrays.py ├── minimum_size_subarray_sum.java ├── move_element_to_end.cpp ├── move_element_to_end.go ├── move_element_to_end.java ├── move_element_to_end.js ├── move_element_to_end.py ├── non-overlapping intervals.cpp ├── pallindromic_permutations.cpp ├── sign_of_the_product_of_an_array.cpp ├── smallest_difference.cpp ├── smallest_difference.go ├── smallest_difference.java ├── smallest_difference.js ├── smallest_difference.py ├── sorted_square_array,js ├── sorted_square_array.cpp ├── sorted_square_array.go ├── sorted_square_array.java ├── sorted_square_array.py ├── string_halves.cpp ├── three_largest_no.py ├── total_hamming_distance.cpp ├── tournament_winner.go ├── triplet_sum.cpp ├── triplet_sum.go ├── triplet_sum.java ├── triplet_sum.js ├── triplet_sum.py └── urlify.go ├── Backtracking ├── Generate_Parentheses.py ├── geenrate_parentheses.go ├── n_queen.cpp ├── n_queens.java └── sudoko_solver.java ├── Binary Search ├── BinarySearchRecursive.java ├── binary_search.cpp ├── binary_search.js ├── binary_search.py ├── binary_search_iterative.go ├── binary_search_recursive.go ├── binary_serach_first_and_last_occurence.py ├── first_and_last_pos.js ├── first_and_last_pos_of_element.cpp ├── first_and_last_position.java ├── first_last_pos.java ├── first_occurance.go ├── first_occurence.java ├── first_true.cpp ├── first_true.go ├── first_true.java ├── first_true.js ├── first_true.py ├── floor_of_target.java ├── index_position.java ├── infinity_array.java ├── last_occurance.go ├── median_of_two_sorted_arrays.cpp ├── median_of_two_sorted_arrays.js ├── minimum_in_rotated_sorted_array.cpp ├── perfect_square.java ├── search_in_rotated_sorted_array.cpp ├── search_in_sorted_rotated_array.cpp ├── search_in_sorted_rotated_array.go ├── search_in_sorted_rotated_array.java ├── search_in_sorted_rotated_array.py ├── search_insert_position.js └── square_root.java ├── Bit Manipulation ├── bloom_filter.cpp ├── bloom_filter.py ├── count_bits.go ├── interesting_array.java ├── mod_array.java ├── number_of_1_bits.java ├── parity_of_a_word.go ├── power_of_2.cpp ├── reduce_to_zero.cpp ├── setbits.cpp ├── single_number.java └── subarrays_with_bitwise_OR_1.java ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dynamic Programming ├── best_time_to_buy_and_sell_stock.cpp ├── best_time_to_buy_and_sell_stock.go ├── best_time_to_buy_and_sell_stock.java ├── best_time_to_buy_and_sell_stock.js ├── best_time_to_buy_and_sell_stock.py ├── climb_stairs.cpp ├── climb_stairs.go ├── climb_stairs.java ├── climb_stairs.js ├── climb_stairs.py ├── coin_change.cpp ├── coin_change.go ├── coin_change.java ├── coin_change.js ├── coin_change.py ├── dice_throws.go ├── disk_stacking.go ├── disk_stacking.py ├── distance_of_nearest_0.cpp ├── distance_of_nearest_0.py ├── distane_of_nearest_0.go ├── distane_of_nearest_0.java ├── distane_of_nearest_0.js ├── edit_distance_dp.cpp ├── edit_distance_dp.go ├── edit_distance_dp.java ├── edit_distance_dp.js ├── edit_distance_dp.py ├── edit_distance_memoized.cpp ├── edit_distance_recursive.cpp ├── house_robber.cpp ├── juice_bottling.cpp ├── juice_bottling.go ├── juice_bottling.java ├── juice_bottling.js ├── juice_bottling.py ├── knapsack.cpp ├── knapsack.go ├── knapsack.java ├── knapsack.js ├── knapsack.py ├── knight_probability_chessboard.cpp ├── knight_probability_chessboard.go ├── knight_probability_chessboard.java ├── knight_probability_chessboard.js ├── knight_probability_chessboard.py ├── kth_closest_point_to origin.java ├── largest_rectangle.java ├── largest_rectangle.js ├── largest_rectangle.py ├── longest_common_subsequence_dp.cpp ├── longest_common_subsequence_memoization.cpp ├── longest_common_subsequence_recursive.cpp ├── longest_increasing_subsequence.cpp ├── longest_pallindromic_substring.cpp ├── longest_pallindromic_substring.go ├── longest_pallindromic_substring.java ├── longest_pallindromic_substring.js ├── longest_pallindromic_substring.py ├── max_path_sum.go ├── max_sum_increasing_subsequence.cpp ├── max_sum_increasing_subsequence.go ├── max_sum_increasing_subsequence.java ├── max_sum_increasing_subsequence.js ├── max_sum_increasing_subsequence.py ├── maximal_sqaure.cpp ├── maximal_sqaure.go ├── maximal_sqaure.js ├── maximal_sqaure.py ├── maximal_square.java ├── min_cost_travel_in_a_grid.cpp ├── min_insertion_steps_for_string_palindrome.java ├── min_number_of_jumps.cpp ├── min_number_of_jumps.go ├── min_number_of_jumps.java ├── min_number_of_jumps.js ├── min_number_of_jumps.py ├── min_steps_to_make_string_palindrome.go ├── min_steps_to_make_string_palindrome.java ├── min_steps_to_make_string_palindrome.py ├── min_steps_to_make_string_pallindrome.cpp ├── min_steps_to_make_string_pallindrome.js ├── min_steps_to_reduce_a_number_to_one.cpp ├── num_ways_to_make_change.cpp ├── num_ways_to_make_change.go ├── num_ways_to_make_change.java ├── num_ways_to_make_change.js ├── num_ways_to_make_change.py ├── num_ways_to_traverse_graph.cpp ├── num_ways_to_traverse_graph.go ├── num_ways_to_traverse_graph.js ├── num_ways_to_traverse_graph.py ├── numbers_in_pi.go ├── reconstruct_bst_in_python.py ├── rod_cutting_problem_dp.cpp ├── rod_cutting_problem_memoized.cpp ├── rod_cutting_problem_recursive.cpp ├── trapping_rain_water.cpp ├── unique_paths_with_obstacles.cpp ├── wine_selling_problem_dp.cpp ├── wine_selling_problem_memoized.cpp └── wine_selling_problem_recursive.cpp ├── Famous Algorithms ├── N_queen.js ├── euclidean_algorithm.java ├── euclidean_algorithm.js ├── euclidean_algorithm.py ├── kadanes_algorithm.c++ ├── kadanes_algorithm.go ├── kadanes_algorithm.java ├── kadanes_algorithm.py ├── kadenes_algorithm.js ├── kmp.java ├── kmp.js └── kmp.py ├── Fast and Slow Pointers ├── happy_number.go ├── linked_list_compute_midpoint.cpp ├── linked_list_compute_midpoint.java ├── linked_list_find_middle.py ├── linked_list_floyds_cycle_detection.cpp └── linked_list_floyds_cycle_detection.py ├── Graphs ├── Diljstra.go ├── GraphBFS.java ├── Graph_Dijstra.java ├── Graphs_Dijkstras.py ├── Graphs_Ford_Fulkerson.cpp ├── Graphs_bfs.cpp ├── Graphs_bfs.js ├── Graphs_bfs.py ├── Graphs_bfs_sssp.cpp ├── Graphs_cycle_detection_bfs.cpp ├── Graphs_cycle_detection_dfs.cpp ├── Graphs_dfs.cpp ├── Graphs_dfs.java ├── Graphs_dfs.js ├── Graphs_dfs.py ├── Graphs_dfs_connected_components.cpp ├── Graphs_dijkstras.js ├── Graphs_flood_fill.cpp ├── Graphs_kill_process.cpp ├── Graphs_kruskals_algo.cpp ├── Graphs_kruskals_algorithm.js ├── Graphs_topological_sort_bfs.cpp ├── Graphs_topological_sort_dfs.cpp ├── a_star_algorithm.py ├── adjacency_list.java ├── adjacency_matrix.go ├── adjacency_matrix.java ├── dijkstras.cpp ├── dijkstras.go ├── dijkstras.java ├── dijkstras.py ├── dijkstras_heap_based.go ├── ford_fulkerson.cpp ├── graphs_adjacency_list.cpp ├── graphs_adjacency_list_generic.cpp ├── graphs_bfs.go ├── graphs_dfs.go ├── kruskals_algorithm.java ├── kruskals_algorithm.py ├── remove_island.go ├── river_sizes.cpp ├── river_sizes.go ├── river_sizes.java ├── river_sizes.js ├── river_sizes.py ├── single_cycle_check.cpp ├── single_cycle_check.go ├── single_cycle_check.java ├── single_cycle_check.js ├── single_cycle_check.py ├── snack_ladders.cpp ├── snack_ladders.js ├── snack_ladders.py ├── snakes_ladders.java ├── topological_sort.cpp ├── topological_sort.go ├── topological_sort.java ├── topological_sort.js ├── topological_sort.py ├── two_colorable.cpp ├── two_colorable.go ├── two_colorable.java ├── two_colorable.js ├── two_colorable.py ├── union_find.cpp ├── union_find.go ├── union_find.java ├── union_find.js ├── union_find.py ├── validate_bst.cpp ├── validate_bst.go ├── validate_bst.java ├── validate_bst.js ├── validate_bst.py ├── youngest_common_ancestor.cpp ├── youngest_common_ancestor.go ├── youngest_common_ancestor.java ├── youngest_common_ancestor.js └── youngest_common_ancestor.py ├── Greedy ├── coin_change.go ├── coin_change.java ├── coin_change.js ├── coin_change.py ├── task_assignment.cpp ├── task_assignment.go ├── task_assignment.java ├── task_assignment.js └── task_assignment.py ├── Hash Table ├── Bloomfilter.cpp ├── Convert an array to reduced form using hashing.cpp ├── Count_Pairs_of_Points_With_Distance_k.py ├── HashTable.java ├── Longest_substring_without_repeating_characters.py ├── Partition.java ├── Partition_string.py ├── add_first_missing_positive.cpp ├── add_first_missing_positive.java ├── find_optimal_partition_of_string.cpp ├── find_optimal_partition_of_string.go ├── first_duplicate_value.go ├── first_missing_positve.go ├── first_missing_positve.js ├── first_missing_positve.py ├── first_non_repeated_character.go ├── first_repeated_character.go ├── four_number_sum.java ├── frequency_of_elements.java ├── group_anagrams.class ├── group_anagrams.cpp ├── group_anagrams.go ├── group_anagrams.java ├── group_anagrams.js ├── group_anagrams.py ├── integer_to_roman.cpp ├── integer_to_roman.go ├── integer_to_roman.java ├── integer_to_roman.js ├── integer_to_roman.py ├── remove_duplicates.go ├── roman_to_integer.cpp ├── roman_to_integer.go ├── roman_to_integer.java ├── roman_to_integer.js ├── roman_to_integer.py ├── sum_of_unique_elements.java ├── three_number_sum.java ├── two_sum.cpp ├── two_sum.go ├── two_sum.java ├── two_sum.js ├── two_sum.py ├── zero_sum_subarray.cpp ├── zero_sum_subarray.go ├── zero_sum_subarray.java ├── zero_sum_subarray.js └── zero_sum_subarray.py ├── Heaps ├── heap.cpp ├── heap.go ├── heap.java ├── heap.js ├── heap.py └── k_closest.py ├── LICENSE ├── Linked List ├── Add_two_numbers.py ├── Intersection_LL.cpp ├── LFU_Cache.cpp ├── Linked_List_Component.java ├── MiddleOfLinkedList.java ├── MiddleofLL.py ├── RemoveKthNodeFromEnd.java ├── Remove_nth_node_from_end.java ├── add_two_numbers.cpp ├── add_two_numbers.js ├── delete_kth_node.js ├── double_linked_list.go ├── doubly_linked_list.cpp ├── doubly_linked_list.java ├── doubly_linked_list.js ├── floyds_cycle_detection.cpp ├── floyds_cycle_detection.go ├── floyds_cycle_detection.java ├── intersection_of_two_linked_lists.cpp ├── liniked_list_sort_list.cpp ├── linked_list.go ├── linked_list.js ├── linked_list.py ├── linked_list_add_two_numbers.py ├── linked_list_compute_middle.cpp ├── linked_list_compute_middle.java ├── linked_list_delete_at_any_pos.cpp ├── linked_list_delete_at_head.cpp ├── linked_list_delete_at_tail.cpp ├── linked_list_delete_node.go ├── linked_list_even_or_odd.go ├── linked_list_find_length.cpp ├── linked_list_insert_at_any_pos.cpp ├── linked_list_insert_at_head.cpp ├── linked_list_insert_at_tail.cpp ├── linked_list_kth_from_end.go ├── linked_list_kth_node_from_end.cpp ├── linked_list_linear_search.cpp ├── linked_list_merge_k_sorted_lists.cpp ├── linked_list_merge_two_sorted_linked_list.cpp ├── linked_list_mergesort_an_unsorted_list.cpp ├── linked_list_middle.go ├── linked_list_middle.js ├── linked_list_odd_even.cpp ├── linked_list_pallindrome.cpp ├── linked_list_recursive_search.cpp ├── linked_list_remove_dups.cpp ├── linked_list_remove_kth_node_from_end.py ├── linked_list_remove_nth_node_from_end.cpp ├── linked_list_remove_nth_node_from_end.py ├── linked_list_reverse.cpp ├── linked_list_reverse.js ├── linked_list_reverse_recursive.cpp ├── linked_list_sum_lists.cpp ├── linked_list_swap_nodes_in_pair.cpp ├── linked_list_swap_nodes_in_pair_iterative.cpp ├── linked_list_take_input.cpp ├── linked_list_take_input_as_array_operator_overloading.cpp ├── linked_list_take_input_operator_overloading.cpp ├── recursive and iterative in singly linkedlist.py ├── reverse_linked_list.go ├── reverse_linked_list.java ├── singly_linked_list.cpp ├── singly_linked_list.go ├── singly_linked_list.java ├── singly_linked_list.py ├── sll.go └── sort_linked_list.cpp ├── Math ├── Basic_operations.py ├── Count.go ├── Factorial.cpp ├── Factorial.go ├── Factorial.java ├── Factorial.py ├── Hamming_distance.py ├── Hammingdistance.cpp ├── K_closest.cpp ├── K_closest_points_to_origin.java ├── K_closest_points_to_origin.py ├── Number_of_Substrings_With_Only_1s.cpp ├── PowXn.go ├── PowXn.java ├── PowXn.py ├── Reverse_Integer.cpp ├── Sum_four.cpp ├── circle.cpp ├── count_numbers_with_unique_digits.java ├── count_primes.cpp ├── count_primes.java ├── count_unique_digits.cpp ├── count_unique_digits.go ├── factorial.py ├── factorial_iterative.js ├── find_longest_increasing_subsequence.cpp ├── hamming_distance.cpp ├── is_power_of_two.js ├── is_prime.js ├── k_closest_points_to_origin.cpp ├── missing_number.py ├── modular_expo_itera.cpp ├── modular_expo_recursive.cpp ├── num_points_inside_a_circle.cpp ├── num_points_inside_a_circle.js ├── num_points_inside_a_circle.py ├── num_steps_reduce_to_zero.Go ├── num_steps_reduce_to_zero.cpp ├── num_steps_reduce_to_zero.java ├── num_steps_reduce_to_zero.js ├── num_steps_reduce_to_zero.py ├── number_of_substrings_with_only_1s.js ├── op.js ├── palindrome_number.java ├── pallindrome_number.cpp ├── pallindrome_number.py ├── powXn.cpp ├── powXn.js ├── prime_factorization.cpp ├── shuffle_an_array.cpp ├── shuffle_an_array.py ├── sieve_of_eratosthenes.cpp ├── substrings_with_1s.py ├── unique_digits.cpp ├── unique_digits.java ├── unique_digits.py └── unique_integers_that_sum_up_to_0.cpp ├── Misc └── tictactoe.java ├── Patterns ├── CompleteSquare.java ├── HollowPattern.cpp ├── HollowPattern.go ├── HollowPattern.java ├── HollowPattern.py ├── Ladder_Pattern.java ├── ReverseRightTrianglePattern.java ├── RightPascalTriangle.java ├── StarDiamond.java ├── diamond_pattern.cpp ├── diamond_pattern.go ├── diamond_pattern.java ├── diamond_pattern.py ├── numerical_pattern.java ├── triangular_pattern.java └── triangular_pattern.py ├── Priority Queues ├── In_Place_HeapSort.cpp ├── buy_the_ticket.cpp ├── check_max_heap.cpp ├── kth_largest_element.cpp ├── kth_smallest_element.cpp ├── merge_k_sorted_arrays.cpp └── running_median.cpp ├── Queue ├── queue.cpp ├── queue.go ├── queue.java ├── queue.js ├── queue.py ├── queue_using_stack.js ├── queue_using_stacks.go ├── queues_using_stacks.py └── stack_using_queue.cpp ├── README.md ├── Recursion ├── calculatextopowern.cpp ├── count_digits.cpp ├── count_digits.go ├── count_zeros.cpp ├── count_zeros.go ├── factorial.cpp ├── factorial.go ├── factorial.js ├── fibonacci.cpp ├── fibonacci.go ├── fibonacci_memoization.cpp ├── fibonacci_memoization.go ├── geometric_sum.cpp ├── is_array_sorted.cpp ├── is_array_sorted.go ├── is_element_present.cpp ├── modular_exponentiation.cpp ├── multiplication.cpp ├── powerset.cpp ├── powerset.go ├── powerset.java ├── powerset.js ├── powerset.py ├── print_numbers.cpp ├── recursive_bubble_sort.cpp ├── reverse_print.go ├── tower_of_hannoi.cpp ├── tower_of_hannoi.java ├── tower_of_hannoi.js ├── tower_of_hannoi.py ├── tower_of_hanoi.go └── valid_palindrome_2.py ├── SECURITY.md ├── Scheduling Algortihms ├── fcfs.c ├── sjf.c └── srtf.c ├── Scheduling ├── fcfs.c ├── sjf.c └── srtf.c ├── Searching ├── first_duplicate_value.js ├── linear_search_string.cpp ├── semordnilap.go ├── separate_0s_and_1s.go └── separate_even_odd.go ├── Sliding Window ├── find_max.go ├── fruits_into_basket.cpp ├── fruits_into_basket.go ├── fruits_into_basket.java ├── fruits_into_basket.js ├── fruits_into_basket.py ├── longest_repeated_character_replacement.cpp ├── longest_repeated_character_replacement.go ├── longest_repeated_character_replacement.java ├── longest_repeated_character_replacement.js ├── longest_repeated_character_replacement.py ├── longest_substring_with_k_distinct_chars.go ├── longest_substring_with_k_distinct_chars.java ├── longest_substring_with_k_distinct_chars.js ├── longest_substring_with_k_distinct_chars.py ├── longest_substring_without_repeating_characters.go ├── max_eraser_value.go ├── max_eraser_value.java ├── sliding_window_max.java ├── sliding_window_max.js ├── sliding_window_max.py ├── subaray_sum_equals_k.cpp ├── subaray_sum_equals_k.go ├── subaray_sum_equals_k.java ├── subaray_sum_equals_k.js ├── subaray_sum_equals_k.py ├── subarray_product_less_than_k,js ├── subarray_product_less_than_k.cpp ├── subarray_product_less_than_k.go ├── subarray_product_less_than_k.java └── subarray_product_less_than_k.py ├── Stacks ├── Stack_with_max_API.cpp ├── Stacks_using_queues.py ├── balanced_parenthesis.go ├── is_palindrome.go ├── next_greater_element.c++ ├── next_greater_element.go ├── next_greater_element.java ├── next_greater_element.js ├── next_greater_element.py ├── queue using stack.go ├── queue using stack.java ├── queue using stack.js ├── queue using stack.py ├── queue_using_stacks.cpp ├── reverse_polish_notation.cpp ├── stack.cpp ├── stack.go ├── stack.java ├── stack.js ├── stack.py ├── stack_array_based.go ├── stack_dynamic_array.go ├── stack_linked_list.go ├── stack_using_queue.cpp ├── stack_using_queue.go ├── stack_using_queue.java ├── stack_using_queue.js ├── stack_using_queue.py ├── stacks_API.cpp ├── stacks_using_queues.java ├── stacks_with_queues.cpp ├── stacks_with_queues.py └── valid_parentheses.cpp ├── Strings ├── Dp_plaindrome.py ├── KMP.go ├── Longest_palindromic_substring.py ├── MaxConcatenatedstr.java ├── Min_palindrome.js ├── Valid_palindrome.py ├── case_specific_sorting_of_strings.cpp ├── check panagram.java ├── check_anagrams.java ├── check_palindrome.cpp ├── check_permutations.cpp ├── count_occurances.java ├── group_anagrams.cpp ├── group_anagrams.go ├── group_anagrams.java ├── group_anagrams.js ├── group_anagrams.py ├── is_pallindrome.cpp ├── is_pallindrome.go ├── is_pallindrome.java ├── is_pallindrome.js ├── is_pallindrome.py ├── is_unique.cpp ├── is_unique.go ├── is_unique.java ├── is_unique.js ├── is_unique.py ├── length_of_longest_substring.java ├── longest palindromic substring.java ├── longest_common_prefix.cpp ├── longest_string.cpp ├── one_edit.cpp ├── one_edit.go ├── one_edit.java ├── one_edit.js ├── one_edit.py ├── plaindrome_str.cpp ├── reverse_string.go ├── reverse_words_in_a_string.cpp ├── reverse_words_in_a_string.go ├── reverse_words_in_a_string.js ├── reverse_words_in_string.java ├── valid_palindrome.js ├── valid_pallindrome2.cpp ├── valid_pallindrome2.go ├── valid_pallindrome2.java ├── valid_pallindrome2.js ├── valid_pallindrome2.py ├── well_formed_parentheses.cpp ├── well_formed_parentheses.java └── zigzag_conversion.cpp ├── Trees ├── AVL │ └── avl.go ├── Binary Search Trees │ ├── Kth_Largest_Value_In_BST.py │ ├── Kth_largest_BST.cpp │ ├── Kth_largest_BST.java │ ├── Kth_largest_BST.js │ ├── Validate_BST.cpp │ ├── Validate_BST.java │ ├── Validate_BST.js │ ├── Validate_BST.py │ ├── bst.go │ ├── find_closest_value.cpp │ ├── find_closest_value.go │ ├── find_closest_value.js │ ├── find_closest_value.py │ ├── insert_into_bst.cpp │ ├── kth_largest.go │ ├── min_height_BST.cpp │ ├── min_height_BST.go │ ├── min_height_BST.java │ ├── min_height_BST.js │ ├── min_height_BST.py │ ├── reconstruct_bst.cpp │ ├── reconstruct_bst.go │ ├── reconstruct_bst.java │ ├── reconstruct_bst.js │ ├── reconstruct_bst.py │ ├── search.cpp │ └── validate_bst.go ├── Binary Trees │ ├── Trie.js │ ├── bfs.cpp │ ├── bfs.go │ ├── binary_tree.go │ ├── branch_sum.go │ ├── build_tree_preorder.cpp │ ├── calculate_size.go │ ├── count_nodes.cpp │ ├── delete.go │ ├── dfs.cpp │ ├── dfs.go │ ├── dfs.java │ ├── dfs.js │ ├── dfs.py │ ├── diameter.cpp │ ├── diameter.go │ ├── diameter.java │ ├── diameter.js │ ├── diameter.py │ ├── find_branch_sum.go │ ├── find_max.go │ ├── height.cpp │ ├── height.go │ ├── height_balanced_binary_tree.cpp │ ├── height_balanced_binary_tree.go │ ├── height_balanced_binary_tree.java │ ├── height_balanced_binary_tree.js │ ├── height_balanced_binary_tree.py │ ├── inorder_traversal.cpp │ ├── inorder_traversal.go │ ├── inorder_traversal.java │ ├── inorder_traversal.js │ ├── inorder_traversal.py │ ├── invert.cpp │ ├── invert.go │ ├── invert.java │ ├── invert.js │ ├── invert.py │ ├── is_symmetric.cpp │ ├── is_symmetric.go │ ├── is_symmetric.java │ ├── is_symmetric.js │ ├── is_symmetric.py │ ├── level_by_level.cpp │ ├── level_order_traversal.cpp │ ├── level_order_traversal.go │ ├── node_depth.go │ ├── postorder_traversal.cpp │ ├── preorder_traversal.cpp │ ├── remove_leaf_nodes.go │ ├── search_an_element.go │ └── sum_of_all_nodes.cpp ├── Implement_Trie.cpp ├── Implement_Trie.py ├── MaxpathBinaryTree.cpp ├── tree.go ├── trie.cpp ├── trie.go └── trie.java ├── Tries ├── pattern_matching.cpp ├── search_in_tries.cpp └── trie_node_class.cpp └── sorting ├── .DS_Store ├── Cyclic_Sort.java ├── bubble_sort.cpp ├── bubble_sort.go ├── bubble_sort.java ├── bubble_sort.js ├── bubble_sort.py ├── bucket-sort.js ├── bucket_sort.cpp ├── bucket_sort.go ├── bucket_sort.java ├── bucket_sort.js ├── count_sort.cpp ├── count_sort.java ├── count_sort.js ├── count_sort.py ├── dnf.cpp ├── dnf.go ├── dnf.java ├── dnf.js ├── dnf.py ├── heap_sort.cpp ├── heap_sort.java ├── heap_sort.js ├── heap_sort.py ├── insertion_sort.cpp ├── insertion_sort.go ├── insertion_sort.java ├── insertion_sort.js ├── insertion_sort.py ├── merge_sort.cpp ├── merge_sort.go ├── merge_sort.java ├── merge_sort.js ├── merge_sort.py ├── quick_sort.cpp ├── quick_sort.go ├── quick_sort.java ├── quick_sort.js ├── quick_sort.py ├── radix_sort.cpp ├── radix_sort.go ├── radix_sort.java ├── radix_sort.js ├── radix_sort.py ├── selection_sort.cpp ├── selection_sort.go ├── selection_sort.java ├── selection_sort.js ├── selection_sort.py ├── tim_sort.cpp ├── tim_sort.go ├── tim_sort.java ├── tim_sort.py └── wave_sort.cpp /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .idea 3 | *.exe -------------------------------------------------------------------------------- /2D Arrays (Matrix)/2D_sorted.go: -------------------------------------------------------------------------------- 1 | func searchMatrix(matrix [][]int, target int) bool { 2 | if len(matrix) == 0 || len(matrix[0]) == 0 { 3 | return false 4 | } 5 | 6 | rows, cols := len(matrix), len(matrix[0]) 7 | left, right := 0, rows*cols-1 8 | 9 | for left <= right { 10 | mid := left + (right-left)/2 11 | // Convert the 1D index back to 2D coordinates 12 | row, col := mid/cols, mid%cols 13 | midValue := matrix[row][col] 14 | 15 | if midValue == target { 16 | return true 17 | } else if midValue < target { 18 | left = mid + 1 19 | } else { 20 | right = mid - 1 21 | } 22 | } 23 | 24 | return false 25 | } 26 | -------------------------------------------------------------------------------- /2D Arrays (Matrix)/binary_search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an m x n integer matrix matrix with the following two properties: 3 | 4 | Each row is sorted in non-decreasing order. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | Given an integer target, return true if target is in matrix or false otherwise. 7 | 8 | You must write a solution in O(log(m * n)) time complexity. 9 | 10 | 11 | 1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 12 | Output: true 13 | 14 | 2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 15 | Output: false 16 | */ 17 | 18 | class Solution { 19 | bool costumBinarySearch(const vector>& matrix, int target, int low, int high){ 20 | int size = matrix[0].size(); 21 | while(high - low > 1){ 22 | int mid = (high + low) / 2; 23 | if(matrix[mid / size][mid % size] < target) { 24 | low = mid + 1; 25 | } else { 26 | high = mid; 27 | } 28 | } 29 | if(matrix[low / size][low % size] == target || matrix[high / size][high % size] == target){ 30 | return true; 31 | } 32 | return false; 33 | } 34 | public: 35 | bool searchMatrix(vector>& matrix, int target) { 36 | return costumBinarySearch(matrix, target, 0, matrix.size() * matrix[0].size() - 1); 37 | } 38 | }; -------------------------------------------------------------------------------- /2D Arrays (Matrix)/count_negatives_in_sorted_matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. 3 | 4 | Example 1: 5 | Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 6 | Output: 8 7 | Explanation: There are 8 negatives number in the matrix. 8 | 9 | Example 2: 10 | Input: grid = [[3,2],[1,0]] 11 | Output: 0 12 | 13 | Constraints: 14 | m == grid.length 15 | n == grid[i].length 16 | 1 <= m, n <= 100 17 | -100 <= grid[i][j] <= 100 18 | 19 | Follow up: Could you find an O(n + m) solution? 20 | */ 21 | 22 | class Solution { 23 | public: 24 | int countNegatives(vector>& grid) { 25 | int len = grid.size(), m = grid[0].size(); 26 | int ans = 0; 27 | int j = 0, i = len - 1; 28 | while(j < m && i >= 0){ 29 | if(grid[i][j] < 0){ 30 | ans += (m - j); 31 | i--; 32 | } 33 | else{ 34 | j++; 35 | } 36 | } 37 | return ans; 38 | } 39 | }; -------------------------------------------------------------------------------- /2D Arrays (Matrix)/matrix_diagonal_sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a square matrix mat, return the sum of the matrix diagonals. 3 | 4 | Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. 5 | 6 | Example 1: 7 | Input: mat = [[1,2,3], 8 | [4,5,6], 9 | [7,8,9]] 10 | Output: 25 11 | Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 12 | Notice that element mat[1][1] = 5 is counted only once. 13 | 14 | Example 2: 15 | Input: mat = [[1,1,1,1], 16 | [1,1,1,1], 17 | [1,1,1,1], 18 | [1,1,1,1]] 19 | Output: 8 20 | 21 | Example 3: 22 | Input: mat = [[5]] 23 | Output: 5 24 | 25 | Constraints: 26 | n == mat.length == mat[i].length 27 | 1 <= n <= 100 28 | 1 <= mat[i][j] <= 100 29 | */ 30 | 31 | class Solution { 32 | public: 33 | int diagonalSum(vector>& mat) { 34 | int len = mat.size(), sum = 0; 35 | for(int i = 0; i < len; i++){ 36 | sum += mat[i][i] + mat[i][len - 1 - i]; 37 | } 38 | // if length is odd then subtract mid element, because its added twice 39 | if(len & 1){ 40 | sum -= mat[len / 2][len / 2]; 41 | } 42 | return sum; 43 | } 44 | }; -------------------------------------------------------------------------------- /2D Arrays (Matrix)/matrix_wave_print.cpp: -------------------------------------------------------------------------------- 1 | // Prints a matrix in wave form 2 | #include 3 | using namespace std; 4 | void wave_print(int Mat[][10], int R, int C){ 5 | for(int j = 0; j < C; j++){ 6 | if(j & 1){ 7 | for(int i = R - 1; i >= 0; i--){ 8 | cout << Mat[i][j] << " "; 9 | } 10 | } 11 | else{ 12 | for(int i = 0; i < R; i++){ 13 | cout << Mat[i][j] << " "; 14 | } 15 | } 16 | } 17 | } 18 | int main(){ 19 | int Mat[10][10], R, C; 20 | cin >> R >> C; 21 | for(int i = 0; i < R; i++){ 22 | for(int j = 0; j < C; j++){ 23 | cin >> Mat[i][j]; 24 | } 25 | } 26 | for(int i = 0; i < R; i++){ 27 | for(int j = 0; j < C; j++){ 28 | cout << Mat[i][j] << " "; 29 | } 30 | cout << endl; 31 | } 32 | wave_print(Mat, R, C); 33 | } -------------------------------------------------------------------------------- /2D Arrays (Matrix)/search_element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an m x n integer matrix matrix with the following two properties: 3 | 4 | Each row is sorted in non-decreasing order. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | Given an integer target, return true if target is in matrix or false otherwise. 7 | 8 | You must write a solution in O(log(m * n)) time complexity. 9 | 10 | 11 | 1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 12 | Output: true 13 | 14 | 2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 15 | Output: false 16 | */ 17 | 18 | class Solution { 19 | public: 20 | bool searchMatrix(vector> &matrix,int target) { 21 | int i = 0; 22 | int j = matrix[0].size() - 1; 23 | 24 | while(i < matrix.size() && j >= 0) 25 | { 26 | if(target == matrix[i][j]) 27 | return true; 28 | else if(target < matrix[i][j]) 29 | j--; 30 | else 31 | i++; 32 | } 33 | return false; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Arrays/Maximum_freq.py: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int majorityElement(int[] nums) { 3 | int candidate = nums[0]; // Initialize the candidate as the first element 4 | int count = 1; // Initialize the count of the current candidate as 1 5 | 6 | // Iterate through the array starting from the second element 7 | for (int i = 1; i < nums.length; i++) { 8 | if (nums[i] == candidate) { 9 | // If the current element is the same as the candidate, increment the count 10 | count++; 11 | } else if (count > 0) { 12 | // If the current element is different from the candidate and count is positive, 13 | // decrement the count since we have a matching pair (candidate vs. current element) 14 | count--; 15 | } else { 16 | // If count becomes zero, update the candidate to the current element and set count to 1 17 | candidate = nums[i]; 18 | count = 1; 19 | } 20 | } 21 | 22 | // At the end, the candidate will be the majority element 23 | return candidate; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Arrays/Rotatedarr.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(std::vector& nums, int target) { 4 | int low = 0, high = nums.size() - 1; 5 | 6 | while (low <= high) { 7 | int mid = (low + high) / 2; 8 | 9 | if (nums[mid] == target) { 10 | return mid; 11 | } 12 | 13 | if (nums[low] <= nums[mid]) { 14 | if (nums[low] <= target && target < nums[mid]) { 15 | high = mid - 1; 16 | } else { 17 | low = mid + 1; 18 | } 19 | } else { 20 | if (nums[mid] < target && target <= nums[high]) { 21 | low = mid + 1; 22 | } else { 23 | high = mid - 1; 24 | } 25 | } 26 | } 27 | 28 | return -1; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Arrays/first_duplicate_value.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function 3 | that returns the first integer that appears more than once (when the array is read from left to right). 4 | 5 | Sample Input = [2, 1, 5, 2, 3, 3, 4] 6 | Output : 2 7 | 8 | Please provide O(n) time and O(1) space solution along with O(n) time and O(n) space solution 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Solution{ 15 | public: 16 | // O(N) time complexity and O(N) Space Complexity Solution 17 | int findDuplicate1(vector& nums) 18 | { 19 | int N=nums.size(); 20 | 21 | // Use Vector Instead of Unordered Set or Map for O(1) extraction time complexity 22 | vector trk(N,false); 23 | 24 | for(int i=0;i& nums) 34 | { 35 | int N=nums.size(); 36 | for(int i=0;i None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | #Time Complexity - O(M+N) 7 | #Space Complexity - O(1) 8 | 9 | #Using similar to merge sort algorithm implementation. 10 | #Traversing in reverse order and comparing m,n values. 11 | #Placing the highest element last and continuing with the algorithm. 12 | i, j, k = m - 1, n - 1, m + n - 1 13 | while(i >= 0 and j >= 0): 14 | if(nums1[i] > nums2[j]): 15 | nums1[k] = nums1[i] 16 | i -= 1 17 | k -= 1 18 | else: 19 | nums1[k] = nums2[j] 20 | j -= 1 21 | k -= 1 22 | 23 | #placing left over elements from num1 to nums1 24 | while(i >= 0): 25 | nums1[k] = nums1[i] 26 | i -= 1 27 | k -= 1 28 | 29 | #placing left over elements from num2 to num1 30 | while(j >= 0): 31 | nums1[k] = nums2[j] 32 | j -= 1 33 | k -= 1 34 | -------------------------------------------------------------------------------- /Arrays/string_halves.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. 3 | 4 | Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. 5 | 6 | Return true if a and b are alike. Otherwise, return false. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "book" 13 | Output: true 14 | Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. 15 | Example 2: 16 | 17 | Input: s = "textbook" 18 | Output: false 19 | Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. 20 | Notice that the vowel o is counted twice. 21 | 22 | 23 | Constraints: 24 | 25 | 2 <= s.length <= 1000 26 | s.length is even. 27 | s consists of uppercase and lowercase letters. 28 | */ 29 | 30 | #include 31 | class Solution { 32 | public: 33 | bool halvesAreAlike(string s) { 34 | set X {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 35 | int half = s.size() / 2; 36 | int c = 0, d = 0; 37 | for(int i = 0; i < half; i++){ 38 | if(X.find(s[i]) != X.end()) 39 | c++; 40 | } 41 | for(int i = half; i < s.size(); i++){ 42 | if(X.find(s[i]) != X.end()){ 43 | d++; 44 | } 45 | } 46 | return c == d; 47 | } 48 | }; -------------------------------------------------------------------------------- /Arrays/triplet_sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, nums, and an integer value, target, 3 | determine if there are any three integers in nums whose sum equals the target. 4 | Return TRUE if three such integers are found in the array. Otherwise, return FALSE. 5 | ''' 6 | 7 | def find3Numbers(A, arr_size, sum): 8 | 9 | # Sort the elements 10 | A.sort() 11 | 12 | # Now fix the first element 13 | # one by one and find the 14 | # other two elements 15 | for i in range(0, arr_size-2): 16 | 17 | # index of the first element 18 | # in the remaining elements 19 | l = i + 1 20 | 21 | # index of the last element 22 | r = arr_size-1 23 | while (l < r): 24 | 25 | if( A[i] + A[l] + A[r] == sum): 26 | return True 27 | elif (A[i] + A[l] + A[r] < sum): 28 | l += 1 29 | else: # A[i] + A[l] + A[r] > sum 30 | r -= 1 31 | 32 | # If we reach here, then 33 | # no triplet was found 34 | return False 35 | 36 | # Driver program to test above function 37 | A = [1, 2, 3, 4, 5, 6] 38 | sum = 9 39 | arr_size = len(A) 40 | 41 | print(find3Numbers(A, arr_size, sum)) -------------------------------------------------------------------------------- /Arrays/urlify.go: -------------------------------------------------------------------------------- 1 | // Implement an algorithm to replace all spaces with %20, assumew we have extra buffer at the end. 2 | // Input : Mr Ashish Lala Output: Mr%20Ashish%20Lala 3 | // Program Author : Abhisek Kumar Gupta 4 | // Time complexity : O(n) Space complexity O(n) 5 | package main 6 | 7 | import "fmt" 8 | 9 | func Urlify(s string, length int) string { 10 | spaceCount := 0 11 | r := []rune{} 12 | // compute spaces, 13 | for i := 0; i < length; i++ { 14 | if s[i] == ' ' { 15 | spaceCount++ 16 | } 17 | } 18 | // string to rune 19 | for _, v := range s { 20 | r = append(r, v) 21 | } 22 | // triple space count and find out how many extra characters will be there in final string 23 | index := length + (spaceCount * 3) // actual length of final string 24 | for i := length - 1; i >= 0; i-- { 25 | // If u encounter space then replace with %20 26 | if r[i] == ' ' { 27 | r[index - 1] = '0' 28 | r[index - 2] = '2' 29 | r[index - 3] = '%' 30 | index -= 3 31 | } else { 32 | // If there is no space then copy the original character 33 | r[index - 1] = r[i] 34 | index-- 35 | } 36 | } 37 | return string(r[index:]) 38 | } 39 | 40 | 41 | func main() { 42 | s := "Mr John Smith "; 43 | length := 13 44 | msg := Urlify(s, length); 45 | fmt.Println(msg) 46 | } -------------------------------------------------------------------------------- /Backtracking/Generate_Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | Example 1: 4 | Input: n = 3 5 | Output: ["((()))","(()())","(())()","()(())","()()()"] 6 | 7 | Example 2: 8 | Input: n = 1 9 | Output: ["()"] 10 | Constraints: 11 | 1 <= n <= 8 12 | ''' 13 | class Solution: 14 | #reference: GeeksforGeeks for comments 15 | '''To form all the sequences of balanced bracket subsequences with n pairs. So there are n opening brackets and n closing brackets. So the subsequence will be of length 2*n. There is a simple idea, the i’th character can be ‘{‘ if and only if the count of ‘{‘ till i’th is less than n and i’th character can be ‘}’ if and only if the count of ‘{‘ is greater than the count of ‘}’ till index i. If these two cases are followed then the resulting subsequence will always be balanced''' 16 | 17 | def generate(self,n,open,close,s,final_arr): 18 | if(open==n and close==n): 19 | final_arr.append(s) 20 | return 21 | if(open List[str]: 27 | final_arr = [] 28 | Solution.generate(self,n,0,0,"",final_arr) 29 | return final_arr -------------------------------------------------------------------------------- /Binary Search/binary_search.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Finds the first and last occurrence of a target value in a sorted array. 3 | * 4 | * @param {number[]} N - The sorted array of numbers. 5 | * @param {number} T - The target value to search for. 6 | * @returns {number[]} An array containing the first and last index of the target value, or [-1,-1] if not found. 7 | */ 8 | const searchRange = function(N, T) { 9 | // Helper function to perform binary search on the array 10 | const find = (target, arr, left=0, right=arr.length) => { 11 | while (left <= right) { 12 | // Calculate the middle index 13 | let mid = left + right >> 1; 14 | // If the middle element is less than the target, move the left pointer to mid + 1 15 | if (arr[mid] < target) left = mid + 1; 16 | // If the middle element is greater than or equal to the target, move the right pointer to mid - 1 17 | else right = mid - 1; 18 | } 19 | // Return the left pointer, which will be the index of the target or the insertion point if not found 20 | return left; 21 | }; 22 | 23 | // Find the leftmost index of the target value 24 | let Tleft = find(T, N); 25 | // If the target value is not found in the array, return [-1,-1] 26 | if (N[Tleft] !== T) return [-1,-1]; 27 | // Find the rightmost index of the target value 28 | return [Tleft, find(T+1, N, Tleft) - 1]; 29 | }; 30 | -------------------------------------------------------------------------------- /Binary Search/first_occurance.go: -------------------------------------------------------------------------------- 1 | // Search of first occurance of element using Binary search 2 | // Sample Input {0, 1, 1, 4, 5} key 1 3 | // Output 1 4 | // Time conplexity O(log n) 5 | package main 6 | 7 | import "fmt" 8 | 9 | func FirstOccurance(Arr []int, key int) int { 10 | start, end, result := 0, len(Arr)-1, -1 11 | 12 | for start <= end { 13 | mid := start + (end-start)/2 14 | if Arr[mid] > key { 15 | end = mid - 1 16 | } else if Arr[mid] < key { 17 | start = mid + 1 18 | } else { 19 | result = mid // update result 20 | end = mid - 1 // move to left side to search for occurance 21 | } 22 | } 23 | return result 24 | } 25 | 26 | func main() { 27 | Arr := []int{0, 1, 1, 4, 5} 28 | fmt.Println(FirstOccurance(Arr, 1)) 29 | } -------------------------------------------------------------------------------- /Binary Search/floor_of_target.java: -------------------------------------------------------------------------------- 1 | /* Floor of an element in a sorted array 2 | You are given a sorted array nums and a target . 3 | Find the index of the greatest element that is less than or equal to target 4 | 5 | EXAMPLES: 6 | INPUT : nums = [2,4,5,7,9,11,18,25], target = 18 7 | OUTPUT: 6 8 | 9 | INPUT : nums = [2,4,5,7,9,11,18,25], target = 10 10 | OUTPUT: 4 11 | 12 | APPROACH : 13 | We will implement this problem using BinarySearch since the array is sorted and will be similar to ceil 14 | but with slight modification 15 | 16 | */ 17 | 18 | 19 | public class FloorOfTarget{ 20 | 21 | public static int search_floor(int[] nums,int target){ 22 | int start = 0,end = nums.length-1; 23 | while(start <=end){ 24 | int mid = start +(end-start)/2; 25 | if(nums[mid]==target){ 26 | return mid; // returns the target 27 | } 28 | else if(nums[mid] > target){ 29 | end = mid-1; 30 | } 31 | else{ 32 | start = mid +1; 33 | } 34 | } 35 | return end; // returns the nearest element to target if the target is not found 36 | } 37 | public static void main(String[] args){ 38 | int[] nums = {2,4,5,7,9,11,18,25}; 39 | int target = 10; // output will be 4 in this case. 40 | System.out.print(search_floor(nums,target)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Binary Search/last_occurance.go: -------------------------------------------------------------------------------- 1 | // Search of last occurance of element using Binary search 2 | // Sample Input {0, 1, 1, 4, 5} key 1 3 | // Output 1 4 | // Time conplexity O(log n) 5 | package main 6 | 7 | import "fmt" 8 | 9 | func LastOccurance(Arr []int, key int) int { 10 | start, end, result := 0, len(Arr)-1, -1 11 | 12 | for start <= end { 13 | mid := start + (end-start)/2 14 | if Arr[mid] > key { 15 | end = mid - 1 16 | } else if Arr[mid] < key { 17 | start = mid + 1 18 | } else { 19 | result = mid // update result 20 | start = mid + 1 // move to RIGHT side to search for occurance 21 | } 22 | } 23 | return result 24 | } 25 | 26 | func main() { 27 | Arr := []int{0, 1, 1, 1, 2, 2, 3, 3, 4, 5} 28 | fmt.Println(LastOccurance(Arr, 1)) // 3 29 | fmt.Println(LastOccurance(Arr, 2)) // 5 30 | fmt.Println(LastOccurance(Arr, 3)) // 7 31 | } -------------------------------------------------------------------------------- /Binary Search/square_root.java: -------------------------------------------------------------------------------- 1 | /* Square root of a number 2 | Given a non-negative integer x, return the square root of x rounded down to the nearest integer. 3 | The returned integer should be non-negative as well. 4 | 5 | Examples: 6 | Input: x = 36 7 | Output: 6 8 | Explanation: The square root of 36 is 6, so we return 6. 9 | 10 | Input: x = 8 11 | Output: 2 12 | Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 13 | 2 is returned. 14 | 15 | 16 | HOW TO SOLVE: 17 | This is similar to finding perfect square of number but to return the square root. 18 | We use Binary Search for this problem. 19 | */ 20 | 21 | public class SquareRoot{ 22 | public static int sqrt(int x){ 23 | int start = 1, end=x; 24 | while(start<=end){ 25 | int mid = (start+end)/2; 26 | if(x/mid==mid){ 27 | return mid; 28 | } 29 | else if(mid< x/mid){ 30 | start = mid+1; 31 | } 32 | else if(mid > x/mid){ 33 | end = mid-1; 34 | } 35 | 36 | } 37 | return end; 38 | } 39 | public static void main(String[] args){ 40 | // you can also get input dynamically using Scanner class 41 | int number = 36; 42 | System.out.print(sqrt(number)); 43 | } 44 | } -------------------------------------------------------------------------------- /Bit Manipulation/count_bits.go: -------------------------------------------------------------------------------- 1 | // Program to count the number of bits that are set to 1 in an integer 2 | // The following program tests bits one at a time starting with the least-significant bit. 3 | // Since we perform O(1) computation per bit, the time complexity is O(n) where n is number of bits in the integer 4 | // Best case time complexity is O(1), if the input io 0 5 | package main 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | ) 11 | 12 | func CountBits(x int) (int, error) { 13 | if x < 0 { 14 | return x, errors.New("Negative number") 15 | } 16 | numBits := 0 17 | for x > 0{ 18 | numBits += x & 1 19 | x >>= 1 20 | } 21 | return numBits, nil 22 | } 23 | 24 | func main() { 25 | res, err := CountBits(7) 26 | fmt.Println(res) 27 | fmt.Println(err) 28 | 29 | } -------------------------------------------------------------------------------- /Bit Manipulation/interesting_array.java: -------------------------------------------------------------------------------- 1 | package BitManipulation; 2 | 3 | import com.google.common.base.Stopwatch; 4 | 5 | public class InterestingArray { 6 | public static void main(String[] args) { 7 | Stopwatch timer = Stopwatch.createStarted(); 8 | 9 | int[] array = {9, 14, 27, 81, 197, 0, 1}; 10 | String ans = solve(array); 11 | System.out.println(ans); 12 | 13 | System.out.println("Runtime " + timer); 14 | } 15 | 16 | public static String solve(int[] array) { 17 | // O(N) time | O(1) space 18 | int oddCount = 0; 19 | 20 | for (var num : array) 21 | if (num % 2 != 0) 22 | oddCount += 1; 23 | 24 | return oddCount % 2 != 0 ? "No" : "Yes"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Bit Manipulation/number_of_1_bits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function that takes an integer and returns the number of 1 bits it has. 3 | * 4 | * 5 | * Problem Constraints 6 | * 1 <= A <= 109 7 | * 8 | * 9 | * Input Format 10 | * First and only argument contains integer A 11 | * 12 | * 13 | * Output Format 14 | * Return an integer as the answer 15 | * 16 | * 17 | * Example Input 18 | * Input 1: 19 | * 11 20 | * Input 2: 21 | * 6 22 | * 23 | * 24 | * Example Output 25 | * Output 1: 26 | * 3 27 | * Output 2: 28 | * 2 29 | * 30 | * 31 | * Example Explanation 32 | * Explaination 1: 33 | * 11 is represented as 1011 in binary. 34 | * Explaination 2: 35 | * 6 is represented as 110 in binary. 36 | */ 37 | 38 | package BitManipulation; 39 | 40 | public class NumberOf1Bits { 41 | public static void main(String[] args) { 42 | int num = 11; 43 | int ans = solve(num); 44 | System.out.println(ans); 45 | } 46 | public static int solve(int num) { 47 | // O(Log(N)) tine | O(1) space 48 | int currentNum = num, count = 0; 49 | 50 | while (currentNum != 0) { 51 | if ( (currentNum & 1) == 1) count++; 52 | currentNum = currentNum >> 1; 53 | } 54 | return count; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Bit Manipulation/parity_of_a_word.go: -------------------------------------------------------------------------------- 1 | // Computing the parity of a word 2 | // The parity of a binary word is 1 if the number of 1s in the word is odd 3 | // The parity of a binary word is 0 if the number of 1s in the word is even 4 | 5 | // Input : 11 6 | // Output : 1 7 | 8 | // Input : 12 9 | // Output : 0 10 | 11 | package main 12 | 13 | import "fmt" 14 | 15 | // This algorithm iteratively tests the value of each bit while 16 | // tacking the number of 1's seen so far (Brute Force) 17 | func Parity(x int) int { 18 | result := 0 19 | for x > 0 { 20 | result ^= (x & 1) 21 | x >>= 1 22 | } 23 | return result 24 | } 25 | 26 | func ParityImproved(x int) int { 27 | result := 0 28 | for x > 0 { 29 | result ^= 1 30 | // This can be used to improve the performance in the best and average cases. 31 | x &= (x - 1) // erase lowest set bit in a word in a single operation 32 | } 33 | return result 34 | } 35 | 36 | func main() { 37 | fmt.Println("*********Brute Force*********") 38 | msg := Parity(11) 39 | fmt.Println(msg) 40 | msg = Parity(12) 41 | fmt.Println(msg) 42 | fmt.Println("*********Improved*********") 43 | msg = ParityImproved(11) 44 | fmt.Println(msg) 45 | msg = ParityImproved(12) 46 | fmt.Println(msg) 47 | } 48 | // The time complexity is O(n) where n is word size -------------------------------------------------------------------------------- /Bit Manipulation/power_of_2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return true if it is a power of two. Otherwise, return false. 3 | 4 | An integer n is a power of two, if there exists an integer x such that n == 2x. 5 | 6 | Example 1: 7 | Input: n = 1 8 | Output: true 9 | Explanation: 20 = 1 10 | 11 | Example 2: 12 | Input: n = 16 13 | Output: true 14 | Explanation: 24 = 16 15 | 16 | Example 3: 17 | Input: n = 3 18 | Output: false 19 | 20 | Constraints: 21 | 22 | -231 <= n <= 231 - 1 23 | 24 | Follow up: Could you solve it without loops/recursion? 25 | 26 | */ 27 | 28 | 29 | class Solution { 30 | public: 31 | bool isPowerOfTwo(int n) { 32 | return n > 0 && !(n &(n - 1)); 33 | } 34 | }; -------------------------------------------------------------------------------- /Bit Manipulation/reduce_to_zero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer num, return the number of steps to reduce it to zero. 3 | 4 | In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: num = 14 11 | Output: 6 12 | Explanation: 13 | Step 1) 14 is even; divide by 2 and obtain 7. 14 | Step 2) 7 is odd; subtract 1 and obtain 6. 15 | Step 3) 6 is even; divide by 2 and obtain 3. 16 | Step 4) 3 is odd; subtract 1 and obtain 2. 17 | Step 5) 2 is even; divide by 2 and obtain 1. 18 | Step 6) 1 is odd; subtract 1 and obtain 0. 19 | Example 2: 20 | 21 | Input: num = 8 22 | Output: 4 23 | Explanation: 24 | Step 1) 8 is even; divide by 2 and obtain 4. 25 | Step 2) 4 is even; divide by 2 and obtain 2. 26 | Step 3) 2 is even; divide by 2 and obtain 1. 27 | Step 4) 1 is odd; subtract 1 and obtain 0. 28 | Example 3: 29 | 30 | Input: num = 123 31 | Output: 12 32 | 33 | 34 | Constraints: 35 | 36 | 0 <= num <= 106 37 | */ 38 | 39 | #include 40 | class Solution { 41 | public: 42 | int numberOfSteps (int num) { 43 | int count = 0; 44 | while(num){ 45 | if(!(num & 1)){ 46 | num = num >> 1; 47 | } 48 | else{ 49 | num--; 50 | } 51 | count++; 52 | } 53 | return count; 54 | } 55 | }; -------------------------------------------------------------------------------- /Bit Manipulation/setbits.cpp: -------------------------------------------------------------------------------- 1 | // Program to count the number of bits that are set to 1 in an integer 2 | // The following program tests bits one at a time starting with the least-significant bit. 3 | // Since we perform O(1) computation per bit, the time complexity is O(n) where n is number of bits in the integer 4 | // Best case time complexity is O(1), if the input io 0 5 | #include 6 | using namespace std; 7 | int find_set_bits(int n){ 8 | int set_bits = 0; 9 | while(n){ 10 | set_bits += (n & 1); 11 | n >>= 1; 12 | } 13 | return set_bits; 14 | } 15 | int main(){ 16 | cout << find_set_bits(4) << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic Programming/best_time_to_buy_and_sell_stock.go: -------------------------------------------------------------------------------- 1 | // Best Time to buy and sell stock 2 | /* 3 | Explanation: 4 | We start by initializing the minimum price to the maximum integer value and the maximum profit to 0. 5 | We loop through the prices array, and for each price: 6 | If the price is less than the current minimum price, we update the minimum price. 7 | Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. 8 | Finally, we return the maximum profit 9 | 10 | Sample Input [7, 1, 5, 3, 6, 4] 11 | Output: 5 buy at 1 sell at 6 12 | 13 | Time Complexity: O(n), where n is the length of the prices array. 14 | Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit 15 | */ 16 | package main 17 | 18 | import ( 19 | "fmt" 20 | "math" 21 | ) 22 | 23 | func maxProfit(prices []int) int { 24 | minPrice := math.MaxInt32 // Initialize minimum price to maximum integer value 25 | maxProfit := 0 // Initialize maximum profit to 0 26 | for _, price := range prices { 27 | if price < minPrice { 28 | minPrice = price // Update minimum price 29 | } else if price-minPrice > maxProfit { 30 | maxProfit = price - minPrice // Update maximum profit 31 | } 32 | } 33 | return maxProfit // Return maximum profit 34 | } 35 | 36 | func main() { 37 | prices := []int{7, 1, 5, 3, 6, 4} 38 | fmt.Println(maxProfit(prices)) // Output: 5 39 | } -------------------------------------------------------------------------------- /Dynamic Programming/best_time_to_buy_and_sell_stock.js: -------------------------------------------------------------------------------- 1 | // Best Time to buy and sell stock 2 | /* 3 | Explanation: 4 | We start by initializing the minimum price to the maximum integer value and the maximum profit to 0. 5 | We loop through the prices array, and for each price: 6 | If the price is less than the current minimum price, we update the minimum price. 7 | Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. 8 | Finally, we return the maximum profit 9 | 10 | Sample Input [7, 1, 5, 3, 6, 4] 11 | Output: 5 buy at 1 sell at 6 12 | 13 | Time Complexity: O(n), where n is the length of the prices array. 14 | Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit 15 | */ 16 | /** 17 | * @param {number[]} prices 18 | * @return {number} 19 | */ 20 | var maxProfit = function (prices) { 21 | let minPrice = Infinity; // keep track of minimum price seen so far 22 | let maxProfit = 0; // keep track of maximum profit seen so far 23 | 24 | for (let i = 0; i < prices.length; i++) { 25 | if (prices[i] < minPrice) { 26 | minPrice = prices[i]; // update minimum price seen so far 27 | } else if (prices[i] - minPrice > maxProfit) { 28 | maxProfit = prices[i] - minPrice; // update maximum profit seen so far 29 | } 30 | } 31 | 32 | return maxProfit; 33 | }; 34 | 35 | const prices = [7, 1, 5, 3, 6, 4]; 36 | console.log(maxProfit(prices)); // Output: 5 37 | -------------------------------------------------------------------------------- /Dynamic Programming/climb_stairs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 4 | // or 2 steps. In how many distinct ways can the child climb to the top? 5 | import "fmt" 6 | 7 | // ClimbStairs: returns the number of ways in which a child can climb stairs 8 | // Approach: Number of ways to reach kth stair = Number of ways to reach k − 1th stair + Number of ways to reach k − 2th stair 9 | // ClimbStairs(k) = ClimbStairs(k-1) + ClimbStairs(k-2) 10 | func ClimbStairs(n int) int { 11 | // base case 12 | if n < 3 { 13 | return n 14 | } 15 | cache := make([]int, n) 16 | // initialize initial 2 values 17 | cache[0], cache[1] = 1, 2 18 | for i := 2; i < n; i++ { 19 | // add previous 2 values 20 | cache[i] = cache[i-1] + cache[i-2] 21 | } 22 | return cache[n-1] 23 | } 24 | 25 | // Variatiom: A child is climbing up a staircase with 􀝊 steps, and can hop either 1 step, 2 steps, or 3 steps at a time. 26 | // Implement a method to count how many possible ways the child can jump up the stairs. 27 | // Approach similar to above problem 28 | func ClimbStairs2(n int) int { 29 | // base case 30 | if n < 3 { 31 | return n 32 | } 33 | cache := make([]int, n) 34 | // initialize initial 3 values 35 | cache[0], cache[1], cache[2] = 1, 2, 4 36 | for i := 3; i < n; i++ { 37 | // add previous 3 values 38 | cache[i] = cache[i-1] + cache[i-2] + cache[i - 3] 39 | } 40 | return cache[n-1] 41 | } 42 | func main() { 43 | fmt.Println(ClimbStairs(5)) 44 | fmt.Println(ClimbStairs2(5)) 45 | } -------------------------------------------------------------------------------- /Dynamic Programming/climb_stairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 \ 3 | or 2 steps. In how many distinct ways can the child climb to the top? 4 | ''' 5 | # ClimbStairs: returns the number of ways in which a child can climb stairs 6 | # Approach: Number of ways to reach kth stair = Number of ways to reach k − 1th stair + Number of ways to reach k − 2th stair 7 | # ClimbStairs(k) = ClimbStairs(k-1) + ClimbStairs(k-2) 8 | def climb_stairs(n): 9 | # Base case 10 | if n < 3: 11 | return n 12 | cache = [0] * n 13 | # Initialize initial 2 values 14 | cache[0], cache[1] = 1, 2 15 | for i in range(2, n): 16 | # Add previous 2 values 17 | cache[i] = cache[i - 1] + cache[i - 2] 18 | return cache[n - 1] 19 | 20 | # Variation: A child is climbing up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. 21 | # Implement a method to count how many possible ways the child can jump up the stairs. 22 | # Approach similar to the above problem 23 | def climb_stairs_variation(n): 24 | # Base case 25 | if n < 3: 26 | return n 27 | cache = [0] * n 28 | # Initialize initial 3 values 29 | cache[0], cache[1], cache[2] = 1, 2, 4 30 | for i in range(3, n): 31 | # Add previous 3 values 32 | cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3] 33 | return cache[n - 1] 34 | 35 | if __name__ == "__main__": 36 | print(climb_stairs(5)) 37 | print(climb_stairs_variation(5)) 38 | -------------------------------------------------------------------------------- /Dynamic Programming/edit_distance_recursive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings str1 and str2 and following three operations that can performed on str1. 3 | 1) Insert 4 | 2) Remove 5 | 3) Replace 6 | Find minimum number of operations required to convert ‘str1’ into ‘str2’. 7 | For example if input strings are CAT AND CAR the edit distance is 1. 8 | 9 | Input : s1 : saturday s2 : sunday 10 | Output : 3 11 | */ 12 | // Recursive Solution : TC Exponential 13 | // Porgram Author : Abhisek Kumar Gupta 14 | #include 15 | using namespace std; 16 | int calls = 0; 17 | int find_edit_distance(string s1, string s2, int l1, int l2){ 18 | calls++; 19 | if(l1 == 0) 20 | return l2; 21 | if(l2 == 0) 22 | return l1; 23 | if(s1[l1] == s2[l2]){ 24 | return find_edit_distance(s1, s2, l1 - 1, l2 - 1); 25 | } 26 | int del = find_edit_distance(s1, s2, l1, l2 - 1); 27 | int replace = find_edit_distance(s1, s2, l1 - 1, l2 - 1); 28 | int insert = find_edit_distance(s1, s2, l1 - 1, l2); 29 | return min (del, min(replace, insert)) + 1; 30 | } 31 | int main(){ 32 | string s1 = "abhisek"; 33 | string s2 = "tsunade"; 34 | int l1 = s1.length() - 1; 35 | int l2 = s2.length() - 1; 36 | int result = find_edit_distance(s1, s2, l1, l2); 37 | cout << result; 38 | cout << "\n" << calls; 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Dynamic Programming/longest_common_subsequence_dp.cpp: -------------------------------------------------------------------------------- 1 | // DP : Find Longest Common Subsequence of two string 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | 5 | using namespace std; 6 | const int maxi = 10000; 7 | int find_longest_common_subsequence(string a, string b, int n, int m, int dp[][maxi]){ 8 | for(int i = 0; i <= n; i++){ 9 | dp[i][0] = 0; 10 | } 11 | for(int i = 0; i <= m; i++){ 12 | dp[0][i] = 0; 13 | } 14 | // dp solution builds the table of LCS of substrings and starts 15 | // computing the length building on the final solution 16 | // we place one string along row and one along the column 17 | for(int i = 1; i <= n; i++){ 18 | for(int j = 1; j <= m; j++){ 19 | // populating table in row-wise order 20 | if(a[i - 1] == b[j - 1]){ 21 | dp[i][j] = dp[i - 1][j - 1] + 1; 22 | } 23 | else{ 24 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 25 | } 26 | } 27 | } 28 | return dp[m][n]; 29 | } 30 | int main(){ 31 | string a = "DABCEFIHKST"; 32 | string b = "DCEFKAAAQST"; 33 | int n = a.length(); 34 | int m = b.length(); 35 | int dp[n+1][maxi]; 36 | memset(dp, -1, sizeof(dp)); 37 | int result = find_longest_common_subsequence(a, b, n, m, dp); 38 | cout << result; 39 | return 0; 40 | } 41 | // Time complexity O(N * M) improvement over both 42 | // Recursion and memoization 43 | // Space complexity O(N * M) -------------------------------------------------------------------------------- /Dynamic Programming/longest_increasing_subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Increasing Subsequence 3 | Input : 1 2 1 3 1 4 4 | Output : 4 5 | */ 6 | // Dynamic Programming Approach : TC O(n^2) 7 | // Program Author : Abhisek Kumar Gupta 8 | #include 9 | using namespace std; 10 | 11 | int find_longest_increasing_subsequence(vector V, int n){ 12 | int dp[1004]; 13 | for(int i = 0; i < 1000; i++) dp[i] = 1; 14 | int best = INT_MIN; 15 | for(int i = 1; i < n; i++){ 16 | for(int j = 0; j < i; j++){ 17 | if(V[j] <= V[i]){ // this means its in increasing order and we can take value stored at dp[j] and add 1 to it 18 | int curr_len = 1 + dp[j]; 19 | dp[i] = max(curr_len, dp[i]); 20 | } 21 | } 22 | best = max(dp[i], best); 23 | } 24 | return best; 25 | } 26 | int main(){ 27 | int n; 28 | cout << "Enter a number"; 29 | cin >> n; 30 | vector V(n); 31 | for(int i = 0; i < n; i++){ 32 | cin >> V[i]; 33 | } 34 | int result = find_longest_increasing_subsequence(V, n); 35 | cout << result; 36 | } 37 | -------------------------------------------------------------------------------- /Dynamic Programming/reconstruct_bst_in_python.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.left = None 5 | self.right = None 6 | 7 | def constructBST(preorder): 8 | if not preorder: 9 | return None 10 | 11 | root = TreeNode(preorder[0]) 12 | 13 | i = 1 14 | while i < len(preorder) and preorder[i] < root.val: 15 | i += 1 16 | 17 | root.left = constructBST(preorder[1:i]) 18 | root.right = constructBST(preorder[i:]) 19 | 20 | return root 21 | 22 | def inorderTraversal(root): 23 | if root is None: 24 | return [] 25 | 26 | return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right) 27 | 28 | # Sample Input 29 | preorder = [10, 4, 2, 1, 5, 17, 19, 18] 30 | 31 | # Construct the BST 32 | root = constructBST(preorder) 33 | 34 | # Print the inorder traversal of the reconstructed BST 35 | inorder = inorderTraversal(root) 36 | print(inorder) 37 | -------------------------------------------------------------------------------- /Dynamic Programming/rod_cutting_problem_dp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a rod of length n inches and an array of prices that contains prices of all 3 | pieces of size smaller than n. Determine the maximum value obtainable by cutting 4 | up the rod and selling the pieces. For example, if length of the rod is 8 and the 5 | values of different pieces are given as following, then the maximum obtainable 6 | value is 22 (by cutting in two pieces of lengths 2 and 6) 7 | Input : 8 8 | : 1 5 8 9 10 17 17 20 9 | Output : 22 10 | */ 11 | // Dynamic Programming solution TC : O(n^2) 12 | // Program Author: Abhisek Kumar Gupta 13 | #include 14 | using namespace std; 15 | int max_profit(vector profit, int total_length){ 16 | int dp[100] = {}; 17 | for(int length = 1; length <= total_length; length++){ 18 | int best = 0; 19 | for(int cut = 1; cut <= length; cut++){ 20 | best = max(best, profit[cut] + dp[length - cut]); 21 | } 22 | dp[length] = best; 23 | } 24 | return dp[total_length]; 25 | } 26 | int main(){ 27 | int total_length; 28 | cin >> total_length; 29 | vector profit(total_length + 1); 30 | for(int length = 1; length <= total_length; length++) 31 | cin >> profit[length]; 32 | int result = max_profit(profit, total_length); 33 | cout << result; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Dynamic Programming/rod_cutting_problem_memoized.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a rod of length n inches and an array of prices that contains prices of all 3 | pieces of size smaller than n. Determine the maximum value obtainable by cutting 4 | up the rod and selling the pieces. For example, if length of the rod is 8 and the 5 | values of different pieces are given as following, then the maximum obtainable 6 | value is 22 (by cutting in two pieces of lengths 2 and 6) 7 | Input : 8 8 | : 1 5 8 9 10 17 17 20 9 | Output : 22 10 | */ 11 | // Memoized solution TC : O(n^2) 12 | // Program Author: Abhisek Kumar Gupta 13 | #include 14 | using namespace std; 15 | int memoized[1000]; 16 | int max_profit(vector length, int n){ 17 | if(n == 0) return 0; 18 | int best = 0; 19 | if(memoized[n] != -1) return memoized[n]; 20 | for(int i = 0; i < n; i++){ 21 | int total_profit = length[i] + max_profit(length, n - (i + 1)); 22 | best = max(best, total_profit); 23 | memoized[n] = best; 24 | } 25 | return memoized[n]; 26 | } 27 | int main(){ 28 | memset(memoized, -1, sizeof(memoized)); 29 | int n; 30 | cin >> n; 31 | vector length(n); 32 | for(int i = 0; i < n; i++) 33 | cin >> length[i]; 34 | int result = max_profit(length, n); 35 | cout << result; 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Dynamic Programming/rod_cutting_problem_recursive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a rod of length n inches and an array of prices that contains prices of all 3 | pieces of size smaller than n. Determine the maximum value obtainable by cutting 4 | up the rod and selling the pieces. For example, if length of the rod is 8 and the 5 | values of different pieces are given as following, then the maximum obtainable 6 | value is 22 (by cutting in two pieces of lengths 2 and 6) 7 | Input : 8 8 | : 1 5 8 9 10 17 17 20 9 | Output : 22 10 | */ 11 | // Recursive solution TC : O(2^n) 12 | // Program Author: Abhisek Kumar Gupta 13 | #include 14 | using namespace std; 15 | int max_profit(vector length, int n){ 16 | if(n == 0) return 0; 17 | int best = 0; 18 | for(int i = 0; i < n; i++){ 19 | int total_profit = length[i] + max_profit(length, n - (i + 1)); 20 | best = max(best, total_profit); 21 | } 22 | return best; 23 | } 24 | int main(){ 25 | int n; 26 | cin >> n; 27 | vector length(n); 28 | for(int i = 0; i < n; i++) 29 | cin >> length[i]; 30 | int result = max_profit(length, n); 31 | cout << result; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Dynamic Programming/trapping_rain_water.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 4 | 5 | Example 1: 6 | 7 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 8 | Output: 6 9 | 10 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 11 | Example 2: 12 | 13 | Input: height = [4,2,0,3,2,5] 14 | Output: 9 15 | 16 | Constraints: 17 | 18 | n == height.length 19 | 1 <= n <= 2 * 104 20 | 0 <= height[i] <= 105 21 | */ 22 | #include 23 | 24 | class Solution { 25 | public: 26 | int trap(vector& height) { 27 | int len = height.size(), result = 0; 28 | if(len == 0) return 0; 29 | int low = 0, high = len - 1, leftmax = 0, rightmax = 0; 30 | while(low <= high){ 31 | if(height[low] < height[high]){ 32 | if(height[low] > leftmax) 33 | leftmax = height[low]; 34 | else 35 | result += leftmax - height[low]; 36 | low++; 37 | } 38 | else{ 39 | if(height[high] > rightmax) 40 | rightmax = height[high]; 41 | else 42 | result += rightmax - height[high]; 43 | high--; 44 | } 45 | } 46 | return result; 47 | } 48 | }; -------------------------------------------------------------------------------- /Dynamic Programming/wine_selling_problem_memoized.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n wines in a row, with integers denoting the cost of each wine respectively. 3 | Each year you can sale the first or the last wine in the row. However, the price 4 | of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. 5 | On the Yth year, the profit from the ith wine will be Y*Pi. 6 | Calculate the maximum profit from all the wines. 7 | 8 | Input : 5 9 | : 2 4 6 2 5 10 | Output : 64 11 | */ 12 | // Memoized Approach TC : O(N^2) 13 | // Program Author : Abhisek Kumar Gupta 14 | 15 | #include 16 | using namespace std; 17 | int memoized[1000][1000]; 18 | int find_max_profit(int *A, int start, int end, int year){ 19 | if(start > end) 20 | return 0; 21 | if(memoized[start][end] != -1) 22 | return memoized[start][end]; 23 | int r1 = A[start] * year + find_max_profit(A, start + 1, end, year + 1); 24 | int r2 = A[end] * year + find_max_profit(A, start, end - 1, year + 1); 25 | int answer = max(r1, r2); ; 26 | memoized[start][end] = answer; 27 | return memoized[start][end]; 28 | } 29 | int main(){ 30 | memset(memoized, -1, sizeof(memoized)); 31 | int n; 32 | cin >> n; 33 | int *A; 34 | for(int i = 0; i < n; i++) 35 | cin >> A[i]; 36 | int start = 0; 37 | int end = n - 1; 38 | int year = 1; 39 | int result = find_max_profit(A, start, end, year); 40 | cout << result; 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Dynamic Programming/wine_selling_problem_recursive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n wines in a row, with integers denoting the cost of each wine respectively. 3 | Each year you can sale the first or the last wine in the row. However, the price 4 | of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. 5 | On the Yth year, the profit from the ith wine will be Y*Pi. 6 | Calculate the maximum profit from all the wines. 7 | 8 | Input : 5 9 | : 2 4 6 2 5 10 | Output : 64 11 | */ 12 | // Recursive Approach TC : O(2^n) 13 | // Program Author : Abhisek Kumar Gupta 14 | 15 | #include 16 | using namespace std; 17 | int find_max_profit(int *A, int start, int end, int year){ 18 | if(start > end) 19 | return 0; 20 | int r1 = A[start] * year + find_max_profit(A, start + 1, end, year + 1); 21 | int r2 = A[end] * year + find_max_profit(A, start, end - 1, year + 1); 22 | return max(r1, r2); 23 | } 24 | int main(){ 25 | int n; 26 | cin >> n; 27 | int *A; 28 | for(int i = 0; i < n; i++) 29 | cin >> A[i]; 30 | int start = 0; 31 | int end = n - 1; 32 | int year = 1; 33 | int result = find_max_profit(A, start, end, year); 34 | cout << result; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Famous Algorithms/euclidean_algorithm.java: -------------------------------------------------------------------------------- 1 | //extended version of Euclid's algorithm to find GCD of 2 numbers 2 | //runs in O(log N) time/space complexity for GCD of numbers a and b 3 | //in comparison, the standard Euclidean algorithm runs in O (log (min (a,b))) 4 | 5 | public class euclidean_algorithm { 6 | public static int euclid(int a, int b, int c, int d){ 7 | if(a == 0){ 8 | c = 0; 9 | d = 0; 10 | return b; 11 | } 12 | int c1 = 1,d1 = 1; 13 | int result = euclid(b%a, a, c1, d1); 14 | //update with recursive call 15 | c = d1 - (b / a) * c1; 16 | d = c1; 17 | return result; 18 | } 19 | //driver 20 | public static void main(String[] args) { 21 | int c =1, d = 1; 22 | int a = 45; 23 | int b = 10; 24 | int gcd = euclid(a, b, c, d); 25 | System.out.print("gcd of "+ a+"," +b +" is equal to: " + gcd); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Famous Algorithms/euclidean_algorithm.js: -------------------------------------------------------------------------------- 1 | //extended version of Euclid's algorithm to find GCD of 2 numbers 2 | //runs in O(log N) time/space complexity for GCD of numbers a and b 3 | //in comparison, the standard Euclidean algorithm runs in O (log (min (a,b))) 4 | 5 | 6 | function euclid(a,b,c,d){ 7 | if(a == 0){ 8 | c = 0; 9 | d = 1; 10 | return b; 11 | } 12 | let result = euclid(b%a,a,c,d); 13 | //update with recursive values 14 | c = d- (b / a) * c; 15 | d = c; 16 | return result; 17 | } 18 | //modify a and b to find gcd of any 2 numbers 19 | let a = 450; 20 | let b = 100; 21 | let gcd = euclid(a,b,0,0); 22 | console.log(`GCD of ${a}, ${b} is equal to ${gcd}`); 23 | -------------------------------------------------------------------------------- /Famous Algorithms/euclidean_algorithm.py: -------------------------------------------------------------------------------- 1 | #extended version of Euclid's algorithm to find GCD of 2 numbers 2 | #runs in O(log N) time/space complexity for GCD of numbers a and b 3 | #in comparison, the standard Euclidean algorithm runs in O (log (min (a,b))) 4 | 5 | def euclidExtended(a,b): 6 | if a==0: 7 | return b,0, 1 8 | result, a1, b1 = euclidExtended(b%a,a) 9 | 10 | a2 = b1- (b//a) *a1 11 | b2 = a1 12 | return result, a2, b2 #used as input to recursive call, 13 | 14 | #example driver, change a and b as desired 15 | 16 | a,b = 45,10 17 | g,x,y = euclidExtended(a,b) 18 | print("gcd of", a,"," ,b ,"is equal to: " , g) 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Famous Algorithms/kmp.py: -------------------------------------------------------------------------------- 1 | # Implementation of KMP Algorithm. Program Author : SNEHA CHAUHAN 2 | ''' problem: Given a text txt and a pattern pat, write a function search(char pat[], char txt[]) 3 | that prints all occurrences of pat[] in txt[]. 4 | 5 | KMP algorithm is used to find the pattern in the given string. This is naive approach to find 6 | the pattern in the given string. 7 | 8 | Time Complexity: O(n*m) 9 | Space Complexity: O(1) 10 | 11 | Example: 12 | input: txt = “AAAABAAABA” pat = “AAAA” 13 | output: Pattern found at index 0 14 | 15 | Algorithm: 16 | 1. Start from the leftmost character of txt and one by one compare it with each character of pat. 17 | 2. If a character matches, then move both txt and pat ahead and compare the next character. 18 | 3. If a mismatch occurs, then move pat to the index where the mismatch occurs and compare again. 19 | 4. If pat reaches its end without any mismatch, then pattern found. 20 | 21 | ''' 22 | 23 | def search(pat, txt): 24 | M = len(pat) 25 | N = len(txt) 26 | 27 | # A loop to slide pat[] one by one 28 | for i in range(N - M + 1): 29 | j = 0 30 | 31 | # For current index i, check for pattern match 32 | for j in range(0, M): 33 | if (txt[i + j] != pat[j]): 34 | break 35 | 36 | if (j == M - 1): 37 | print("Pattern found at index ", i) 38 | 39 | 40 | # Driver Code 41 | if __name__ == '__main__': 42 | txt = "AABAACAADAABAAABAA" 43 | pat = "AABA" 44 | search(pat, txt) -------------------------------------------------------------------------------- /Fast and Slow Pointers/happy_number.go: -------------------------------------------------------------------------------- 1 | /* 2 | Write an algorithm to determine if a number num is happy. 3 | 4 | A happy number is a number defined by the following process: 5 | 6 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 7 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1 8 | 9 | Those numbers for which this process ends in 1 are happy. 10 | Return TRUE if num is a happy number, and FALSE if not. 11 | 12 | Sample Input : 4 13 | Output: False 14 | 15 | Sample Input : 19 16 | Output: True 17 | 18 | */ 19 | 20 | package main 21 | 22 | import "fmt" 23 | 24 | // pow calculates the power of the given digit 25 | func pow(digit int, power int) int { 26 | res := 1 27 | for i := 0; i < power; i++ { 28 | res = res * digit 29 | } 30 | return res 31 | } 32 | 33 | // sumDigits is a helper function that calculates the sum of digits. 34 | func sumDigits(number int) int { 35 | totalSum := 0 36 | for number > 0 { 37 | digit := number % 10 38 | number = number / 10 39 | totalSum += pow(digit, 2) 40 | } 41 | return totalSum 42 | } 43 | 44 | func happyNumber(num int) bool { 45 | slow := num 46 | fast := sumDigits(num) 47 | for fast != 1 && fast != slow { 48 | slow = sumDigits(slow) 49 | fast = sumDigits(sumDigits(fast)) 50 | } 51 | return fast == 1 52 | } 53 | 54 | func main() { 55 | fmt.Println(happyNumber(4)) // false 56 | fmt.Println(happyNumber(19)) // true 57 | fmt.Println(happyNumber(100)) // true 58 | } -------------------------------------------------------------------------------- /Fast and Slow Pointers/linked_list_find_middle.py: -------------------------------------------------------------------------------- 1 | # Finding Midpoint of a LinkedList 2 | # Node class 3 | class Node: 4 | 5 | # Function to initialise the node object 6 | def __init__(self, data): 7 | self.data = data 8 | self.next = None 9 | 10 | class LinkedList: 11 | 12 | def __init__(self): 13 | self.head = None 14 | 15 | def push(self, new_data): 16 | new_node = Node(new_data) 17 | new_node.next = self.head 18 | self.head = new_node 19 | 20 | 21 | 22 | # Function to get the middle of 23 | # the linked list using pointers 24 | def printMiddle(self): 25 | slow_ptr = self.head 26 | fast_ptr = self.head 27 | 28 | if self.head is not None: 29 | while (fast_ptr is not None and fast_ptr.next is not None): 30 | fast_ptr = fast_ptr.next.next 31 | slow_ptr = slow_ptr.next 32 | print("The middle element is: ", slow_ptr.data) 33 | 34 | 35 | 36 | # Driver code 37 | list1 = LinkedList() 38 | list1.push(25) 39 | list1.push(33) 40 | list1.push(14) 41 | list1.push(22) 42 | list1.push(9) 43 | list1.push(11) 44 | list1.push(20) 45 | list1.printMiddle() 46 | -------------------------------------------------------------------------------- /Fast and Slow Pointers/linked_list_floyds_cycle_detection.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Floyds Cycle detection and removal 3 | Program Author : Abhisek Kumar Gupta 4 | The cycle detection problem is to find the cycle in a sequence, 5 | and Floyd’s cycle detection algorithm, aka Tortoise and Hare algorithm, 6 | is a two-pointer algorithm to detect the cycle and locate the start of the cycle as well. 7 | ''' 8 | # Definition for singly-linked list. 9 | # class ListNode: 10 | # def __init__(self, x): 11 | # self.val = x 12 | # self.next = None 13 | 14 | class Solution: 15 | def hasCycle(self, head: Optional[ListNode]) -> bool: 16 | #Floyd's cycle detection algorithm uses slow and fast points to find the loop 17 | #Reference - https://www.geeksforgeeks.org/floyds-cycle-finding-algorithm/ 18 | slow,fast= head,head 19 | while(slow!=None and fast!=None and fast.next!=None): 20 | slow = slow.next 21 | fast = fast.next.next 22 | if(slow == fast): 23 | return True 24 | return False -------------------------------------------------------------------------------- /Graphs/Graphs_bfs.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Graph: 4 | def __init__(self): 5 | self.graph = defaultdict(list) 6 | 7 | def insertEdge(self,v1,v2): 8 | self.graph[v1].append(v2) 9 | 10 | def subBfs(self,visited,queue): 11 | while(queue): 12 | v=queue.pop(0) 13 | visited.add(v) 14 | print(v,end=" ") 15 | 16 | for neighbour in self.graph[v]: 17 | if neighbour not in visited: 18 | queue.append(neighbour) 19 | visited.add(neighbour) 20 | 21 | def bfs(self,v): 22 | visited=set() 23 | queue=[v] 24 | self.subBfs(visited,queue) 25 | 26 | g=Graph() 27 | g.insertEdge(1,2) 28 | g.insertEdge(2,1) 29 | g.insertEdge(2,3) 30 | g.insertEdge(3,4) 31 | g.insertEdge(4,5) 32 | g.insertEdge(5,6) 33 | g.insertEdge(2,6) 34 | 35 | g.bfs(1) 36 | -------------------------------------------------------------------------------- /Graphs/Graphs_dfs.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Graph: 4 | def __init__(self): 5 | self.graph = defaultdict(list) 6 | 7 | def insertEdge(self,v1,v2): 8 | self.graph[v1].append(v2) 9 | 10 | def dfsSub(self,v,visited): 11 | 12 | visited.add(v) 13 | print(v,end=" ") 14 | 15 | for neighbour in self.graph[v]: 16 | if neighbour not in visited: 17 | self.dfsSub(neighbour,visited) 18 | 19 | def dfs(self,v): 20 | 21 | visited = set() 22 | self.dfsSub(v,visited) 23 | 24 | g=Graph() 25 | g.insertEdge(1,2) 26 | g.insertEdge(2,1) 27 | g.insertEdge(3,4) 28 | g.insertEdge(4,5) 29 | g.insertEdge(5,6) 30 | g.insertEdge(2,6) 31 | 32 | g.dfs(2) 33 | 34 | -------------------------------------------------------------------------------- /Graphs/graphs_adjacency_list.cpp: -------------------------------------------------------------------------------- 1 | // Graphs Adjacency List implementation 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | 6 | class Graph{ 7 | public: 8 | int V; 9 | list *L; // a pointer to an array of linkedlist 10 | Graph(int v){ 11 | V = v; 12 | L = new list[V]; // Array of LL 13 | // there is a pointer to an array whose size is v and every object is list of integer 14 | } 15 | void addEdge(int u, int v, bool bidir = true){ 16 | L[u].push_back(v); 17 | if(bidir){ 18 | L[v].push_back(u); 19 | } 20 | } 21 | void printAdjacencyList(){ 22 | for(int i = 0; i < V; i++){ 23 | cout << i << "-> "; 24 | for(auto vertex : L[i]){ 25 | cout << vertex << ", "; 26 | } 27 | cout << endl; 28 | } 29 | } 30 | }; 31 | int main(){ 32 | //graph has 5 vertices numbered from 0-4 33 | Graph g(5); 34 | g.addEdge(0, 1); 35 | g.addEdge(0, 4); 36 | g.addEdge(1, 4); 37 | g.addEdge(1, 3); 38 | g.addEdge(1, 2); 39 | g.addEdge(2, 3); 40 | g.addEdge(4, 3); 41 | g.printAdjacencyList(); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Graphs/graphs_adjacency_list_generic.cpp: -------------------------------------------------------------------------------- 1 | // Graphs Adjacency List implementation for Generic Data 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | 6 | template 7 | class Graph{ 8 | map > adjList; 9 | public: 10 | Graph(){ 11 | 12 | } 13 | void addEdge(T u, T v, bool bidir = true){ 14 | adjList[u].push_back(v); 15 | if(bidir){ 16 | adjList[v].push_back(u); 17 | } 18 | } 19 | void printAdjList(){ 20 | for(auto obj : adjList){ 21 | cout << obj.first << "->"; 22 | for(auto element : obj.second){ 23 | cout << element << ","; 24 | } 25 | cout << endl; 26 | } 27 | } 28 | }; 29 | int main(){ 30 | Graph g; 31 | g.addEdge("Ashish", "Asif", false); 32 | g.addEdge("Ashish", "Abhisek", false); 33 | g.addEdge("Ashish", "Amir", false); 34 | g.addEdge("Abhisek", "Asif", true); 35 | g.addEdge("Abhisek", "Anvesh", true); 36 | g.addEdge("Anvesh", "Sai", false); 37 | g.addEdge("Sai", "Abhisek", false); 38 | g.printAdjList(); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Graphs/topological_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implementation of Topological sort using DFS 3 | According to Introduction to Algorithms, given a directed acyclic graph (DAG), 4 | a topological sort is a linear ordering of all vertices such that for any edge 5 | (u, v), u comes before v. Another way to describe it is that when you put all 6 | vertices horizontally on a line, all of the edges are pointing from left to right. 7 | 8 | Time complexity O(Vertices + Edges) 9 | """ 10 | 11 | def main(): 12 | adj_list = { 13 | 5: [2, 0], 14 | 4: [0, 1], 15 | 3: [1], 16 | 2: [3], 17 | 1: [], 18 | 0: [] 19 | } 20 | 21 | dfs(adj_list, set(), []) 22 | 23 | 24 | 25 | def dfs(adj_list, visited, stack): 26 | for vertex in range(6): 27 | if vertex in visited: 28 | continue 29 | dfs_visit(adj_list, visited, vertex, stack) 30 | 31 | print(stack[::-1]) 32 | 33 | 34 | def dfs_visit(adj_list, visited, node, stack): 35 | visited.add(node) 36 | 37 | for neighbor in adj_list[node]: 38 | if neighbor in visited: 39 | continue 40 | dfs_visit(adj_list, visited, neighbor, stack) 41 | 42 | stack.append(node) 43 | 44 | 45 | 46 | if __name__ == "__main__": 47 | main() -------------------------------------------------------------------------------- /Greedy/coin_change.go: -------------------------------------------------------------------------------- 1 | /* 2 | The coin change problem is a classic algorithmic problem, where given a target amount and a set of coin 3 | denominations, we need to find the minimum number of coins required to make up that amount. 4 | 5 | In this implementation, we start by sorting the array of coin denominations in descending order. 6 | We then iterate through the array from largest to smallest denomination, and for each denomination, 7 | we repeatedly subtract the largest possible multiple of that denomination from the target amount 8 | until we reach 0. 9 | 10 | The time complexity of this algorithm is O(n log n) due to the sorting step, where n is the number 11 | of coin denominations. However, the space complexity is O(1) since we are only using a constant 12 | amount of extra space. 13 | 14 | For the sample input coins := []int{1, 5, 10, 25} and target := 36, the output should be Minimum 15 | number of coins required to make 36 cents: 3. 16 | */ 17 | package main 18 | 19 | import "fmt" 20 | 21 | func coinChangeGreedy(coins []int, target int) int { 22 | count := 0 23 | for i := len(coins) - 1; i >= 0; i-- { 24 | for target >= coins[i] { 25 | target -= coins[i] 26 | count++ 27 | } 28 | } 29 | return count 30 | } 31 | 32 | func main() { 33 | coins := []int{1, 5, 10, 25} 34 | target := 36 35 | result := coinChangeGreedy(coins, target) 36 | fmt.Printf("Minimum number of coins required to make %d cents: %d\n", target, result) 37 | } 38 | -------------------------------------------------------------------------------- /Greedy/coin_change.js: -------------------------------------------------------------------------------- 1 | 2 | function coinChangeGreedy(s, l) { 3 | // First step: sort l in descending order 4 | l.sort((a, b) => b - a); 5 | 6 | let r = []; // Result list 7 | let sumr = 0; // Keep track of the current sum of r to avoid iterating over r to calculate the sum 8 | 9 | for (let coin of l) { 10 | if (sumr === s) { // The sum of r is the target sum s 11 | break; 12 | } 13 | 14 | let n = Math.floor((s - sumr) / coin); // Calculate the max n with sum(r) + l[i] * n <= s 15 | 16 | for (let i = 0; i < n; i++) { // Append n elements of this coin to r 17 | r.push(coin); 18 | } 19 | 20 | sumr += coin * n; // Update the sum of r 21 | } 22 | 23 | if (sumr !== s) { // The target sum s was not reached 24 | return false; 25 | } 26 | 27 | return r; 28 | } 29 | 30 | // SAMPLE 1 (optimal) 31 | console.log(coinChangeGreedy(60, [5, 10, 25])); 32 | 33 | // SAMPLE 2 (not optimal) 34 | console.log(coinChangeGreedy(50, [25, 10, 30, 5])); 35 | 36 | // SAMPLE 3 (fails) 37 | console.log(coinChangeGreedy(50, [25, 30])); 38 | -------------------------------------------------------------------------------- /Hash Table/Count_Pairs_of_Points_With_Distance_k.py: -------------------------------------------------------------------------------- 1 | #Given a 2D integer array coordinates and an integer k, where coordinates[i] = [xi, yi] are the coordinates of the ith point in a 2D plane. 2 | 3 | #We define the distance between two points (x1, y1) and (x2, y2) as (x1 XOR x2) + (y1 XOR y2) where XOR is the bitwise XOR operation. 4 | 5 | #Return the number of pairs (i, j) such that i < j and the distance between points i and j is equal to k. 6 | 7 | def count_pairs(coordinates, k): 8 | result = 0 9 | seen = {} 10 | 11 | for x, y in coordinates: 12 | for split in range(k + 1): 13 | x_complement = x ^ split 14 | y_complement = y ^ (k - split) 15 | result += seen.get((x_complement, y_complement), 0) 16 | seen[x, y] = seen.get((x, y), 0) + 1 17 | 18 | return result 19 | 20 | # Take user input for coordinates 21 | coordinates = [] 22 | num_coordinates = int(input("Enter the number of coordinates: ")) 23 | 24 | for i in range(num_coordinates): 25 | x = int(input(f"Enter x-coordinate for point {i + 1}: ")) 26 | y = int(input(f"Enter y-coordinate for point {i + 1}: ")) 27 | coordinates.append((x, y)) 28 | 29 | # Take user input for k 30 | k = int(input("Enter the value of k: ")) 31 | 32 | pair_count = count_pairs(coordinates, k) 33 | print(f"Number of pairs that satisfy the condition: {pair_count}") 34 | -------------------------------------------------------------------------------- /Hash Table/first_repeated_character.go: -------------------------------------------------------------------------------- 1 | // Program to find first repeating character in a word 2 | // Sample Input : "DataStructures" 3 | // Output: a 4 | 5 | package main 6 | 7 | import "fmt" 8 | 9 | func FirstRepeatedCCharacter(word string) byte { 10 | length := len(word) 11 | 12 | hMap := [256]int{} // Extended Ascii can support 256 different characters 13 | 14 | // initialize hMap values to 0 15 | for i := 0; i < 256; i++ { 16 | hMap[i] = 0 17 | } 18 | 19 | // every time you see a character in a word increment its position in hMap 20 | for i := 0; i < length; i++ { 21 | // if character is already present incase "1" then return character 22 | if hMap[word[i]] == 1 { 23 | return word[i] 24 | } 25 | // increment value in position of character 26 | hMap[word[i]]++ 27 | } 28 | return byte(0) 29 | } 30 | 31 | func main() { 32 | fmt.Printf("%c",FirstRepeatedCCharacter("DataStructures")) 33 | } -------------------------------------------------------------------------------- /Hash Table/group_anagrams.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akgmage/data-structures-and-algorithms/a9d5f0c556b70a787a0c834bf2b1ea40ec39858d/Hash Table/group_anagrams.class -------------------------------------------------------------------------------- /Hash Table/integer_to_roman.go: -------------------------------------------------------------------------------- 1 | // Integer to Roman 2 | /* 3 | In this implementation, we create two arrays symbols and values that hold the Roman numeral symbols and their 4 | corresponding integer values respectively. We then create a string builder to hold our result. 5 | 6 | We loop through the values array, and while the current num is greater than or equal to the current values 7 | element, we subtract the values element from num and append the corresponding symbols element to the result 8 | string builder. We continue this process until we have gone through all the values elements. 9 | 10 | Finally, we return the result string. 11 | */ 12 | package main 13 | 14 | import "strings" 15 | 16 | func intToRoman(num int) string { 17 | // Create two arrays to hold the Roman numeral symbols and their corresponding values 18 | symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} 19 | values := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1} 20 | 21 | var result strings.Builder 22 | // Loop through the values array and subtract the corresponding value from num while appending the symbol to the result 23 | for i := 0; i < len(values); i++ { 24 | for num >= values[i] { 25 | num -= values[i] 26 | result.WriteString(symbols[i]) 27 | } 28 | } 29 | 30 | return result.String() 31 | } 32 | 33 | func main() { 34 | print(intToRoman(8000)) 35 | } -------------------------------------------------------------------------------- /Hash Table/integer_to_roman.js: -------------------------------------------------------------------------------- 1 | // Integer to Roman 2 | /* 3 | This solution uses a greedy approach to build the roman numeral string by subtracting the maximum 4 | possible value at each step until the input number is zero. The time complexity of this implementation 5 | is O(1) since there is a fixed number of roman numerals and the loop will always run 13 times. 6 | The space complexity is also O(1) since we only store a single string. 7 | */ 8 | function intToRoman(num) { 9 | // Create arrays for the symbols and their values 10 | const symbols = [ 11 | "M", 12 | "CM", 13 | "D", 14 | "CD", 15 | "C", 16 | "XC", 17 | "L", 18 | "XL", 19 | "X", 20 | "IX", 21 | "V", 22 | "IV", 23 | "I", 24 | ]; 25 | const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; 26 | 27 | let result = ""; // Initialize an empty string to store the roman numeral 28 | 29 | // Loop through the values array 30 | for (let i = 0; i < values.length; i++) { 31 | // While the input num is greater than or equal to the current value 32 | while (num >= values[i]) { 33 | result += symbols[i]; // Add the corresponding symbol to the result string 34 | num -= values[i]; // Subtract the value from the input num 35 | } 36 | } 37 | 38 | return result; // Return the roman numeral string 39 | } 40 | -------------------------------------------------------------------------------- /Hash Table/remove_duplicates.go: -------------------------------------------------------------------------------- 1 | // Given an array of integers, give an algorithm for removing the duplicates. 2 | package main 3 | 4 | import "fmt" 5 | 6 | // RemoveDuplicates: returns new string without duplicate characters 7 | // Approach: use hash table to see if value already exists or not, if it does the skip the value 8 | // else append it to the result string 9 | // Time Complexity: Θ(n) on average. Space Complexity: O(n). 10 | func RemoveDuplicates(word string) string { 11 | result := "" 12 | mp := map[byte]bool{} 13 | for i:= 0; i < len(word); i++ { 14 | if mp[word[i]] == true { 15 | // current character exist in hash table so do nothing 16 | } else { 17 | // mark as true(insert into hashtable) and add to result string 18 | mp[word[i]] = true 19 | result = result + string(word[i]) 20 | } 21 | } 22 | return result 23 | } 24 | 25 | func main() { 26 | fmt.Println(RemoveDuplicates("aabbcaaacdd")); 27 | } -------------------------------------------------------------------------------- /Hash Table/roman_to_integer.js: -------------------------------------------------------------------------------- 1 | // Approach: In case of symbols like IV, CM, XC, etc., the first value is less than the second value. 2 | // So we have to subtract the first value from the second value to get the exact value. 3 | // Example: CM --> C=100, M=1000, so CM=1000-100=900. 4 | // Therefore, we can conclude that in such cases, we have to subtract the first value from the whole result. 5 | // Time complexity O(1) and Space complexity O(1). 6 | var romanToInt = function(s) { 7 | let map = new Map(); // Create a hashmap to store (symbol, value) pairs. 8 | map['I'] = 1; 9 | map['V'] = 5; 10 | map['X'] = 10; 11 | map['L'] = 50; 12 | map['C'] = 100; 13 | map['D'] = 500; 14 | map['M'] = 1000; 15 | 16 | let arr = []; 17 | for (let i = 0; i < s.length; i++) { // Store the value of each symbol in arr from left to right. 18 | arr[i] = map[s.charAt(i)]; 19 | } 20 | 21 | let ans = 0; 22 | for (let i = 0; i < arr.length - 1; i++) { // Traverse from 0 to last-1. 23 | // If the i-th element is less than the i+1-th element, then subtract the i-th element. 24 | if (arr[i] < arr[i + 1]) { 25 | ans = ans - arr[i]; 26 | } 27 | // Otherwise, add the i-th element. 28 | else { 29 | ans = ans + arr[i]; 30 | } 31 | } 32 | // Add the last element because there is no further element to compare. 33 | ans = ans + arr[arr.length - 1]; 34 | return ans; 35 | }; 36 | -------------------------------------------------------------------------------- /Hash Table/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | # Roman to Integer 2 | ''' 3 | The function takes a string s as an input and returns the corresponding integer value 4 | by converting the string from Roman numerals to its integer value. 5 | 6 | It does this by iterating through the string. If the current character has a lower 7 | value than the character after it, the current character value is subtracted from 8 | the total, so that it is added correctly. 9 | 10 | Otherwise, the current character value is added to the total. 11 | 12 | Finally, the total integer value is returned. 13 | ''' 14 | 15 | def roman_to_int(s: str) -> int: 16 | # define mapping of values to symbols 17 | symbols = { 18 | 'I': 1, 19 | 'V': 5, 20 | 'X': 10, 21 | 'L': 50, 22 | 'C': 100, 23 | 'D': 500, 24 | 'M': 1000 25 | } 26 | 27 | # initialise integer to return total value 28 | total = 0 29 | 30 | # iterate through characters 31 | for i in range(len(s) - 1): 32 | # if the symbol after current symbol is less than it, 33 | # subtract it from the total value 34 | if symbols[s[i]] < symbols[s[i+1]]: 35 | total -= symbols[s[i]] 36 | # else, just add the corresponding value 37 | else: 38 | total += symbols[s[i]] 39 | # add the last value 40 | total += symbols[s[-1]] 41 | 42 | return total -------------------------------------------------------------------------------- /Hash Table/sum_of_unique_elements.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /* 4 | You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. 5 | 6 | Return the sum of all the unique elements of nums. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,2,3,2] 13 | Output: 4 14 | Explanation: The unique elements are [1,3], and the sum is 4. 15 | Example 2: 16 | 17 | Input: nums = [1,1,1,1,1] 18 | Output: 0 19 | Explanation: There are no unique elements, and the sum is 0. 20 | Example 3: 21 | 22 | Input: nums = [1,2,3,4,5] 23 | Output: 15 24 | Explanation: The unique elements are [1,2,3,4,5], and the sum is 15. 25 | 26 | Constraints: 27 | 28 | 1 <= nums.length <= 100 29 | 1 <= nums[i] <= 100 30 | */ 31 | class Solution { 32 | public int sumOfUnique(int[] nums) { 33 | HashMap hm=new HashMap(); 34 | int sum=0; 35 | for(int x:nums) 36 | { 37 | if(hm.containsKey(x)) 38 | hm.put(x,hm.get(x)+1); 39 | else 40 | hm.put(x,1); 41 | } 42 | for(int x:nums) 43 | { 44 | if(hm.get(x)== 1) 45 | sum+=x; 46 | } 47 | return sum; 48 | } 49 | } 50 | class SumOfUniqueElements { 51 | public static void main(String[] args) { 52 | int arr[] = {1,2,2,3}; 53 | Solution s = new Solution(); 54 | System.out.println(s.sumOfUnique(arr)); 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Heaps/k_closest.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: 3 | min_heap = [] 4 | 5 | # For each point, find distance from origin 6 | for x,y in points: 7 | dist = sqrt(x**2 + y**2) 8 | min_heap.append([dist,x,y]) 9 | 10 | # Pop 'k' smallest distances 11 | heapify(min_heap) 12 | res = [] 13 | for _ in range(k): 14 | _,x,y = heappop(min_heap) 15 | res.append([x,y]) 16 | 17 | return res -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2022] [Abhisek Kumar Gupta] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Linked List/Intersection_LL.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 | ListNode *pA = headA; 13 | ListNode *pB = headB; 14 | 15 | // Traverse both linked lists until they meet or reach the end (NULL) 16 | while (pA != pB) { 17 | // Move pointers to the next node 18 | pA = (pA != nullptr) ? pA->next : headB; 19 | pB = (pB != nullptr) ? pB->next : headA; 20 | } 21 | 22 | // Return the intersection node (or NULL if no intersection) 23 | return pA; 24 | } 25 | }; 26 | 27 | /* 28 | Explanation: 29 | The provided code implements the solution to find the intersection point of two singly-linked lists headA and headB. The getIntersectionNode function takes two ListNode pointers as parameters and returns the intersection node if one exists, or NULL if there is no intersection. 30 | 31 | The approach used here is based on the concept of "runner pointers." The pointers pA and pB start from the heads of the two linked lists and traverse through the lists. When a pointer reaches the end of its list, it is redirected to the head of the other list. This ensures that the pointers will meet at the intersection point if it exists, or they will both reach the end of the lists (NULL) simultaneously if there is no intersection. 32 | */ 33 | -------------------------------------------------------------------------------- /Linked List/MiddleofLL.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, value=0, next=None): 3 | self.value = value 4 | self.next = next 5 | 6 | def find_middle(head): 7 | # Initialize slow and fast pointers to the head of the linked list 8 | slow_ptr = head 9 | fast_ptr = head 10 | 11 | # Traverse the linked list with slow and fast pointers 12 | while fast_ptr is not None and fast_ptr.next is not None: 13 | # Move slow pointer one step at a time 14 | slow_ptr = slow_ptr.next 15 | # Move fast pointer two steps at a time 16 | fast_ptr = fast_ptr.next.next 17 | 18 | # When the fast pointer reaches the end, the slow pointer will be at the middle 19 | return slow_ptr 20 | 21 | # Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5 22 | head = ListNode(1) 23 | head.next = ListNode(2) 24 | head.next.next = ListNode(3) 25 | head.next.next.next = ListNode(4) 26 | head.next.next.next.next = ListNode(5) 27 | 28 | # Find the middle node of the linked list 29 | middle_node = find_middle(head) 30 | 31 | # Print the value of the middle node 32 | print("Middle Node:", middle_node.value) # Output: Middle Node: 3 33 | -------------------------------------------------------------------------------- /Linked List/linked_list_delete_at_head.cpp: -------------------------------------------------------------------------------- 1 | // Delete from Head in a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | void insert_at_head(node *&head, int data){ 16 | node *n = new node(data); 17 | n->next = head; 18 | head = n; 19 | } 20 | void delete_at_head(node *&head){ 21 | if(head == NULL){ 22 | return; 23 | } 24 | node *temp = head; 25 | head = head->next; 26 | delete temp; 27 | } 28 | void print_linked_list(node *head){ 29 | while(head != NULL){ 30 | cout << head->data << "->"; 31 | head = head->next; 32 | } 33 | } 34 | int main(){ 35 | node *head = NULL; 36 | insert_at_head(head, 1); 37 | insert_at_head(head, 2); 38 | insert_at_head(head, 3); 39 | print_linked_list(head); 40 | cout << endl; 41 | delete_at_head(head); 42 | delete_at_head(head); 43 | print_linked_list(head); 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Linked List/linked_list_delete_at_tail.cpp: -------------------------------------------------------------------------------- 1 | // Delete from Tail in a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | void insert_at_tail(node *&head, int data){ 17 | if(head == NULL){ 18 | head = new node(data); 19 | return; 20 | } 21 | node *n = new node(data); 22 | node * temp = head; 23 | while(temp -> next != NULL){ 24 | temp = temp->next; 25 | } 26 | temp->next = n; 27 | } 28 | void delete_at_tail(node *&head){ 29 | node *prev = NULL; 30 | node *temp = head; 31 | while(temp->next != NULL){ 32 | prev = temp; 33 | temp = temp->next; 34 | } 35 | prev->next = NULL; 36 | delete temp; 37 | } 38 | void print_linked_list(node *head){ 39 | while(head != NULL){ 40 | cout << head->data << "->"; 41 | head = head->next; 42 | } 43 | } 44 | int main(){ 45 | node *head = NULL; 46 | insert_at_tail(head, 20); 47 | insert_at_tail(head, 33); 48 | insert_at_tail(head, 100); 49 | insert_at_tail(head, 200); 50 | insert_at_tail(head, 201); 51 | insert_at_tail(head, 202); 52 | print_linked_list(head); 53 | cout << endl; 54 | delete_at_tail(head); 55 | delete_at_tail(head); 56 | 57 | print_linked_list(head); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Linked List/linked_list_delete_node.go: -------------------------------------------------------------------------------- 1 | /* 2 | We are given a pointer to a node (not the tail node) in a singly linked list. Delete that node from the 3 | linked list. 4 | */ 5 | package main 6 | 7 | /* 8 | Approach: 9 | 1. We can move the data from the next node into the current node 10 | 2. Delete the next node. 11 | Time Complexity: O(1). Space Complexity: O(1). 12 | */ 13 | func deleteNode(node *ListNode) { 14 | temp = node.next 15 | node.data = node.next.data 16 | node.next = temp.next 17 | temp = nil 18 | } -------------------------------------------------------------------------------- /Linked List/linked_list_even_or_odd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Check whether the given Linked List length is even or odd? 3 | 4 | Approach: 5 | Use a 2x pointer. Take a pointer that moves at 2x [two nodes at a time]. At the end, if the length is even, 6 | then the pointer will be nil; otherwise it will point to the last node. 7 | */ 8 | // Time Complexity: O(⌊n/2⌋) ≈O(n). Space Complexity: O(1). 9 | package main 10 | 11 | // has two fields [data] of type integer and [next] of type *node (holds the memory address of next node) 12 | type node struct { 13 | data int 14 | next *node 15 | } 16 | //has three fields length, head and tail node 17 | type LinkedList struct { 18 | length int 19 | head *node 20 | tail *node 21 | } 22 | 23 | func (ll *LinkedList) IsLengthEven() bool { 24 | current := ll.head 25 | for current != nil && current.next != nil { 26 | current = current.next.next 27 | } 28 | if current != nil { 29 | return false 30 | } 31 | return true 32 | } -------------------------------------------------------------------------------- /Linked List/linked_list_find_length.cpp: -------------------------------------------------------------------------------- 1 | // Find length of a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | 4 | #include 5 | using namespace std; 6 | class node{ 7 | public: 8 | int data; 9 | node* next; 10 | 11 | node(int d){ 12 | data = d; 13 | next = NULL; 14 | } 15 | }; 16 | int length(node* head){ 17 | int len = 0; 18 | while(head != NULL){ 19 | head = head->next; 20 | len++; 21 | } 22 | return len; 23 | } 24 | void insert_at_head(node *&head, int data){ 25 | node *n = new node(data); 26 | n->next = head; 27 | head = n; 28 | } 29 | void print_linked_list(node *head){ 30 | while(head != NULL){ 31 | cout << head->data << "->"; 32 | head = head->next; 33 | } 34 | } 35 | int main(){ 36 | node *head = NULL; 37 | insert_at_head(head, 1); 38 | insert_at_head(head, 2); 39 | insert_at_head(head, 3); 40 | print_linked_list(head); 41 | int len = length(head); 42 | cout << endl < 5 | using namespace std; 6 | class node{ 7 | public: 8 | int data; 9 | node* next; 10 | 11 | node(int d){ 12 | data = d; 13 | next = NULL; 14 | } 15 | }; 16 | void insert_at_head(node *&head, int data){ 17 | node *n = new node(data); 18 | n->next = head; 19 | head = n; 20 | } 21 | void print_linked_list(node *head){ 22 | while(head != NULL){ 23 | cout << head->data << "->"; 24 | head = head->next; 25 | } 26 | } 27 | int main(){ 28 | node *head = NULL; 29 | insert_at_head(head, 1); 30 | insert_at_head(head, 2); 31 | insert_at_head(head, 3); 32 | print_linked_list(head); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Linked List/linked_list_insert_at_tail.cpp: -------------------------------------------------------------------------------- 1 | // Insert at Tail in a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | void insert_at_tail(node *&head, int data){ 17 | if(head == NULL){ 18 | head = new node(data); 19 | return; 20 | } 21 | node *n = new node(data); 22 | node * temp = head; 23 | while(temp -> next != NULL){ 24 | temp = temp->next; 25 | } 26 | temp->next = n; 27 | } 28 | void print_linked_list(node *head){ 29 | while(head != NULL){ 30 | cout << head->data << "->"; 31 | head = head->next; 32 | } 33 | } 34 | int main(){ 35 | node *head = NULL; 36 | insert_at_tail(head, 20); 37 | insert_at_tail(head, 33); 38 | insert_at_tail(head, 100); 39 | insert_at_tail(head, 200); 40 | print_linked_list(head); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Linked List/linked_list_kth_from_end.go: -------------------------------------------------------------------------------- 1 | // Finding Kth node from end of a LinkedList 2 | package main 3 | 4 | /* 5 | Approach 6 | 1. Make two pointers slow and fast and keep them both on the head of the linked list. 7 | 2. Now, move the fast pointer k steps away from the slow pointer. 8 | 3. Now, move the fast pointer and the slow pointer each one step at a time till 9 | the fast pointer reaches the tail of the linked list. When the fast pointer reaches the tail, 10 | the node at which the slow pointer resides will be our answer. 11 | 12 | Time and space complexity 13 | 14 | Time complexity of the solution is O(n) as we have traversed the linked list once. 15 | We have traversed it in two parts. 16 | First we traversed k elements and then we traversed the remaining (size minus k) elements. 17 | 18 | Space complexity is O(1) as we have not used any extra space for the solution. 19 | 20 | 21 | */ 22 | func kthFromEnd(head *ListNode, n int) *ListNode { 23 | first, second := head, head 24 | for ; n > 0; n-- { 25 | second = second.next 26 | } 27 | for ; second.next != nil; first, second = first.next, second.next { 28 | } 29 | first.next = first.next.next 30 | return first 31 | } -------------------------------------------------------------------------------- /Linked List/linked_list_linear_search.cpp: -------------------------------------------------------------------------------- 1 | // Search linearly in a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | bool linear_search(node *head, int key){ 16 | if(head == NULL){ 17 | return false; 18 | } 19 | else{ 20 | node *temp = head; 21 | while(temp != NULL){ 22 | if(temp->data == key){ 23 | return true; 24 | } 25 | temp = temp->next; 26 | } 27 | } 28 | return false; 29 | } 30 | void insert_at_head(node *&head, int data){ 31 | node *n = new node(data); 32 | n->next = head; 33 | head = n; 34 | } 35 | void print_linked_list(node *head){ 36 | while(head != NULL){ 37 | cout << head->data << "->"; 38 | head = head->next; 39 | } 40 | } 41 | int main(){ 42 | node *head = NULL; 43 | insert_at_head(head, 1); 44 | insert_at_head(head, 2); 45 | insert_at_head(head, 3); 46 | print_linked_list(head); 47 | cout << endl; 48 | if(linear_search(head, 1)){ 49 | cout << "Found"; 50 | } 51 | else{ 52 | cout << "Not Found"; 53 | } 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Linked List/linked_list_middle.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. 3 | * 4 | * Example #1: 5 | * Input: head = [1,2,3,4,5] 6 | * Output: [3,4,5] 7 | * Explanation: The middle node of the list is node 3. 8 | * 9 | * Example #2: 10 | * Input: head = [1,2,3,4,5,6] 11 | * Output: [4,5,6] 12 | * Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 13 | * 14 | * Constraints: 15 | * The number of nodes in the list is in the range [1, 100]. 16 | * 1 <= Node.val <= 100 17 | * 18 | * Definition for singly-linked list. 19 | * type ListNode struct { 20 | * Val int 21 | * Next *ListNode 22 | * } 23 | * 24 | * Solution: to find the middle of a linked list, we can use two pointers ("slow" and "fast"). They should both start at head. 25 | * While traversing the list, we move the slow pointer one node at a time and the fast pointer two nodes at a time. 26 | * When the fast pointer reaches the end of the linked list, the slow pointer will be pointing to the middle node. 27 | * 28 | * Time complexity: O(n), space complexity: O(n) 29 | */ 30 | func middleNode(head *ListNode) *ListNode { 31 | slow, fast := head, head 32 | 33 | for (fast != nil && fast.Next != nil) { 34 | slow = slow.Next 35 | fast = fast.Next.Next 36 | } 37 | 38 | return slow 39 | } 40 | -------------------------------------------------------------------------------- /Linked List/linked_list_recursive_search.cpp: -------------------------------------------------------------------------------- 1 | // Search recursively in a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | bool recursive_search(node *head, int key){ 16 | if(head == NULL){ 17 | return false; 18 | } 19 | if(head->data == key){ 20 | return true; 21 | } 22 | else{ 23 | recursive_search(head->next, key); 24 | } 25 | } 26 | void insert_at_head(node *&head, int data){ 27 | node *n = new node(data); 28 | n->next = head; 29 | head = n; 30 | } 31 | void print_linked_list(node *head){ 32 | while(head != NULL){ 33 | cout << head->data << "->"; 34 | head = head->next; 35 | } 36 | } 37 | int main(){ 38 | node *head = NULL; 39 | insert_at_head(head, 1); 40 | insert_at_head(head, 2); 41 | insert_at_head(head, 3); 42 | print_linked_list(head); 43 | cout << endl; 44 | if(recursive_search(head, 3)){ 45 | cout << "Found"; 46 | } 47 | else{ 48 | cout << "Not Found"; 49 | } 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Linked List/linked_list_remove_nth_node_from_end.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 3 | dummy_header = ListNode('*') 4 | dummy_header.next=head 5 | slow = dummy_header 6 | fast = dummy_header 7 | 8 | for _ in range(1,n+2): 9 | fast=fast.next 10 | 11 | while(fast!=None): 12 | slow = slow.next 13 | fast = fast.next 14 | 15 | slow.next = slow.next.next 16 | return dummy_header.next 17 | -------------------------------------------------------------------------------- /Linked List/linked_list_reverse.cpp: -------------------------------------------------------------------------------- 1 | // Reverse a linkedlist iteratively 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | void insert_at_tail(node *&head, int data){ 16 | if(head == NULL){ 17 | head = new node(data); 18 | return; 19 | } 20 | node *n = new node(data); 21 | node * temp = head; 22 | while(temp -> next != NULL){ 23 | temp = temp->next; 24 | } 25 | temp->next = n; 26 | } 27 | void print_linked_list(node *head){ 28 | while(head != NULL){ 29 | cout << head->data << "->"; 30 | head = head->next; 31 | } 32 | } 33 | void makeLinkedList(node *&head){ 34 | int data; 35 | cin >> data; 36 | while(data != -1){ 37 | insert_at_tail(head, data); 38 | cin >> data; 39 | } 40 | } 41 | void reverse_linked_list(node *&head){ 42 | node *current = head; 43 | node *next = NULL; 44 | node *prev = NULL; 45 | while(current != NULL){ 46 | next = current->next; 47 | current->next = prev; 48 | prev = current; 49 | current = next; 50 | } 51 | head = prev; 52 | } 53 | int main(){ 54 | node *head = NULL; 55 | makeLinkedList(head); 56 | print_linked_list(head); 57 | cout << endl; 58 | reverse_linked_list(head); 59 | print_linked_list(head); 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Linked List/linked_list_reverse.js: -------------------------------------------------------------------------------- 1 | //Problem statement-Given the head of a singly linked list, reverse the list, and return the reversed list. 2 | 3 | // Iteratively 4 | * @param {ListNode} head 5 | * @return {ListNode} 6 | */ 7 | var reverseList = function(head) { 8 | // Handling the edge cases if head node is null or when single node is there 9 | if (head === null || head.next === null) { 10 | return head; 11 | } 12 | // Using three pointer approach 13 | let prev = null; 14 | let curr = head; 15 | let fwd = null; 16 | while (curr !== null) { 17 | // Updatng the value of each of the pointers 18 | fwd = curr.next; 19 | curr.next = prev; 20 | prev = curr; 21 | curr = fwd; 22 | } 23 | // Returning the head of the reversed linked list 24 | return prev; 25 | }; 26 | // Time complexity - O(N) 27 | // Space complexity - O(1) 28 | 29 | // Recursively 30 | var reverseList = function(head) { 31 | // Base case- If the head is null or single node is there 32 | if (head === null || head.next === null) { 33 | return head; 34 | } 35 | 36 | // Recursively reverse the remaining list starting from the next node 37 | const reversedList = reverseList(head.next); 38 | 39 | // Reversing the links between the current and next node 40 | head.next.next = head; 41 | head.next = null; 42 | 43 | // Returning the head of the reversed linked list 44 | return reversedList; 45 | }; 46 | // Time complexity - O(N) 47 | // Space complexity - O(N) 48 | -------------------------------------------------------------------------------- /Linked List/linked_list_reverse_recursive.cpp: -------------------------------------------------------------------------------- 1 | // Reverse a linkedlist recursively 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | void insert_at_tail(node *&head, int data){ 16 | if(head == NULL){ 17 | head = new node(data); 18 | return; 19 | } 20 | node *n = new node(data); 21 | node * temp = head; 22 | while(temp -> next != NULL){ 23 | temp = temp->next; 24 | } 25 | temp->next = n; 26 | } 27 | void print_linked_list(node *head){ 28 | while(head != NULL){ 29 | cout << head->data << "->"; 30 | head = head->next; 31 | } 32 | } 33 | void makeLinkedList(node *&head){ 34 | int data; 35 | cin >> data; 36 | while(data != -1){ 37 | insert_at_tail(head, data); 38 | cin >> data; 39 | } 40 | } 41 | 42 | node* recursive_reverse(node *head){ 43 | if(head->next == NULL || head == NULL){ 44 | return head; 45 | } 46 | node *mini_head = recursive_reverse(head->next); 47 | node *current = head; 48 | current->next->next = current; 49 | current->next = NULL; 50 | return mini_head; 51 | } 52 | int main(){ 53 | node *head = NULL; 54 | makeLinkedList(head); 55 | print_linked_list(head); 56 | cout << endl; 57 | head = recursive_reverse(head); 58 | print_linked_list(head); 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Linked List/linked_list_swap_nodes_in_pair.cpp: -------------------------------------------------------------------------------- 1 | // Swap adjacant Nodes in pair Recursive 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | node(int d){ 10 | data = d; 11 | next = NULL; 12 | } 13 | }; 14 | void insert_at_tail(node *&head, int data){ 15 | if(head == NULL){ 16 | head = new node(data); 17 | return; 18 | } 19 | node *n = new node(data); 20 | node * temp = head; 21 | while(temp -> next != NULL){ 22 | temp = temp->next; 23 | } 24 | temp->next = n; 25 | } 26 | void print_linked_list(node *head){ 27 | cout << endl; 28 | while(head != NULL){ 29 | cout << head->data << "->"; 30 | head = head->next; 31 | } 32 | } 33 | void makeLinkedList(node *&head){ 34 | int data; 35 | cin >> data; 36 | while(data != -1){ 37 | insert_at_tail(head, data); 38 | cin >> data; 39 | } 40 | } 41 | node* swapNodesInPairRecursive(node *head){ 42 | if(head == NULL || head->next == NULL){ 43 | return head; 44 | } 45 | node *newHead = swapNodesInPairRecursive(head->next->next); 46 | node *temp = head->next; 47 | temp->next = head; 48 | head->next = newHead; 49 | return temp; 50 | } 51 | int main(){ 52 | node *head = NULL; 53 | makeLinkedList(head); 54 | print_linked_list(head); 55 | head = swapNodesInPairRecursive(head); 56 | print_linked_list(head); 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Linked List/linked_list_take_input.cpp: -------------------------------------------------------------------------------- 1 | // Finding Midpoint of a LinkedList 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | node(int d){ 10 | data = d; 11 | next = NULL; 12 | } 13 | }; 14 | void insert_at_tail(node *&head, int data){ 15 | if(head == NULL){ 16 | head = new node(data); 17 | return; 18 | } 19 | node *n = new node(data); 20 | node * temp = head; 21 | while(temp -> next != NULL){ 22 | temp = temp->next; 23 | } 24 | temp->next = n; 25 | } 26 | void print_linked_list(node *head){ 27 | cout << endl; 28 | while(head != NULL){ 29 | cout << head->data << "->"; 30 | head = head->next; 31 | } 32 | } 33 | void makeLinkedList(node *&head){ 34 | int data; 35 | cin >> data; 36 | while(data != -1){ 37 | insert_at_tail(head, data); 38 | cin >> data; 39 | } 40 | } 41 | 42 | int main(){ 43 | node *head = NULL; 44 | makeLinkedList(head); 45 | print_linked_list(head); 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Math/Basic_operations.py: -------------------------------------------------------------------------------- 1 | def divide(dividend, divisor): 2 | if divisor == 0: 3 | raise ZeroDivisionError("Division by zero") 4 | if dividend == 0: 5 | return 0 6 | 7 | negative = (dividend < 0) ^ (divisor < 0) 8 | dividend = abs(dividend) 9 | divisor = abs(divisor) 10 | 11 | quotient = 0 12 | while dividend >= divisor: 13 | dividend -= divisor 14 | quotient += 1 15 | 16 | if negative: 17 | quotient = -quotient 18 | 19 | INT_MAX = 2**31 - 1 20 | INT_MIN = -2**31 21 | if quotient > INT_MAX: 22 | return INT_MAX 23 | elif quotient < INT_MIN: 24 | return INT_MIN 25 | else: 26 | return quotient 27 | 28 | # Take user input for dividend and divisor 29 | dividend = int(input("Enter the dividend: ")) 30 | divisor = int(input("Enter the divisor: ")) 31 | 32 | # Perform the division and print the result 33 | result = divide(dividend, divisor) 34 | print(f"The result of {dividend} divided by {divisor} is: {result}") 35 | -------------------------------------------------------------------------------- /Math/Count.go: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNumbersWithUniqueDigits(int n) { 4 | if (n == 0) { 5 | return 1; // There's only one number with 0 digits, which is 0. 6 | } 7 | 8 | int result = 10; // For n = 1, there are 10 numbers with unique digits (0-9). 9 | int uniqueDigits = 9; 10 | int availableDigits = 9; 11 | 12 | for (int i = 2; i <= n && availableDigits > 0; i++) { 13 | uniqueDigits *= availableDigits; 14 | result += uniqueDigits; 15 | availableDigits--; 16 | } 17 | 18 | return result; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Math/Factorial.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Approach: 3 | We will take the number as input from the user and calculate its factorial. 4 | To calculate the factorial, we will start from 1 and multiply it with all the numbers from 1 to n. 5 | Finally, we will return the factorial. 6 | 7 | Time Complexity: O(n) 8 | Space Complexity: O(1) 9 | 10 | Sample Input: 5 11 | Sample Output: Factorial of 5 is 120 12 | ''' 13 | 14 | # Initializing the factorial to 1 15 | fact = 1 16 | def factorial(num): 17 | # If the number is 0 or 1, then the factorial is 1. 18 | if num == 0 or num == 1: 19 | return 1 20 | # Calculating factorial by multiplying every number from 1 to num 21 | for i in range(1, num+1): 22 | fact *= i 23 | return fact 24 | 25 | #Taking input from user 26 | num = int(input("Enter a number: ")) 27 | #Calculating and printing the factorial of the number 28 | print("Factorial of", num, "is", factorial(num)) 29 | 30 | 31 | -------------------------------------------------------------------------------- /Math/Hamming_distance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | 4 | Given two integers x and y, return the Hamming distance between them. 5 | 6 | Example 1: 7 | Input: x = 1, y = 4 8 | Output: 2 9 | Explanation: 10 | 1 (0 0 0 1) 11 | 4 (0 1 0 0) 12 | ↑ ↑ 13 | The above arrows point to positions where the corresponding bits are different. 14 | 15 | Example 2: 16 | Input: x = 3, y = 1 17 | Output: 1 18 | 19 | Constraints: 20 | 0 <= x, y <= 231 - 1 21 | ''' 22 | class Solution: 23 | def totalHammingDistance(self, nums: List[int]) -> int: 24 | '''By using bit manipulation, as all the array elements are 32-bit array elements, we calculate all the number of set bits and unset bits as we need to consider the permutations, we take setbits*unsetbits.''' 25 | hamming_dist,n = 0,len(nums) 26 | for i in range(32): 27 | count = 0 28 | for element in nums: 29 | #Right shifting the element by the index and performing &1 lets us know if a bit is set or not 30 | if((element>>i)&1): 31 | count+=1 32 | #Adding all the combinations where there are set and unset bits. 33 | hamming_dist+=count*(n-count) 34 | return hamming_dist -------------------------------------------------------------------------------- /Math/Number_of_Substrings_With_Only_1s.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: s = "0110111" 9 | Output: 9 10 | Explanation: There are 9 substring in total with only 1's characters. 11 | "1" -> 5 times. 12 | "11" -> 3 times. 13 | "111" -> 1 time. 14 | Example 2: 15 | 16 | Input: s = "101" 17 | Output: 2 18 | Explanation: Substring "1" is shown 2 times in s. 19 | Example 3: 20 | 21 | Input: s = "111111" 22 | Output: 21 23 | Explanation: Each substring contains only 1's characters. 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= s.length <= 105 29 | s[i] is either '0' or '1'. 30 | 31 | Approach: First we count continuos number of ones and if we have n continuos 1's than total substring = (n*(n+1))/2. Using this we can count all substring and add them and return. 32 | using this property (a*b)%mod = ((a%mod)*(b%mod))%mod 33 | */ 34 | class Solution { 35 | public: 36 | int mod = 1000000007; 37 | int numSub(string s) { 38 | long long cnt = 0,ans=0; 39 | for(int i = 0;i 0) 40 | return x * temp * temp; 41 | else 42 | return (temp * temp) / x; 43 | } 44 | 45 | } 46 | } 47 | class PowXn { 48 | public static void main(String[] args) { 49 | double x=2.00; 50 | int y=10; 51 | Solution s=new Solution(); 52 | System.out.println(s.myPow(x,y)); 53 | } 54 | } -------------------------------------------------------------------------------- /Math/PowXn.py: -------------------------------------------------------------------------------- 1 | # Implement pow(x, n), which calculates x raised to the power n (i.e., xn). in Go 2 | 3 | # --- Recursion Approach --- 4 | 5 | # Example 1: 6 | # Input: x = 2, n = 10 7 | # Output: 1024 8 | 9 | # Example 2: 10 | # Input: x = 2.10000, n = 3 11 | # Output: 9.26100 12 | 13 | # Example 3: 14 | # Input: x = 2.00000, n = -2 15 | # Output: 0.25000 16 | # Explanation: 2^(-2) = 1/(2^2) = 1/4 = 0.25 17 | 18 | def power(x, n): 19 | if n == 0: return 1 20 | elif n<0: return power(1/x, -n) 21 | else: return (x*power(x, n-1)) 22 | 23 | 24 | if __name__ == '__main__': 25 | x = 2 26 | n = 3 27 | print(power(x, n)) -------------------------------------------------------------------------------- /Math/Reverse_Integer.cpp: -------------------------------------------------------------------------------- 1 | /* Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 2 | 3 | Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 4 | Example 1: 5 | 6 | Input: x = 123 7 | Output: 321 8 | Example 2: 9 | 10 | Input: x = -123 11 | Output: -321 12 | Example 3: 13 | 14 | Input: x = 120 15 | Output: 21 16 | 17 | 18 | Constraints: 19 | 20 | -2^31 <= x <= 2^31 - 1 21 | */ 22 | // function for reversing the integer; 23 | 24 | int reverse(int x) { 25 | int ans =0; 26 | if(x > INT_MAX || x < INT_MIN) // checking the integer is in range of -2^31 <= x <= 2^31 - 1 27 | return 0; 28 | while(x != 0){ 29 | if(ans > INT_MAX/10 || ans < INT_MIN/10) // -2^31 <= x <= 2^31 - 1 this condition for border values of range 30 | return 0; 31 | ans = ans*10; // we increaing the unit position each itereation 32 | ans += x%10; // here we finding the last unit elemet so that we can add in ans 33 | x /=10; // decreamenting the value or we can say elemenating the last unit element that we are find 34 | 35 | } 36 | return ans; // returning the ans; 37 | } 38 | -------------------------------------------------------------------------------- /Math/circle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] countPoints(int[][] points, int[][] queries) { 3 | int[] answer = new int[queries.length]; 4 | 5 | for (int j = 0; j < queries.length; j++) { 6 | int centerX = queries[j][0]; 7 | int centerY = queries[j][1]; 8 | int radius = queries[j][2]; 9 | 10 | for (int i = 0; i < points.length; i++) { 11 | int pointX = points[i][0]; 12 | int pointY = points[i][1]; 13 | 14 | // Check if the point (pointX, pointY) is inside the circle. 15 | if (isInsideCircle(pointX, pointY, centerX, centerY, radius)) { 16 | answer[j]++; 17 | } 18 | } 19 | } 20 | 21 | return answer; 22 | } 23 | 24 | private boolean isInsideCircle(int x, int y, int centerX, int centerY, int radius) { 25 | int distanceSquared = (x - centerX) * (x - centerX) + (y - centerY) * (y - centerY); 26 | return distanceSquared <= radius * radius; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Math/count_primes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return the number of prime numbers that are strictly less than n. 3 | 4 | Example 1: 5 | Input: n = 10 6 | Output: 4 7 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 8 | 9 | Example 2: 10 | Input: n = 0 11 | Output: 0 12 | 13 | Example 3: 14 | Input: n = 1 15 | Output: 0 16 | Constraints: 17 | 0 <= n <= 5 * 106 18 | */ 19 | 20 | // Refer to Sieve Of Eratosthenes explanation under Math folder 21 | class Solution { 22 | public: 23 | int countPrimes(int n) { 24 | if(n <= 1) return 0; 25 | bool seive[n]; 26 | for(int i = 0; i < n; i++) 27 | seive[i] = true; 28 | seive[0] = false; seive[1] = false; 29 | for(int i = 2; i * i < n; i++){ 30 | if(seive[i]){ 31 | for(int j = i * i; j < n; j += i){ 32 | seive[j] = false; 33 | } 34 | } 35 | } 36 | return count(seive, seive + n, true); 37 | } 38 | }; -------------------------------------------------------------------------------- /Math/count_unique_digits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. 3 | 4 | Input: n = 2 5 | Output: 91 6 | 7 | Input: n = 0 8 | Output: 1 9 | 10 | Constraints: 11 | > 0 <= n <= 8 12 | */ 13 | 14 | class Solution { 15 | public: 16 | 17 | /* 18 | By using concepts of permutation and combination, we can count the unique numbers for N digits. 19 | For the first digit we can choose any 1 digit from 1-9 20 | For the latter digits we can choose any 1 digit from 0-9 except the digits already used 21 | 22 | */ 23 | int countNumbersWithUniqueDigits(int n) { 24 | int ans=0; 25 | for(int i=0;i { 21 | for (let i = 2, s = Math.sqrt(num); i <= s; i++) { 22 | if (num % i === 0) return false; 23 | } 24 | return num > 1; 25 | }; 26 | 27 | console.log(isPrime(10)); 28 | 29 | // Time complexity - O(logn) 30 | function isPrimeLogn(input) { 31 | for (i = 2; i < Math.sqrt(input); i++) { 32 | if (input % i == 0) { 33 | return "The number is not a prime number"; 34 | break; 35 | } else { 36 | continue; 37 | } 38 | } 39 | return "Given number is a prime number"; 40 | } 41 | 42 | // Driver code 43 | console.log(isPrime(6)); 44 | console.log(isPrimeLogn(7)); 45 | -------------------------------------------------------------------------------- /Math/missing_number.py: -------------------------------------------------------------------------------- 1 | # Given an array arr[] of size N with integers in the range of [0, N], the task is to find the missing number 2 | # from the first N integers. 3 | # Note: There are no duplicates in the list 4 | 5 | #ISSUE 1445 6 | 7 | # This code calculates the sum of the given list and the sum of consecutive numbers up to the 8 | # maximum value. The missing number is obtained by subtracting the list sum from the calculated sum, 9 | # and it is printed as the output. 10 | 11 | # input the list 12 | list1 = list(map(int, input().split())) 13 | # calculate sum of the list 14 | s = sum(list1) 15 | #find the max of the array and calculate sum of n natural numbers 16 | n = max(list1) 17 | ans = (n*(n+1))//2 18 | print(ans-s) 19 | 20 | # Time complexity is O(n) -------------------------------------------------------------------------------- /Math/modular_expo_itera.cpp: -------------------------------------------------------------------------------- 1 | // Modular exponentiation is exponentiation performed over a modulus. 2 | // It is useful in computer science, especially in the field of public-key cryptography, 3 | // where it is used in both Diffie-Hellman Key Exchange and RSA public/private keys. 4 | // Sample Input : 10 3 5 | // Output : 1000 6 | // Iterative approach 7 | #include 8 | using namespace std; 9 | int modular_expo(int x, int n, int mod){ 10 | int ans = 1; 11 | while(n >= 1){ 12 | if(n % 2 == 0){ 13 | x = ((x % mod) * (x % mod)) % mod; 14 | n /= 2; 15 | } 16 | else{ 17 | ans = ((ans % mod) * (x % mod)) % mod; 18 | n--; 19 | } 20 | } 21 | return ans; 22 | } 23 | int main(){ 24 | int mod = 1000000007; 25 | cout << modular_expo(5, 3, mod); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Math/modular_expo_recursive.cpp: -------------------------------------------------------------------------------- 1 | // Modular exponentiation is exponentiation performed over a modulus. 2 | // It is useful in computer science, especially in the field of public-key cryptography, 3 | // where it is used in both Diffie-Hellman Key Exchange and RSA public/private keys. 4 | // Sample Input : 10 3 5 | // Output : 1000 6 | // recursive approach 7 | #include 8 | using namespace std; 9 | int modular_expo(int x, int n, int mod){ 10 | if(n == 0) 11 | return 1; 12 | else if(n % 2 == 0){ 13 | int y = modular_expo(x, n / 2, mod); 14 | return (y * y) % mod; 15 | } 16 | else{ 17 | return ((x % mod) * modular_expo(x, n - 1, mod)) % mod; 18 | } 19 | } 20 | int main(){ 21 | int n, x, mod = 1000000007; 22 | cin >> x >> n; 23 | cout << modular_expo(x, n, mod); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Math/num_steps_reduce_to_zero.Go: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer num, return the number of steps to reduce it to zero. 3 | 4 | In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 5 | 6 | Example 1: 7 | Input: num = 14 8 | Output: 6 9 | Explanation: 10 | Step 1) 14 is even; divide by 2 and obtain 7. 11 | Step 2) 7 is odd; subtract 1 and obtain 6. 12 | Step 3) 6 is even; divide by 2 and obtain 3. 13 | Step 4) 3 is odd; subtract 1 and obtain 2. 14 | Step 5) 2 is even; divide by 2 and obtain 1. 15 | Step 6) 1 is odd; subtract 1 and obtain 0. 16 | 17 | Example 2: 18 | Input: num = 8 19 | Output: 4 20 | Explanation: 21 | Step 1) 8 is even; divide by 2 and obtain 4. 22 | Step 2) 4 is even; divide by 2 and obtain 2. 23 | Step 3) 2 is even; divide by 2 and obtain 1. 24 | Step 4) 1 is odd; subtract 1 and obtain 0. 25 | 26 | Example 3: 27 | Input: num = 123 28 | Output: 12 29 | 30 | Constraints: 0 <= num <= 106 31 | */ 32 | func numberOfSteps(num int) int { 33 | var steps = 0 34 | for num != 0 { 35 | if num % 2 == 0 { 36 | num /= 2 37 | steps++ 38 | } else { 39 | num -= 1 40 | steps++ 41 | } 42 | } 43 | return steps 44 | } 45 | -------------------------------------------------------------------------------- /Math/num_steps_reduce_to_zero.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer num, return the number of steps to reduce it to zero. 3 | 4 | In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 5 | 6 | Example 1: 7 | Input: num = 14 8 | Output: 6 9 | Explanation: 10 | Step 1) 14 is even; divide by 2 and obtain 7. 11 | Step 2) 7 is odd; subtract 1 and obtain 6. 12 | Step 3) 6 is even; divide by 2 and obtain 3. 13 | Step 4) 3 is odd; subtract 1 and obtain 2. 14 | Step 5) 2 is even; divide by 2 and obtain 1. 15 | Step 6) 1 is odd; subtract 1 and obtain 0. 16 | 17 | Example 2: 18 | Input: num = 8 19 | Output: 4 20 | Explanation: 21 | Step 1) 8 is even; divide by 2 and obtain 4. 22 | Step 2) 4 is even; divide by 2 and obtain 2. 23 | Step 3) 2 is even; divide by 2 and obtain 1. 24 | Step 4) 1 is odd; subtract 1 and obtain 0. 25 | 26 | Example 3: 27 | Input: num = 123 28 | Output: 12 29 | 30 | Constraints: 0 <= num <= 106 31 | ''' 32 | class Solution(object): 33 | def numberOfSteps(self, num): 34 | """ 35 | :type num: int 36 | :rtype: int 37 | """ 38 | steps = 0 39 | while num != 0: 40 | if num % 2 == 0: 41 | num = num / 2 42 | steps = steps + 1 43 | else: 44 | num = num - 1 45 | steps = steps + 1 46 | return steps 47 | -------------------------------------------------------------------------------- /Math/op.js: -------------------------------------------------------------------------------- 1 | function divide(dividend, divisor) { 2 | // Handle special cases 3 | if (divisor === 0) { 4 | throw new Error("Division by zero"); 5 | } 6 | if (dividend === 0) { 7 | return 0; 8 | } 9 | 10 | // Determine the sign of the result 11 | const negativeResult = (dividend < 0) ^ (divisor < 0); 12 | 13 | // Make dividend and divisor positive for easier calculations 14 | dividend = Math.abs(dividend); 15 | divisor = Math.abs(divisor); 16 | 17 | let quotient = 0; 18 | 19 | while (dividend >= divisor) { 20 | dividend -= divisor; 21 | quotient++; 22 | } 23 | 24 | if (negativeResult) { 25 | quotient = -quotient; 26 | } 27 | 28 | // Check for overflow 29 | if (quotient < -(2**31) || quotient > 2**31 - 1) { 30 | return 2**31 - 1; // Return INT_MAX for overflow 31 | } 32 | 33 | return quotient; 34 | } 35 | 36 | // Example usage: 37 | const dividend = 10; 38 | const divisor = 3; 39 | const result = divide(dividend, divisor); 40 | console.log(result); // Output should be 3 41 | -------------------------------------------------------------------------------- /Math/palindrome_number.java: -------------------------------------------------------------------------------- 1 | /* Question : Given an integer x, return true if x is a palindrome, and false otherwise. 2 | 3 | Example 1: 4 | 5 | Input: x = 121 6 | Output: true 7 | Explanation: 121 reads as 121 from left to right and from right to left. 8 | Example 2: 9 | 10 | Input: x = -121 11 | Output: false 12 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 13 | Example 3: 14 | 15 | Input: x = 10 16 | Output: false 17 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 18 | 19 | 20 | Constraints: 21 | 22 | -231 <= x <= 231 - 1 */ 23 | 24 | class Solution { 25 | public boolean isPalindrome(int x) { 26 | if(x < 0){ 27 | return false; 28 | } 29 | 30 | //Checking if the number is equal to its reverse, if true, it is a palindrome 31 | return x == rev(x); 32 | } 33 | 34 | 35 | // Function to find reverse of a number 36 | 37 | public int reverse(int n){ 38 | int reverse = 0; 39 | while(n != 0){ 40 | int digit = n % 10; 41 | rev = digit + reverse * 10; 42 | n /= 10; 43 | } 44 | 45 | return reverse; 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Math/pallindrome_number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer x, return true if x is a palindrome, and false otherwise. 3 | 4 | Example 1: 5 | Input: x = 121 6 | Output: true 7 | Explanation: 121 reads as 121 from left to right and from right to left. 8 | 9 | Example 2: 10 | Input: x = -121 11 | Output: false 12 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 13 | 14 | Example 3: 15 | Input: x = 10 16 | Output: false 17 | 18 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 19 | 20 | 21 | Constraints: 22 | 23 | -231 <= x <= 231 - 1 24 | */ 25 | 26 | class Solution { 27 | public: 28 | bool isPalindrome(int x) { 29 | int temp = x; 30 | if(x < 0) 31 | return false; 32 | long long new_num = 0; 33 | while(x) { 34 | int rem = x % 10; 35 | new_num = (new_num * 10) + rem; 36 | x /= 10; 37 | } 38 | return new_num == temp; 39 | } 40 | }; -------------------------------------------------------------------------------- /Math/pallindrome_number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer x, return true if x is a 3 | palindrome 4 | , and false otherwise. 5 | 6 | Example 1: 7 | Input: x = 121 8 | Output: true 9 | Explanation: 121 reads as 121 from left to right and from right to left. 10 | 11 | Example 2: 12 | Input: x = -121 13 | Output: false 14 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 15 | 16 | Example 3: 17 | Input: x = 10 18 | Output: false 19 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 20 | Constraints: 21 | -231 <= x <= 231 - 1 22 | 23 | Follow up: Could you solve it without converting the integer to a string? 24 | ''' 25 | class Solution: 26 | def isPalindrome(self, x: int) -> bool: 27 | #check if the number is less than zero. 28 | if x < 0: 29 | return False 30 | #Then, calculating the reverse of the number to see if it is equal to the original number. 31 | rev = 0 32 | original_value = x 33 | while x != 0: 34 | rev = rev * 10 + x % 10 35 | x = x // 10 36 | return rev == original_value -------------------------------------------------------------------------------- /Math/powXn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: x = 2.00000, n = 10 9 | Output: 1024.00000 10 | Example 2: 11 | 12 | Input: x = 2.10000, n = 3 13 | Output: 9.26100 14 | Example 3: 15 | 16 | Input: x = 2.00000, n = -2 17 | Output: 0.25000 18 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 19 | 20 | 21 | Constraints: 22 | 23 | -100.0 < x < 100.0 24 | -231 <= n <= 231-1 25 | n is an integer. 26 | -104 <= xn <= 104 27 | 28 | if it we solve it though simply by recursion it will give time complexity of O(n) 29 | so we will use divide and conquer approach that leads to O(logn) time complexity 30 | eg. 3^7 dive seven by two 333 * 333 3 than in 333 divide by two 3 * 3 3 31 | on conquering 93 * 93 than again conquer 27 * 27 * 3 final output is 218 32 | */ 33 | 34 | class Solution { 35 | public: 36 | double pow(double x, int n) 37 | { 38 | if(x==0)return 0; 39 | if(n==0)return 1; 40 | double res=pow(x,n/2); 41 | res=res*res; 42 | if(n%2)res=x*res; 43 | return res; 44 | } 45 | double myPow(double x, int n) { 46 | if(n<0)return pow(1/x,n); 47 | return pow(x,n); 48 | } 49 | }; -------------------------------------------------------------------------------- /Math/powXn.js: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 2 | // Time complexity: O(log n) | Space complexity: O(log n) 3 | 4 | function pow(x, n) { 5 | // Any number raised to 0 is 1) 6 | if (n === 0) return 1 7 | // Power of a negative number is the reciprocal of power of positive number 8 | if (n < 0) return 1 / pow(x, -n) 9 | // If n is even, calculate pow(x, n / 2) and return the square of it 10 | if (n % 2 === 0) return pow(x, n / 2) * pow(x, n / 2) 11 | // If n is odd, return x * pow(x, n - 1) (x raised to odd power n can be represented as x * x^(n-1)) 12 | return x * pow(x, n - 1) 13 | } 14 | 15 | // Sample inputs and outputs 16 | console.log(pow(2, 10)) // 1024 17 | console.log(pow(2, -3)) // 0.125 18 | console.log(pow(3, 3)) // 27 19 | console.log(pow(3, 0)) // 1 -------------------------------------------------------------------------------- /Math/prime_factorization.cpp: -------------------------------------------------------------------------------- 1 | // Prime factorisation is a method to find the prime factors of a given number, say a composite number. 2 | // These factors are nothing but the prime numbers. A prime number is a number 3 | // which has only two factors, i.e. 1 and the number itself. For example, 2 is a prime number which has two factors, 2 × 1 4 | // Sample Input: 10 5 | // Output 6 | // 2->1 Times 7 | // 5->1 Times 8 | #include 9 | using namespace std; 10 | 11 | int f[100], expo[100], len = -1; 12 | void prime_factor(int n){ 13 | int d = 2; 14 | if(n == 1){ 15 | len++; 16 | f[len] = 2; 17 | expo[len] = 0; 18 | return; 19 | } 20 | while(n > 1 && 1ll * d * d <= n){ 21 | int k = 0; 22 | while(n % d == 0){ 23 | n = n / d; 24 | k++; 25 | } 26 | if(k > 0){ 27 | len++; 28 | f[len] = d; 29 | expo[len] = k; 30 | } 31 | d++; 32 | } 33 | if(n > 1){ 34 | len++; 35 | f[len] = n; 36 | expo[len] = 1; 37 | } 38 | } 39 | int main(){ 40 | int n; 41 | cin >> n; 42 | prime_factor(n); 43 | for(int i = 0; i <= len; i++){ 44 | cout << f[i] << "->" << expo[i] << " Times" << endl; 45 | } 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Math/shuffle_an_array.py: -------------------------------------------------------------------------------- 1 | #Problem statement - Given an integer array nums, design an algorithm to randomly shuffle the array. 2 | # All permutations of the array should be equally likely as a result of the shuffling. 3 | # Complete the provided functions 4 | 5 | class Solution: 6 | 7 | def __init__(self, nums: List[int]): 8 | #the value of nums is stored as an instance variable that can be accessed and used by other methods within the class 9 | self.nums = nums 10 | 11 | 12 | def reset(self) -> List[int]: 13 | #returning the original array after reseting it 14 | return self.nums 15 | 16 | def shuffle(self) -> List[int]: 17 | s = [x for x in self.nums] 18 | random.shuffle(s) 19 | return s 20 | # Time complexity - O(N), where N is the length of the input list self.nums 21 | #Space compelxity - O(N) 22 | 23 | 24 | # Your Solution object will be instantiated and called as such: 25 | # obj = Solution(nums) 26 | # param_1 = obj.reset() 27 | # param_2 = obj.shuffle() 28 | -------------------------------------------------------------------------------- /Math/unique_digits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. 3 | 4 | Example 1: 5 | Input: n = 2 6 | Output: 91 7 | Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 8 | 9 | Example 2: 10 | Input: n = 0 11 | Output: 1 12 | 13 | Constraints: 14 | 0 <= n <= 8 15 | ''' 16 | class Solution: 17 | def countNumbersWithUniqueDigits(self, n: int) -> int: 18 | '''For n = 0, ans = 1 19 | For n = 1, ans = 10 20 | If we take 2 digit number, we have 9 options for first digit (1 - 9) 21 | and 9 options for second digit(0 & all other digits except the one taken as first digit (to keep digits unique)) therefore ans += (9 * 9) 22 | Similarly if we take 3 digit number we have 8 options for third digit, therefore ans += (9 * 9 * 8)''' 23 | if(n==0): return 1 24 | if(n==1): return 10 25 | unique = 10 26 | digits = 9 27 | for i in range(2,n+1): 28 | digits*=(10-i+1) 29 | unique+=digits 30 | return unique 31 | -------------------------------------------------------------------------------- /Math/unique_integers_that_sum_up_to_0.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return any array containing n unique integers such that they add up to 0. 3 | 4 | Example 1: 5 | Input: n = 5 6 | Output: [-7,-1,1,3,4] 7 | Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. 8 | 9 | Example 2: 10 | Input: n = 3 11 | Output: [-1,0,1] 12 | 13 | Example 3: 14 | Input: n = 1 15 | Output: [0] 16 | 17 | Constraints: 18 | 1 <= n <= 1000 19 | */ 20 | 21 | class Solution { 22 | public: 23 | vector sumZero(int n) { 24 | int A[n]; 25 | for(int i = 0; i < n; i++){ A[i] = 0; } 26 | int start = 0; 27 | int end = n - 1; 28 | int i = 1; 29 | // populate start and end with n and -n 30 | while(start < end) { 31 | A[start] = i; 32 | A[end] = -i; 33 | i++; 34 | start++; 35 | end--; 36 | } 37 | vector R; 38 | for(int a: A){ 39 | R.push_back(a); 40 | } 41 | return R; 42 | } 43 | }; -------------------------------------------------------------------------------- /Patterns/CompleteSquare.java: -------------------------------------------------------------------------------- 1 | /* 2 | pattern to print: 3 | for input:5 4 | * * * * * 5 | * * * * * 6 | * * * * * 7 | * * * * * 8 | * * * * * 9 | 10 | APPROACH: 11 | 1) Identify the numbers of rows for the outer for loop 12 | 2) Identify the relation of column with respect to row. 13 | 3) for each loop , print the respective element. 14 | */ 15 | public class CompleteSquare { 16 | 17 | public static void main(String[] args) { 18 | int size = 5; 19 | for(int row=1;row <= size;row++) { 20 | for (int col = 1;col<=size;col++) { 21 | System.out.print("* "); 22 | } 23 | System.out.println(); 24 | } 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Patterns/ReverseRightTrianglePattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse Right Triangular Pattern 3 | Approach: 4 | 1) Identify the numbers of rows for the outer for loop 5 | 2) Identify the relation of column with respect to row. 6 | In this case col = size-row+1 7 | 3) for each loop , print the respective element. 8 | 9 | TIME COMPLEXITY: O(N^2) 10 | SPACE COMPLEXITY: O(1) 11 | Eg: For size = 5, 12 | OUTPUT: 13 | * * * * * 14 | * * * * 15 | * * * 16 | * * 17 | * 18 | */ 19 | public class ReverseRightTrianglePattern { 20 | 21 | public static void main(String[] args) { 22 | int size = 5; 23 | pattern(size); 24 | } 25 | 26 | public static void pattern(int size) { 27 | for(int row=1;row<=size;row++) { 28 | for(int col=1;col<=size-row+1;col++) { 29 | System.out.print("* "); 30 | } 31 | System.out.println(); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Patterns/RightPascalTriangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Right Pascal Triangle pattern in java 3 | Approach: 4 | 1) Identify the numbers of rows for the outer for loop 5 | 2) Identify the relation of column with respect to row. 6 | In this case col = size-row+1 7 | 3) for each loop , print the respective element. 8 | 9 | TIME COMPLEXITY: O(N^2) 10 | SPACE COMPLEXITY: O(1) 11 | Eg: For size = 5, 12 | OUTPUT: 13 | * 14 | * * 15 | * * * 16 | * * * * 17 | * * * 18 | * * 19 | * 20 | */ 21 | public class RightPascalTriangle { 22 | 23 | public static void main(String[] args) { 24 | int size = 4; 25 | pattern(size); 26 | } 27 | 28 | public static void pattern(int size) { 29 | for(int row=0;row< 2*size-1;row++){ 30 | int totalcol = row < size?row:2*size-row-2; 31 | for(int col =0;col <=totalcol;col++){ 32 | System.out.print("* "); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Patterns/StarDiamond.java: -------------------------------------------------------------------------------- 1 | /* 2 | DIAMOND PATTERN 3 | * 4 | * * 5 | * * * 6 | * * * * 7 | * * * 8 | * * 9 | * 10 | 11 | APPROACH: 12 | 1) Identify the numbers of rows for the outer for loop 13 | 2) Identify the relation of column with respect to row. 14 | 3) for each loop , print the respective element. 15 | */ 16 | public class StarDiamond { 17 | 18 | public static void main(String[] args) { 19 | int size = 5; 20 | pattern(size); 21 | } 22 | 23 | public static void pattern(int size) { 24 | for (int row=1;row< 2*size;row++) { 25 | int totalcolsinrow = row <= size ? row:2*size-row; 26 | int spaces = size-totalcolsinrow; 27 | 28 | for(int i =1;i<=spaces;i++) { 29 | System.out.print(" "); 30 | } 31 | for(int col =1;col<=totalcolsinrow;col++) { 32 | System.out.print("* "); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Patterns/triangular_pattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | Approach: 3 | - Initialize the `rows` variable to determine the number of rows in the pattern. 4 | - Initialize the `count` variable to keep track of the current number. 5 | - Use nested `for` loops to iterate through the rows and columns. 6 | - Print the current `count` value and increment it after printing. 7 | - Move to the next line after each row by using `System.out.println()`. 8 | 9 | Time Complexity: The nested loops iterate through the rows and columns of the pattern, resulting in a time complexity of O(rows^2). 10 | 11 | Space Complexity: The space complexity is O(1) as we only require a few variables to store the number of rows, current count, and loop indices. 12 | 13 | Sample Input (rows = 5): 14 | 5 15 | 16 | Sample Output: 17 | 1 18 | 2 3 19 | 4 5 6 20 | 7 8 9 10 21 | 11 12 13 14 15 22 | */ 23 | 24 | //Java code for generating a number pattern in a triangular pattern, starting from 1: 25 | 26 | public class triangular_pattern { 27 | public static void main(String[] args) { 28 | int rows = 5; // number of rows in the pattern 29 | 30 | int count = 1; // variable to keep track of the current number 31 | 32 | // loop through the rows 33 | for (int i = 1; i <= rows; i++) { 34 | // loop through the columns 35 | for (int j = 1; j <= i; j++) { 36 | System.out.print(count + " "); 37 | count++; 38 | } 39 | System.out.println(); // move to the next line after each row 40 | } 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Recursion/calculatextopowern.cpp: -------------------------------------------------------------------------------- 1 | // Canculate power of x^n 2 | // Sample Input : 3 2 3 | // Output : 9 4 | 5 | #include 6 | using namespace std; 7 | 8 | // Method 1 Time complexity O(n) 9 | int power1(int x, int n){ 10 | if(n == 0) 11 | return 1; 12 | return x * power1(x, n-1); 13 | } 14 | 15 | // Method 2 : Time complexity O(log n) 16 | int power(int x, int n){ 17 | if(n == 0) 18 | return 1; 19 | else if(n % 2 == 0){ 20 | int y = power(x, n / 2); 21 | return y * y; 22 | } 23 | return x * power(x, n - 1); 24 | } 25 | 26 | int main(){ 27 | int x, n; 28 | cout << "Give me x annd n"; 29 | cin >> x >> n; 30 | int result = power(x,n); 31 | cout << result << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Recursion/count_digits.cpp: -------------------------------------------------------------------------------- 1 | // Count the number of digits in an integer 2 | // Sample Input: 2003 3 | // Output: 4 4 | 5 | #include 6 | using namespace std; 7 | int count_digits(int n){ 8 | if(n == 0) 9 | return 0; 10 | // recursively hit base case and keep adding 1 afterwards 11 | int small_no = count_digits(n / 10); 12 | return small_no + 1; 13 | } 14 | int main(){ 15 | cout << count_digits(2003099910); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Recursion/count_digits.go: -------------------------------------------------------------------------------- 1 | // Count the number of digits in an integer 2 | // Sample Input: 2003 3 | // Output: 4 4 | package main 5 | 6 | import "fmt" 7 | 8 | func CountDigits(n int) int { 9 | if n == 0 { 10 | return 0; 11 | } 12 | // recursively hit base case and keep adding 1 afterwards 13 | smallNo := CountDigits(n / 10) 14 | return smallNo + 1 15 | } 16 | 17 | func main() { 18 | msg := CountDigits(2003) 19 | fmt.Println(msg) 20 | } -------------------------------------------------------------------------------- /Recursion/count_zeros.cpp: -------------------------------------------------------------------------------- 1 | // Count the number of 0's in an integer 2 | // Sample Input : 10010 3 | // Output: 3 4 | #include 5 | using namespace std; 6 | int count_zeros(int n){ 7 | if(n == 0) 8 | return 0; 9 | // divide the number recursively and hit the base case 10 | int small_no = count_zeros(n / 10); 11 | int last_digit = n % 10; 12 | if(last_digit == 0) 13 | return small_no + 1; 14 | else 15 | return small_no; 16 | } 17 | int main(){ 18 | cout << count_zeros(2003010); 19 | return 0; 20 | } -------------------------------------------------------------------------------- /Recursion/count_zeros.go: -------------------------------------------------------------------------------- 1 | // Count the number of 0's in an integer 2 | // Sample Input : 10010 3 | // Output: 3 4 | package main 5 | 6 | import "fmt" 7 | 8 | func CountZeroes(n int) int { 9 | if n == 0 { 10 | return 0; 11 | } 12 | // divide the number recursively and hit the base case 13 | smallNo := CountZeroes(n / 10) 14 | lastDigit := n % 10 15 | if lastDigit == 0 { 16 | smallNo += 1 17 | } else { 18 | return smallNo 19 | } 20 | return smallNo 21 | } 22 | 23 | func main() { 24 | msg := CountZeroes(1000100100100) 25 | fmt.Println(msg) 26 | } -------------------------------------------------------------------------------- /Recursion/factorial.cpp: -------------------------------------------------------------------------------- 1 | // Factorial of an integer 2 | // Sample Input: 5 3 | // Output: 120 4 | #include 5 | using namespace std; 6 | int factorial(int n){ 7 | cout << "I am calculating f(" << n << ")\n"; 8 | if(n == 0) 9 | return 1; 10 | int f = n * factorial(n - 1); 11 | cout << "Done! f(" << n << ") = " << f << endl; 12 | return f; 13 | } 14 | int main(){ 15 | int n; 16 | cout << "Give me n : "; 17 | cin >> n; 18 | int result = factorial(n); 19 | cout << result << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Recursion/factorial.go: -------------------------------------------------------------------------------- 1 | // Factorial of an integer 2 | // Sample Input: 5 3 | // Output: 120 4 | 5 | package main 6 | 7 | import "fmt" 8 | 9 | func Factorial(n int) int { 10 | if n == 0 { 11 | return 1; 12 | } 13 | return n * Factorial(n - 1) 14 | } 15 | 16 | func main() { 17 | msg := Factorial(5); 18 | fmt.Println(msg) 19 | } -------------------------------------------------------------------------------- /Recursion/factorial.js: -------------------------------------------------------------------------------- 1 | // Factorial of an integer 2 | // Sample Input: 5 3 | // Output: 120 4 | function recursiveFactorial(number) { 5 | //Base case 6 | if (number == 1) { 7 | return 1; 8 | } 9 | 10 | //recursively calling function to get factorial result 11 | return number * recursiveFactorial(number - 1); 12 | } 13 | 14 | // Driver code 15 | console.log(recursiveFactorial(2)); 16 | console.log(recursiveFactorial(3)); 17 | console.log(recursiveFactorial(4)); 18 | console.log(recursiveFactorial(5)); 19 | -------------------------------------------------------------------------------- /Recursion/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | // Fibonacci numbers, commonly denoted Fn , form a sequence, the Fibonacci sequence, 2 | // in which each number is the sum of the two preceding ones. 3 | // The sequence commonly starts from 0 and 1, although some authors start the sequence 4 | // from 1 and 1 or sometimes (as did Fibonacci) from 1 and 2. Starting from 0 and 1, 5 | // the first few values in the sequence are: 6 | // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144. 7 | 8 | // Sample Input: 5 9 | // Output: 5 10 | // Sample Input: 7 11 | // Output: 13 12 | #include 13 | using namespace std; 14 | int fib(int n){ 15 | if(n <= 1) 16 | return n; 17 | return fib(n-1) + fib(n-2); 18 | } 19 | int main(){ 20 | int n; 21 | cout << "Give me n : "; 22 | cin >> n; 23 | int result = fib(n); 24 | cout << result << endl; 25 | } 26 | -------------------------------------------------------------------------------- /Recursion/fibonacci.go: -------------------------------------------------------------------------------- 1 | // Fibonacci numbers, commonly denoted Fn , form a sequence, the Fibonacci sequence, 2 | // in which each number is the sum of the two preceding ones. 3 | // The sequence commonly starts from 0 and 1, although some authors start the sequence 4 | // from 1 and 1 or sometimes (as did Fibonacci) from 1 and 2. Starting from 0 and 1, 5 | // the first few values in the sequence are: 6 | // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144. 7 | 8 | // Sample Input: 5 9 | // Output: 5 10 | // Sample Input: 7 11 | // Output: 13 12 | package main 13 | 14 | import "fmt" 15 | 16 | func Fibonacci(n int) int { 17 | if n <= 1 { 18 | return n 19 | } 20 | return Fibonacci(n - 1) + Fibonacci(n - 2) 21 | } 22 | 23 | func main() { 24 | msg := Fibonacci(7) 25 | fmt.Println(msg) 26 | } -------------------------------------------------------------------------------- /Recursion/fibonacci_memoization.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implelement memoized fibonacci 3 | 4 | Memoization is an enhancement procedure used to speed up computer programs by keeping the values 5 | of distinct function calls and returning the stored input when the same function is invoked again. 6 | 7 | Sample Input: 6 8 | Output: 8 9 | */ 10 | #include 11 | using namespace std; 12 | int F[51]; 13 | int fib(int n){ 14 | if(F[n] != -1) 15 | return F[n]; 16 | F[n] = fib(n - 1) + fib(n-2); 17 | return F[n]; 18 | } 19 | int main(){ 20 | for(int i = 0; i < 51; i++) 21 | F[i] = -1; 22 | F[0] = 0; 23 | F[1] = 1; 24 | int n; 25 | cout << "Give me n : "; 26 | cin >> n; 27 | int result = fib(n); 28 | cout << result; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Recursion/fibonacci_memoization.go: -------------------------------------------------------------------------------- 1 | /* 2 | Implelement memoized fibonacci 3 | 4 | Memoization is an enhancement procedure used to speed up computer programs by keeping the values 5 | of distinct function calls and returning the stored input when the same function is invoked again. 6 | 7 | Sample Input: 6 8 | Output: 8 9 | */ 10 | package main 11 | 12 | import "fmt" 13 | 14 | var F = make([]int, 51) 15 | // array based implementation 0th fib = 1 16 | func Fibonacci(n int) int { 17 | if F[n] != -1 { 18 | return F[n] 19 | } 20 | F[n] = Fibonacci(n - 1) + Fibonacci(n - 2) 21 | return F[n] 22 | } 23 | // more optimized 1st fibonacci = 0, second = 1 24 | func GetNthFib(n int) int { 25 | firstNo := 0 26 | secondNo := 1 27 | result := 0 28 | if n <= 2 { 29 | return n - 1 30 | } 31 | for i := 2; i < n; i++ { 32 | // move first and second to to next iteration 33 | result = firstNo + secondNo 34 | firstNo = secondNo 35 | secondNo = result 36 | } 37 | return result 38 | } 39 | func main() { 40 | for i := 0; i < 51; i++ { 41 | F[i] = -1 42 | } 43 | F[0] = 0 44 | F[1] = 1 45 | msg := Fibonacci(5) 46 | fmt.Println(msg) 47 | msg = GetNthFib(5) 48 | fmt.Println(msg) 49 | } -------------------------------------------------------------------------------- /Recursion/geometric_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | double g_sum(int m){ 4 | if(m == 0) 5 | return 1; 6 | double small_num = g_sum(m - 1); 7 | return small_num + 1.0 / pow(2, m); 8 | } 9 | int main(){ 10 | cout << g_sum(2); 11 | return 0; 12 | } -------------------------------------------------------------------------------- /Recursion/is_array_sorted.cpp: -------------------------------------------------------------------------------- 1 | // Given an array, check whether the array is in sorted order with recursion. 2 | // Sample Input: [1, 2, 3, 4, 4, 5, 3] 3 | // Output: 0 meaning false 4 | // Sample Output: [1, 2, 3, 4, 4, 5, 6] 5 | // Output: 1 meaning true 6 | #include 7 | using namespace std; 8 | bool is_sorted(int A[], int m){ 9 | if(m == 0 || m == 1) 10 | return true; 11 | if(A[0] > A[1]) 12 | return false; 13 | bool small_array = is_sorted(A + 1, m - 1); 14 | return small_array; 15 | } 16 | int main(){ 17 | int A[7] = {1, 2, 3, 4, 4, 5, 3}; 18 | cout << is_sorted(A, 7); 19 | return 0; 20 | } -------------------------------------------------------------------------------- /Recursion/is_array_sorted.go: -------------------------------------------------------------------------------- 1 | // Given an array, check whether the array is in sorted order with recursion. 2 | 3 | package main 4 | 5 | import "fmt" 6 | 7 | // Time Complexity: O(n). Space Complexity: O(n) for recursive stack space. 8 | func isSorted(A []int) bool { 9 | n := len(A) 10 | // Base case 1 11 | if n == 1 { 12 | return true 13 | } 14 | // Base case 2 15 | if A[n - 1] < A[n - 2] { 16 | return false 17 | } 18 | // recursive case 19 | return isSorted(A[:n-1]) 20 | } 21 | 22 | func main() { 23 | A := []int{10, 20, 23, 23, 45, 78, 88} 24 | fmt.Println(isSorted(A)) 25 | A = []int{10, 20, 23, 7, 23, 45, 78, 88} 26 | fmt.Println(isSorted(A)) 27 | } -------------------------------------------------------------------------------- /Recursion/is_element_present.cpp: -------------------------------------------------------------------------------- 1 | // Program to check if an element is present in an array 2 | // Sample Input: [1, 2, 3, 4, 4, 5, 3] key: 51 3 | // Output: 0 meaning false 4 | // Sample Input: [1, 2, 3, 4, 4, 5, 3] key: 5 5 | // Output: 1 meaning true 6 | #include 7 | using namespace std; 8 | bool is_element_present(int A[], int m, int key){ 9 | if(m == 0) 10 | return false; 11 | if(A[0] == key) 12 | return true; 13 | return is_element_present(A + 1, m - 1, key); 14 | } 15 | bool is_element_present2(int A[], int m, int key, int i){ 16 | if(i == m) 17 | return false; 18 | if(A[i] == key) 19 | return true; 20 | return is_element_present2(A, m, key, i + 1); 21 | } 22 | int main(){ 23 | int A[7] = {1, 2, 3, 4, 4, 5, 3}; 24 | int key = 51; 25 | cout << is_element_present(A, 7, key) << endl; 26 | cout << is_element_present2(A, 7, 5, 0) << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Recursion/modular_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | // Modular exponentiation is exponentiation performed over a modulus. 2 | // It is useful in computer science, especially in the field of public-key cryptography, 3 | // where it is used in both Diffie-Hellman Key Exchange and RSA public/private keys. 4 | 5 | // Sample Input : 2 3 100 6 | // Output: 8 7 | 8 | #include 9 | using namespace std; 10 | int mod(int x, int n, int m){ 11 | if(n == 0) 12 | return 1; 13 | else if( n % 2 == 0){ 14 | int y = mod(x, n/2, m); 15 | return y * y % m; 16 | } 17 | return ((x % m) * mod(x, n-1, m)) % m; 18 | } 19 | int main(){ 20 | int x, n, m; 21 | cout << "Give me x, n and m : "; 22 | cin >> x >> n >> m; 23 | int result = mod(x, n, m); 24 | cout << result << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Recursion/multiplication.cpp: -------------------------------------------------------------------------------- 1 | // Multiply number using recursion 2 | // Sample Input: 7, 9 3 | // Output: 63 4 | #include 5 | using namespace std; 6 | int multiply(int n, int m){ 7 | if(m == 0) 8 | return 0; 9 | int small_m = multiply(n, m-1); 10 | return n + small_m; 11 | } 12 | int main(){ 13 | cout << multiply(7, 9); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Recursion/print_numbers.cpp: -------------------------------------------------------------------------------- 1 | // Print numbers recursively 2 | // Sample Input: 5 3 | // Output: 1 2 3 4 5 4 | #include 5 | using namespace std; 6 | void print(int n){ 7 | if(n == 0) 8 | return; 9 | print(n - 1); 10 | cout << n << " "; 11 | } 12 | int main(){ 13 | print(5); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Recursion/recursive_bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | // Implementation of Recursive Bubble sort. 2 | // Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm 3 | // that repeatedly steps through the input list element by element, 4 | // comparing the current element with the one after it, swapping their values if needed. 5 | // These passes through the list are repeated until no swaps had to be performed during a pass, 6 | // meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort 7 | 8 | // Time Complexity worst-case and average complexity O(n^{2}) 9 | // Bubble sort is O(n) on a list that is already sorted i.e. Best case 10 | 11 | // Sample Input : [2, 1, 9, 3, 5, 4, 0] 12 | // Output : [0 1 2 3 4 5 9] 13 | // Program Author : Abhisek Kumar Gupta 14 | #include 15 | using namespace std; 16 | void bubble_sort(int *A, int len){ 17 | if(len == 1) 18 | return; 19 | for(int i = 0; i < len - 1; i++){ 20 | if(A[i] > A[i+1]){ 21 | swap(A[i], A[i+1]); 22 | } 23 | } 24 | bubble_sort(A, len-1); 25 | } 26 | int main(){ 27 | int A[] = {5, 4, 3, 2, 1, 7}; 28 | int len = sizeof(A) / sizeof(int); 29 | bubble_sort(A, len); 30 | for(int x : A){ 31 | cout << x << " "; 32 | } 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Recursion/reverse_print.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Starting from n print number till 1 6 | func print(n int) int { 7 | if n == 0 { // base case 8 | return 0 9 | } 10 | fmt.Println(n) 11 | return print(n - 1) 12 | } 13 | 14 | func main() { 15 | print(10) 16 | } -------------------------------------------------------------------------------- /Recursion/tower_of_hannoi.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Towers of Hanoi puzzle. 4 | Source(https://en.wikipedia.org/wiki/Tower_of_Hanoi) 5 | Object of the game is to move all the disks over to Tower 3. 6 | But you cannot place a larger disk onto a smaller disk. 7 | 8 | Approach 9 | 1 Move the top 􀝊 − 1 disks from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower, 10 | 2 Move the 􀝊􀯧􀯛 disk from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower, 11 | 3 Move the 􀝊 − 1disks from 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower. 12 | ''' 13 | #Tower of Hanoi explanation - https://youtu.be/YstLjLCGmgg 14 | def TowerOfHanoi(n, A,B,C): 15 | if n == 0: 16 | return 17 | TowerOfHanoi(n-1, A,C,B) 18 | print("Move disk", n, "from", A, "to rod", B) 19 | TowerOfHanoi(n-1, C, B, A) -------------------------------------------------------------------------------- /Recursion/tower_of_hanoi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Towers of Hanoi puzzle. 3 | Source(https://en.wikipedia.org/wiki/Tower_of_Hanoi) 4 | Object of the game is to move all the disks over to Tower 3. 5 | But you cannot place a larger disk onto a smaller disk. 6 | */ 7 | /* 8 | Approach 9 | 1 Move the top 􀝊 − 1 disks from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower, 10 | 2 Move the 􀝊􀯧􀯛 disk from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower, 11 | 3 Move the 􀝊 − 1disks from 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower. 12 | */ 13 | package main 14 | 15 | import "fmt" 16 | func TowerOfHanoiHelper(n int, from, to, temp string) { 17 | // Base case 18 | // If only 1 disk, make the move and return 19 | if n == 1 { 20 | fmt.Println("Move disk ", n, " from peg ", from, " to peg ", to) 21 | return 22 | } 23 | 24 | // Move top n-1 disks from A to B, using C as auxiliary 25 | TowerOfHanoiHelper(n-1, from, temp, to) 26 | 27 | // Move remaining disks from A to C 28 | fmt.Println("Move disk ", n, " from peg ", from, " to peg ", to) 29 | 30 | // Move n-1 disks from B to C using A as auxiliary 31 | TowerOfHanoiHelper(n-1, temp, to, from) 32 | } 33 | 34 | func TowersOfHanoi(n int) { 35 | TowerOfHanoiHelper(n, "A", "C", "B") 36 | } 37 | func main() { 38 | TowersOfHanoi(3) 39 | } -------------------------------------------------------------------------------- /Recursion/valid_palindrome_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. 3 | 4 | Constraints: string.length The string only consists of English letters 5 | 6 | Sample Input : "madame" 7 | Output : True 8 | 9 | Sample Input : "masdasd" 10 | Output : False 11 | 12 | ''' 13 | class Solution: 14 | def subPalindrome(self,s,low,high,count): 15 | if(low>high): 16 | return True 17 | if(count>1): 18 | return False 19 | if(s[low]!=s[high]): 20 | return Solution.subPalindrome(self,s,low+1,high,count+1) or Solution.subPalindrome(self,s,low,high-1,count+1) 21 | else: 22 | return Solution.subPalindrome(self,s,low+1,high-1,count) 23 | 24 | def validPalindrome(self, s: str) -> bool: 25 | if(s==s[::-1]): 26 | return True 27 | return Solution.subPalindrome(self,s,0,len(s)-1,0) 28 | 29 | print(Solution().validPalindrome("ebcbbececabbacecbbcbe")) 30 | print(Solution().validPalindrome("cdbeeeabddddbaeedebdc")) 31 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | -------------------------------------------------------------------------------- /Searching/linear_search_string.cpp: -------------------------------------------------------------------------------- 1 | // Linear search in an array of strings 2 | #include 3 | using namespace std; 4 | int main(){ 5 | char a[10][100]; 6 | int n; 7 | cin >> n; 8 | cin.ignore(); 9 | for(int i = 0 ; i < n; i++){ 10 | cin.getline(a[i], 100); 11 | } 12 | char key[100]; 13 | cout << "Enter string to search : "; 14 | cin.getline(key, 100); 15 | int i = 0; 16 | for(i = 0; i < n; i++){ 17 | if(strcmp(key, a[i]) == 0){ 18 | cout << "Found at index : " << i; 19 | break; 20 | } 21 | } 22 | if(i == n) 23 | cout << "Not Found" < list[int]: 6 | dq = deque() 7 | max_elements = [] 8 | for i in range(len(arr)): 9 | if(len(dq) != 0 and dq[0]== i - windowSize): 10 | dq.popleft() 11 | while(len(dq) !=0 and arr[dq[-1]] < arr[i]): 12 | dq.pop() 13 | dq.append(i) 14 | if(i >= windowSize - 1): 15 | max_elements.append(arr[dq[0]]) 16 | return max_elements 17 | 18 | arr = list(map(int, input().split())) 19 | windowSize = int(input()) 20 | print(slidingWindowMax(arr, windowSize)) 21 | -------------------------------------------------------------------------------- /Stacks/is_palindrome.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // IsPalindrome: returns true if supplied string is a palindrome 4 | // Time Complexity: O(n). Space Complexity: O(n/2) ≈ O(n). 5 | func IsPalindrome(s string) bool { 6 | stack := NewStack(1) 7 | i, n := 0, len(s) 8 | // push hald element into stack 9 | for i < n/2 { 10 | stack.Push(s[i]) 11 | i++ 12 | } 13 | // escape mid character 14 | if n%2 == 1 { 15 | i++ 16 | } 17 | // compare other half of string with stack 18 | for i < len(s) { 19 | // if element doesn't match, or stack is empty then return false 20 | if stack.IsEmpty() || s[i] != stack.Pop() { 21 | return false 22 | } 23 | i++ 24 | } 25 | return true 26 | } -------------------------------------------------------------------------------- /Stacks/queue using stack.js: -------------------------------------------------------------------------------- 1 | // Queue using stack 2 | class Queue { 3 | constructor() { 4 | this.enqueueStack = []; // Stack for enqueue operations 5 | this.dequeueStack = []; // Stack for dequeue operations 6 | } 7 | 8 | enqueue(value) { 9 | // Enqueue: Add an element to the back of the queue. 10 | this.enqueueStack.push(value); 11 | } 12 | 13 | dequeue() { 14 | // Dequeue: Remove and return the front element of the queue. 15 | // If the dequeue stack is empty, transfer elements from the enqueue stack 16 | if (this.dequeueStack.length === 0) { 17 | while (this.enqueueStack.length > 0) { 18 | // Pop an element from the enqueue stack and push it onto the dequeue stack 19 | const element = this.enqueueStack.pop(); 20 | this.dequeueStack.push(element); 21 | } 22 | } 23 | 24 | // If the dequeue stack is still empty, the queue is empty 25 | if (this.dequeueStack.length === 0) { 26 | throw new Error("Queue is empty"); 27 | } 28 | 29 | // Pop and return the front element from the dequeue stack 30 | return this.dequeueStack.pop(); 31 | } 32 | } 33 | 34 | // Example usage 35 | const queue = new Queue(); 36 | queue.enqueue(1); 37 | queue.enqueue(2); 38 | queue.enqueue(3); 39 | console.log(queue.dequeue()); // Output: 1 40 | console.log(queue.dequeue()); // Output: 2 41 | queue.enqueue(4); 42 | queue.enqueue(5); 43 | console.log(queue.dequeue()); // Output: 3 44 | console.log(queue.dequeue()); // Output: 4 45 | console.log(queue.dequeue()); // Output: 5 46 | -------------------------------------------------------------------------------- /Stacks/queue using stack.py: -------------------------------------------------------------------------------- 1 | # Queue using stack 2 | class Queue: 3 | def __init__(self): 4 | self.enqueue_stack = [] # Stack for enqueue operations 5 | self.dequeue_stack = [] # Stack for dequeue operations 6 | 7 | def enqueue(self, value): 8 | """Enqueue: Add an element to the back of the queue.""" 9 | self.enqueue_stack.append(value) 10 | 11 | def dequeue(self): 12 | """Dequeue: Remove and return the front element of the queue.""" 13 | # If the dequeue stack is empty, transfer elements from the enqueue stack 14 | if not self.dequeue_stack: 15 | while self.enqueue_stack: 16 | # Pop an element from the enqueue stack and push it onto the dequeue stack 17 | element = self.enqueue_stack.pop() 18 | self.dequeue_stack.append(element) 19 | 20 | # If the dequeue stack is still empty, the queue is empty 21 | if not self.dequeue_stack: 22 | raise IndexError("Queue is empty") 23 | 24 | # Pop and return the front element from the dequeue stack 25 | return self.dequeue_stack.pop() 26 | 27 | # Example usage 28 | queue = Queue() 29 | queue.enqueue(1) 30 | queue.enqueue(2) 31 | queue.enqueue(3) 32 | print(queue.dequeue()) # Output: 1 33 | print(queue.dequeue()) # Output: 2 34 | queue.enqueue(4) 35 | queue.enqueue(5) 36 | print(queue.dequeue()) # Output: 3 37 | print(queue.dequeue()) # Output: 4 38 | print(queue.dequeue()) # Output: 5 39 | -------------------------------------------------------------------------------- /Stacks/stack.go: -------------------------------------------------------------------------------- 1 | // Implement Stack Data Structure 2 | // TODO: Make Stack Generic 3 | 4 | package main 5 | 6 | import "fmt" 7 | 8 | type Stack []string 9 | 10 | // IsEmpty func checks if the stack is empty 11 | func (s *Stack) IsEmpty() bool { 12 | return len(*s) == 0 13 | } 14 | 15 | // Push func pushes a new value into the stack 16 | func (s *Stack) Push(str string) { 17 | fmt.Printf("%s pushed into stack\n", str) 18 | *s = append(*s, str) 19 | } 20 | // Pop func pops the top most value from stack if there is any 21 | func (s *Stack) Pop() (string, bool) { 22 | if s.IsEmpty() { 23 | return "", false 24 | } else { 25 | index := len(*s) - 1 26 | element := (*s)[index] 27 | *s = (*s)[:index] 28 | return element, true 29 | } 30 | } 31 | func main() { 32 | var stack Stack 33 | 34 | // push 3 values in stack 35 | stack.Push("Hello0") 36 | stack.Push("Hello1") 37 | stack.Push("Hello2") 38 | 39 | // pop out all values from stack 40 | for len(stack) > 0 { 41 | x, y := stack.Pop() 42 | if y == true { 43 | fmt.Printf("%s popped from stack\n", x) 44 | } 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /Stacks/valid_parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | Every close bracket has a corresponding open bracket of the same type. 9 | 10 | 11 | Example 1: 12 | Input: s = "()" 13 | Output: true 14 | 15 | Example 2: 16 | Input: s = "()[]{}" 17 | Output: true 18 | 19 | Example 3: 20 | Input: s = "(]" 21 | Output: false 22 | 23 | Constraints: 24 | 25 | 1 <= s.length <= 104 26 | s consists of parentheses only '()[]{}'. 27 | */ 28 | 29 | class Solution { 30 | public: 31 | bool Are_pair(char opening, char closing){ 32 | if (opening == '(' && closing == ')') return true; 33 | else if (opening == '[' && closing == ']') return true; 34 | else if (opening == '{' && closing == '}') return true; 35 | return false; 36 | } 37 | bool isValid(string s) { 38 | stack Sta; 39 | int len = s.size(); 40 | for(int i = 0; i < len; i++){ 41 | if(s[i] == '(' || s[i] == '[' || s[i] == '{'){ 42 | Sta.push(s[i]); 43 | } 44 | else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){ 45 | if(Sta.empty() || !Are_pair(Sta.top(), s[i])) 46 | return false; 47 | else 48 | Sta.pop(); 49 | } 50 | } 51 | return Sta.empty() ? true : false; 52 | } 53 | }; -------------------------------------------------------------------------------- /Strings/Dp_plaindrome.py: -------------------------------------------------------------------------------- 1 | def find_min_insertion_steps(s): 2 | n = len(s) 3 | dp = [[0] * n for _ in range(n)] 4 | 5 | for length in range(2, n + 1): 6 | for i in range(n - length + 1): 7 | j = i + length - 1 8 | if s[i] == s[j]: 9 | dp[i][j] = dp[i + 1][j - 1] 10 | else: 11 | dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1 12 | 13 | return dp[0][n - 1] 14 | 15 | # Test the function 16 | string = "abcd" 17 | print("Minimum Insertion Steps:", find_min_insertion_steps(string)) 18 | -------------------------------------------------------------------------------- /Strings/Min_palindrome.js: -------------------------------------------------------------------------------- 1 | function minInsertionStepsToPalindrome(str) { 2 | const n = str.length; 3 | // Create a 2D array to store the minimum steps needed to make substrings palindrome 4 | const dp = Array.from({ length: n }, () => Array(n).fill(0)); 5 | 6 | // Base case: single characters are palindromes, so dp[i][i] = 0 7 | for (let i = 0; i < n; i++) { 8 | dp[i][i] = 0; 9 | } 10 | 11 | // Fill the dp table in bottom-up manner 12 | for (let len = 2; len <= n; len++) { 13 | for (let i = 0; i < n - len + 1; i++) { 14 | const j = i + len - 1; 15 | if (str[i] === str[j]) { 16 | // If the characters at the ends are the same, no additional insertion is needed 17 | dp[i][j] = dp[i + 1][j - 1]; 18 | } else { 19 | // Otherwise, choose the minimum between inserting character at i or j 20 | dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1]); 21 | } 22 | } 23 | } 24 | 25 | return dp[0][n - 1]; 26 | } 27 | 28 | // Example usage: 29 | const str = "abcd"; 30 | const minInsertions = minInsertionStepsToPalindrome(str); 31 | console.log("Minimum insertion steps:", minInsertions); // Output: 3 (abcd -> dabcbad) 32 | -------------------------------------------------------------------------------- /Strings/check_palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // 2 pointer approach to find if a number is palindrome or not 7 | // Time complexity O(n), Space complexity O(1). 8 | 9 | int palindrome_checker(string str) // palindrome checker function 10 | { 11 | int left = 0; 12 | int right = str.length() - 1; // initializing left and right variables 13 | while(left < right) 14 | { 15 | if(str[left] != str[right]) 16 | { 17 | return 0; 18 | } 19 | left = left + 1; // updating left and right variables 20 | right = right - 1; 21 | } 22 | return 1; 23 | } 24 | 25 | int main() 26 | { 27 | string str; 28 | cin>>str; 29 | int isPal = palindrome_checker(str); // calling palindrome checker function 30 | if(isPal == 1) 31 | { 32 | cout<<"String is palindrome"; 33 | } 34 | else 35 | { 36 | cout<<"String is not palindrome"; 37 | } 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Strings/check_permutations.cpp: -------------------------------------------------------------------------------- 1 | // Check if a string is a permutation of other 2 | // Sample Input: s1 = abba s2 = baba 3 | // Output: true 4 | // Time Complexity O(n) Space complexity O(1) 5 | #include 6 | using namespace std; 7 | bool check_permutations(string a, string b){ 8 | vector Freq(26, 0); // assuming only letters 9 | for(int i = 0; i < a.length(); i++){ 10 | Freq[a[i] - 'a']++; 11 | } 12 | for(int x : Freq) cout << x << ","; 13 | cout << endl; 14 | for(int i = 0; i < b.length(); i++){ 15 | if(Freq[b[i] - 'a'] > 0) // seen a letter 16 | Freq[b[i] - 'a']--; // reduce count 17 | else 18 | Freq[b[i] - 'a']++; // not seen before so increase count 19 | } 20 | for(int x : Freq) cout << x << ","; 21 | cout << endl; 22 | int res = accumulate(Freq.begin(), Freq.end(), 0); // checl of sum of elements in freq is 0 23 | return res == 0 ? true : false; 24 | } 25 | int main(){ 26 | string a, b; 27 | cin >> a >> b; 28 | if(check_permutations(a, b)) 29 | cout << "TRUE"; 30 | else 31 | cout << "FALSE"; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Strings/is_pallindrome.go: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes in a non-empty string and that returns a boolean 3 | representing whether the string is a palindrome. 4 | Sample Input: abba 5 | Output: True 6 | Sample Input: aberba 7 | Output: False 8 | */ 9 | package main 10 | 11 | import "fmt" 12 | 13 | func IsPalindrome(str string) bool { 14 | start := 0 15 | end := len(str) - 1 16 | for start <= end { 17 | // if string doesn't match return false straight away 18 | if str[start] != str[end] { 19 | return false 20 | } 21 | // string matches so bring start and end inwards 22 | start++ 23 | end-- 24 | } 25 | return true 26 | } 27 | 28 | func main() { 29 | msg := IsPalindrome("HelleH") 30 | fmt.Println(msg) 31 | msg = IsPalindrome("Hello") 32 | fmt.Println(msg) 33 | } -------------------------------------------------------------------------------- /Strings/is_pallindrome.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that takes in a non-empty string and that returns a boolean 3 | representing whether the string is a palindrome. 4 | Sample Input: abba 5 | Output: True 6 | Sample Input: aberba 7 | Output: False 8 | 9 | Explanation: 10 | 11 | In this implementation, we use Python's filter() function to remove all non-alphanumeric characters 12 | from the string and lower() method to convert the string to lowercase. Then we check if the reversed 13 | string is equal to the original string using the slice notation [::-1]. If the two strings are equal, 14 | we return True, indicating that the input string is a palindrome; otherwise, we return False. 15 | ''' 16 | 17 | def is_palindrome(s: str) -> bool: 18 | """ 19 | This function takes in a non-empty string and returns a boolean indicating 20 | whether the string is a palindrome or not. 21 | 22 | Parameters: 23 | s (str): The input string 24 | 25 | Returns: 26 | bool: True if s is a palindrome, False otherwise 27 | """ 28 | # Remove all non-alphanumeric characters and convert to lowercase 29 | s = ''.join(filter(str.isalnum, s)).lower() 30 | 31 | # Check if the reversed string is equal to the original string 32 | return s == s[::-1] 33 | -------------------------------------------------------------------------------- /Strings/is_unique.go: -------------------------------------------------------------------------------- 1 | // Implement an algorithm to determine if a string has all unique characters. 2 | // what if you cannot use additional data structures? 3 | // Program Author : Abhisek Kumar Gupta 4 | // Approach 1 : compare every character of string with other character TC O(n^2) 5 | // Approach 2 : Sort the string and compare neighbouring character for dups TC O(n log(n)) 6 | 7 | package main 8 | 9 | import "fmt" 10 | 11 | 12 | func is_unique_normal(s string) bool { 13 | if len(s) > 128 { 14 | return false 15 | } 16 | var visited [128]bool 17 | 18 | for i := 0; i < len(s); i++ { 19 | val := int(s[i]) // convert to ascii value 20 | if(visited[val]) { // if already seen then duplicate exists hence return false 21 | return false 22 | } 23 | visited[val] = true // mark seen as true so far 24 | } 25 | return true 26 | } 27 | 28 | func IsUniqueUsingBitVector(s string) bool { 29 | checker := 0 30 | for _, s := range []rune(s){ 31 | val := s - 'a' 32 | if (checker & (1 << uint32(val))) > 0 { 33 | return false 34 | } 35 | checker |= (1 << uint32(val)) 36 | } 37 | return true 38 | } 39 | 40 | func main() { 41 | s := "ABCDD" 42 | t := "ABCD" 43 | u := "AAAAAABCD" 44 | msg := is_unique_normal(s) 45 | fmt.Println(msg) 46 | msg = is_unique_normal(t) 47 | fmt.Println(msg) 48 | msg = is_unique_normal(u) 49 | fmt.Println(msg) 50 | 51 | msg = IsUniqueUsingBitVector("aa") 52 | fmt.Println(msg) 53 | } -------------------------------------------------------------------------------- /Strings/length_of_longest_substring.java: -------------------------------------------------------------------------------- 1 | /* Implement lengthOfLongestSubstring(s), which calculates the length of the longest possible substring that does not contain repeating characters. 2 | 3 | Example 1: 4 | Input: "abcabcbaba" 5 | Output: 3 6 | 7 | Example 2: 8 | Input: "dddddddd" 9 | Output: 1 10 | 11 | Example 3: 12 | Input: "pwwkewo" 13 | Output: 4 14 | 15 | Constraints: 16 | 0 <= s.length <= 5 * 10^4 17 | 18 | Time complexity: O(n^2) 19 | Space complexity: O(1) 20 | 21 | */ 22 | 23 | class Solution { 24 | public int lengthOfLongestSubstring(String s) { 25 | int length = s.length(); 26 | if (length==0) { 27 | return 0; 28 | } 29 | 30 | int max = 1; 31 | // Aiming to find substring of s that starts at index i and ends at j-1. 32 | int i = 0; 33 | int j = i+1; 34 | 35 | while (j max) { 41 | max = j-i; 42 | } 43 | 44 | i++; 45 | } 46 | 47 | return max; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Strings/longest_common_prefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: strs = ["flower","flow","flight"] 11 | Output: "fl" 12 | Example 2: 13 | 14 | Input: strs = ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= strs.length <= 200 22 | 0 <= strs[i].length <= 200 23 | strs[i] consists of only lowercase English letters. 24 | 25 | Time complexity : O(strs) 26 | */ 27 | 28 | #include 29 | 30 | class Solution { 31 | public: 32 | string longestCommonPrefix(vector& strs) { 33 | if(strs.size() == 0) return ""; 34 | string ans = ""; 35 | // fix one string and check the common prefix of this string with other strings 36 | // s is the smallest string, so longest cant be greater than smallest string in array 37 | string s = *min_element(strs.begin(), strs.end()); 38 | for(int i = 0; i < s.size(); i++){ 39 | for(int j = 0; j < strs.size(); j++){ 40 | if(s[i] != strs[j][i]) 41 | return ans; 42 | } 43 | ans.push_back(s[i]); 44 | } 45 | return ans; 46 | } 47 | }; -------------------------------------------------------------------------------- /Strings/plaindrome_str.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | bool isPalindrome(string s, int start, int end) { 7 | while (start < end) { 8 | if (s[start] != s[end]) { 9 | return false; 10 | } 11 | start++; 12 | end--; 13 | } 14 | return true; 15 | } 16 | 17 | vector> partitionPalindrome(string s) { 18 | vector> result; 19 | vector current; 20 | 21 | backtrack(s, 0, current, result); 22 | 23 | return result; 24 | } 25 | 26 | void backtrack(string s, int start, vector& current, vector>& result) { 27 | if (start == s.length()) { 28 | result.push_back(current); 29 | return; 30 | } 31 | 32 | for (int end = start; end < s.length(); end++) { 33 | if (isPalindrome(s, start, end)) { 34 | current.push_back(s.substr(start, end - start + 1)); 35 | backtrack(s, end + 1, current, result); 36 | current.pop_back(); 37 | } 38 | } 39 | } 40 | 41 | int main() { 42 | string s = "aab"; 43 | vector> partitions = partitionPalindrome(s); 44 | 45 | for (auto partition : partitions) { 46 | for (string palindrome : partition) { 47 | cout << palindrome << " "; 48 | } 49 | cout << endl; 50 | } 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Strings/reverse_string.go: -------------------------------------------------------------------------------- 1 | // Reverse a string 2 | // Program Author : Abhisek Kumar Gupta 3 | 4 | package main 5 | 6 | import "fmt" 7 | 8 | func reverse(s string) string { 9 | // since strings are immutable in go, we make array of runes 10 | chars := []rune(s) 11 | // swap start and end position characters 12 | for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { 13 | chars[i], chars[j] = chars[j], chars[i] 14 | } 15 | // cast chars to string 16 | return string(chars) 17 | } 18 | 19 | func main() { 20 | fmt.Printf("%v\n", reverse("abcdefg")) 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Strings/well_formed_parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | Example 1: 5 | Input: n = 3 6 | Output: ["((()))","(()())","(())()","()(())","()()()"] 7 | 8 | Example 2: 9 | Input: n = 1 10 | Output: ["()"] 11 | 12 | Constraints: 1 <= n <= 8 13 | */ 14 | #include 15 | class Solution { 16 | public: 17 | vector ans; 18 | int N; 19 | void solve(string s,int count) 20 | { 21 | if(s.size()==2*N) 22 | ans.push_back(s); 23 | 24 | if(count generateParenthesis(int n) { 30 | string st; 31 | solve(st,0); 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Trees/Binary Trees/bfs.cpp: -------------------------------------------------------------------------------- 1 | // Binary Tree : Breadth First Search TC : O(n) 2 | // Program Author : Abhisek Kumar Gupta 3 | /* 4 | 40 5 | / \ 6 | 10 30 7 | / \ / \ 8 | 5 -1 -1 28 9 | / \ / \ 10 | 1 -1 15 20 11 | / \ /\ /\ 12 | 1 -1 -1 -1 -1 -1 13 | /\ 14 | -1 -1 15 | Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 16 | Output : 40 10 30 5 28 1 15 20 1 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | 22 | class Node{ 23 | public: 24 | int data; 25 | Node* left; 26 | Node* right; 27 | 28 | Node(int x){ 29 | data = x; 30 | } 31 | }; 32 | 33 | Node* build_binary_tree(){ 34 | int data; 35 | cin >> data; 36 | if(data == -1) 37 | return NULL; 38 | Node* root = new Node(data); 39 | root->left = build_binary_tree(); 40 | root->right = build_binary_tree(); 41 | return root; 42 | } 43 | void bfs(Node* root){ 44 | queue q; 45 | q.push(root); 46 | while(!q.empty()){ 47 | Node* element = q.front(); 48 | cout << element->data << "->"; 49 | q.pop(); 50 | if(element->left != NULL){ 51 | q.push(element->left); 52 | } 53 | if(element->right != NULL){ 54 | q.push(element->right); 55 | } 56 | } 57 | return; 58 | } 59 | int main(){ 60 | Node* root = build_binary_tree(); 61 | bfs(root); 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/build_tree_preorder.cpp: -------------------------------------------------------------------------------- 1 | // Pre-Order Traversal of a Binary-Tree 2 | // Program Author : Abhisek Kumar Gupta 3 | #include 4 | using namespace std; 5 | class Node{ 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | 11 | Node(int x){ 12 | data = x; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | 17 | }; 18 | 19 | Node* build_binary_tree(){ 20 | int data; 21 | cin >> data; 22 | if(data == -1) 23 | return NULL; 24 | Node* root = new Node(data); 25 | root->left = build_binary_tree(); 26 | root->right = build_binary_tree(); 27 | return root; 28 | } 29 | 30 | void print_binary_tree(Node* root){ 31 | if(root == NULL) 32 | return; 33 | cout << root->data << "->"; 34 | print_binary_tree(root->left); 35 | print_binary_tree(root->right); 36 | } 37 | 38 | int main(){ 39 | Node* root = build_binary_tree(); 40 | print_binary_tree(root); 41 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/calculate_size.go: -------------------------------------------------------------------------------- 1 | // Size of binary tree 2 | package main 3 | 4 | type BinaryTreeNode struct { 5 | left *BinaryTreeNode 6 | data int 7 | right *BinaryTreeNode 8 | } 9 | // Time Complexity: O(n). Space Complexity: O(n). 10 | // Approach: calculate the size of left and right subtree recursively 11 | // add 1 (curr node) and return to its parent 12 | func Size(root *BinaryTreeNode) int { 13 | if root == nil { 14 | return 0 15 | } else { 16 | return Size(root.left) + 1 + Size(root.right) 17 | } 18 | } 19 | 20 | // Time Complexity: O(n). Space Complexity: O(n). 21 | // Approach: use level order traversal and count nodes 22 | func SizeWithoutUsingRecursion(root *BinaryTreeNode) int { 23 | if root == nil { 24 | return 0 25 | } 26 | var result int 27 | queue := []*BinaryTreeNode{root} 28 | for len(queue) > 0 { 29 | qlen := len(queue) 30 | //var level []int 31 | for i := 0; i < qlen; i++ { 32 | node := queue[0] 33 | result++ 34 | //level = append(level, node.data) 35 | queue = queue[1:] 36 | if node.left != nil { 37 | queue = append(queue, node.left) 38 | } 39 | if node.right != nil { 40 | queue = append(queue, node.right) 41 | } 42 | } 43 | } 44 | return result 45 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/count_nodes.cpp: -------------------------------------------------------------------------------- 1 | // Binary Tree : Count Number of Nodes 2 | // Program Author : Abhisek Kumar Gupta 3 | /* 4 | 40 5 | / \ 6 | 10 30 7 | / \ / \ 8 | 5 -1 -1 28 9 | / \ / \ 10 | 1 -1 15 20 11 | / \ /\ /\ 12 | 1 -1 -1 -1 -1 -1 13 | /\ 14 | -1 -1 15 | Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 16 | Output : 9 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | class Node{ 22 | public: 23 | int data; 24 | Node* left; 25 | Node* right; 26 | 27 | Node(int d){ 28 | data = d; 29 | } 30 | }; 31 | Node* build_binary_tree(){ 32 | int data; 33 | cin >> data; 34 | if(data == -1){ 35 | return NULL; 36 | } 37 | Node* root = new Node(data); 38 | root->left = build_binary_tree(); 39 | root->right = build_binary_tree(); 40 | return root; 41 | } 42 | int count_number_of_nodes(Node* root){ 43 | if(root == NULL) 44 | return 0; 45 | return 1 + count_number_of_nodes(root->left) + count_number_of_nodes(root->right); 46 | } 47 | int main(){ 48 | Node* root = build_binary_tree(); 49 | int number_of_nodes = count_number_of_nodes(root); 50 | cout << number_of_nodes; 51 | return 0; 52 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/delete.go: -------------------------------------------------------------------------------- 1 | // Delete binary tree 2 | package main 3 | 4 | type BinaryTreeNode struct { 5 | left *BinaryTreeNode 6 | data int 7 | right *BinaryTreeNode 8 | } 9 | 10 | // Time Complexity: O(n). Space Complexity: O(n). 11 | // Approach: before deleting parent node, delete all its children nodes 12 | // using post order traversal we can solve this problem 13 | func DeleteTree(root *BinaryTreeNode) *BinaryTreeNode { 14 | if root == nil { 15 | return nil 16 | } 17 | // delete both subtrees 18 | root.left = DeleteTree(root.left) 19 | root.right = DeleteTree(root.right) 20 | // delete current node after deleting subtrees 21 | root = nil 22 | return root 23 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/find_max.go: -------------------------------------------------------------------------------- 1 | // Find max in Binary tree 2 | package main 3 | 4 | import "math" 5 | 6 | type BinaryTreeNode struct { 7 | left *BinaryTreeNode 8 | data int 9 | right *BinaryTreeNode 10 | } 11 | 12 | // Time Complexity: O(n). Space Complexity: O(n). 13 | // Approach: find maximum in left sub tree, find maximum in right subtree 14 | // compare them with root data and select the one which is giving the max value 15 | // recursive appraoch 16 | func FindMax(root *BinaryTreeNode) int { 17 | max := math.MinInt32 18 | if root != nil { 19 | rootVal := root.data 20 | left := FindMax(root.left) 21 | right := FindMax(root.right) 22 | if left > max { 23 | max = left 24 | } else { 25 | max = right 26 | } 27 | if rootVal > max { 28 | max = rootVal 29 | } 30 | } 31 | return max 32 | } 33 | 34 | // Time Complexity: O(n). Space Complexity: O(n). 35 | // Approach: Using level order traversal observe the elements data 36 | func FindMaxWithoutRecursion(root *BinaryTreeNode) int { 37 | max := math.MinInt32 38 | if root == nil { 39 | return max 40 | } 41 | queue := []*BinaryTreeNode{root} 42 | for len(queue) > 0 { 43 | qlen := len(queue) 44 | for i := 0; i < qlen; i++ { 45 | node := queue[0] 46 | if node.data > max { 47 | max = node.data 48 | } 49 | queue = queue[1:] 50 | if node.left != nil { 51 | queue = append(queue, node.left) 52 | } 53 | if node.right != nil { 54 | queue = append(queue, node.right) 55 | } 56 | } 57 | } 58 | return max 59 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/height.cpp: -------------------------------------------------------------------------------- 1 | // Compute Height of a Binary-Tree 2 | // Program Author : Abhisek Kumar Gupta 3 | /* 4 | 40 5 | / \ 6 | 10 30 7 | / \ / \ 8 | 5 -1 -1 28 9 | / \ / \ 10 | 1 -1 15 20 11 | / \ /\ /\ 12 | 1 -1 -1 -1 -1 -1 13 | /\ 14 | -1 -1 15 | Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 16 | Output : 5 17 | */ 18 | #include 19 | using namespace std; 20 | class Node{ 21 | public: 22 | int data; 23 | Node* left; 24 | Node* right; 25 | 26 | Node(int x){ 27 | data = x; 28 | } 29 | }; 30 | Node* build_binary_tree(){ 31 | int data; 32 | cin >> data; 33 | if(data == -1) 34 | return NULL; 35 | Node* root = new Node(data); 36 | root->left = build_binary_tree(); 37 | root->right = build_binary_tree(); 38 | return root; 39 | } 40 | int compute_height_of_binary_tree(Node* root){ 41 | if(root == NULL){ 42 | return 0; 43 | } 44 | int left_height = compute_height_of_binary_tree(root->left); 45 | int right_height = compute_height_of_binary_tree(root->right); 46 | return max(left_height, right_height) + 1; 47 | } 48 | int main(){ 49 | Node* root = build_binary_tree(); 50 | int height = compute_height_of_binary_tree(root); 51 | cout << "Height of Tree is " << height; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Trees/Binary Trees/height.go: -------------------------------------------------------------------------------- 1 | // Binary tree Find height 2 | package main 3 | 4 | type BinaryTreeNode struct { 5 | left *BinaryTreeNode 6 | data int 7 | right *BinaryTreeNode 8 | } 9 | 10 | // Time Complexity: O(n). Space Complexity: O(n). 11 | // Approach: Recursively calculate height of left and right subtrees of a node 12 | // and assign height to the node as max of heights of two children + 1 13 | func Height(root *BinaryTreeNode) int { 14 | if root == nil { 15 | return 0 16 | } else { 17 | // compute depth of each subtree 18 | leftHeight := Height(root.left) 19 | rightHeight := Height(root.right) 20 | if leftHeight > rightHeight { 21 | return leftHeight + 1 22 | } else { 23 | return rightHeight + 1 24 | } 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/inorder_traversal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // TreeNode definition 6 | type TreeNode struct { 7 | Val int 8 | Left *TreeNode 9 | Right *TreeNode 10 | } 11 | 12 | func inorderTraversal(root *TreeNode) []int { 13 | var result []int 14 | var stack []*TreeNode 15 | current := root 16 | 17 | for current != nil || len(stack) > 0 { 18 | // Traverse all the way to the leftmost node, pushing each node onto the stack 19 | for current != nil { 20 | stack = append(stack, current) 21 | current = current.Left 22 | } 23 | 24 | // Pop the top node from the stack (current leftmost node) 25 | current, stack = stack[len(stack)-1], stack[:len(stack)-1] 26 | 27 | // Add the value of the current node to the result slice 28 | result = append(result, current.Val) 29 | 30 | // Move to the right subtree of the current node 31 | current = current.Right 32 | } 33 | 34 | return result 35 | } 36 | 37 | func main() { 38 | // Create a sample binary tree 39 | root := &TreeNode{Val: 1, Right: &TreeNode{Val: 2, Left: &TreeNode{Val: 3}}} 40 | 41 | // Perform in-order traversal 42 | result := inorderTraversal(root) 43 | 44 | // Print the result 45 | fmt.Println(result) // Output: [1 3 2] 46 | } 47 | -------------------------------------------------------------------------------- /Trees/Binary Trees/inorder_traversal.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = this.right = null; 5 | } 6 | } 7 | 8 | class Solution { 9 | inorderTraversal(root) { 10 | const result = []; 11 | const stack = []; 12 | let current = root; 13 | 14 | while (current || stack.length > 0) { 15 | // Traverse all the way to the leftmost node, pushing each node onto the stack 16 | while (current) { 17 | stack.push(current); 18 | current = current.left; 19 | } 20 | 21 | // Pop the top node from the stack (current leftmost node) 22 | current = stack.pop(); 23 | 24 | // Add the value of the current node to the result array 25 | result.push(current.val); 26 | 27 | // Move to the right subtree of the current node 28 | current = current.right; 29 | } 30 | 31 | return result; 32 | } 33 | } 34 | 35 | // Example usage 36 | const root = new TreeNode(1); 37 | root.right = new TreeNode(2); 38 | root.right.left = new TreeNode(3); 39 | 40 | const solution = new Solution(); 41 | const result = solution.inorderTraversal(root); 42 | 43 | console.log(result); // Output: [1, 3, 2] 44 | -------------------------------------------------------------------------------- /Trees/Binary Trees/inorder_traversal.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.left = self.right = None 5 | 6 | class Solution: 7 | def inorderTraversal(self, root): 8 | result = [] 9 | stack = [] 10 | current = root 11 | 12 | while current or stack: 13 | # Traverse all the way to the leftmost node, pushing each node onto the stack 14 | while current: 15 | stack.append(current) 16 | current = current.left 17 | 18 | # Pop the top node from the stack (current leftmost node) 19 | current = stack.pop() 20 | 21 | # Add the value of the current node to the result list 22 | result.append(current.val) 23 | 24 | # Move to the right subtree of the current node 25 | current = current.right 26 | 27 | return result 28 | 29 | # Example usage 30 | root = TreeNode(1) 31 | root.right = TreeNode(2) 32 | root.right.left = TreeNode(3) 33 | 34 | solution = Solution() 35 | result = solution.inorderTraversal(root) 36 | 37 | print(result) # Output: [1, 3, 2] 38 | -------------------------------------------------------------------------------- /Trees/Binary Trees/invert.cpp: -------------------------------------------------------------------------------- 1 | // Invert Binary tree 2 | #include 3 | 4 | class BinaryTreeNode { 5 | public: 6 | int data; 7 | BinaryTreeNode* left; 8 | BinaryTreeNode* right; 9 | 10 | BinaryTreeNode(int val) : data(val), left(nullptr), right(nullptr) {} 11 | }; 12 | 13 | BinaryTreeNode* invertTree(BinaryTreeNode* root) { 14 | if (root != nullptr) { 15 | root->left = invertTree(root->right); 16 | root->right = invertTree(root->left); 17 | } 18 | return root; 19 | } 20 | 21 | BinaryTreeNode* invertTree2(BinaryTreeNode* root) { 22 | if (root != nullptr) { 23 | // swap the pointers in this node 24 | BinaryTreeNode* temp = root->left; 25 | root->left = root->right; 26 | root->right = temp; 27 | 28 | invertTree2(root->left); 29 | invertTree2(root->right); 30 | } 31 | return root; 32 | } 33 | 34 | int main() { 35 | // Example usage: 36 | // Construct a binary tree 37 | BinaryTreeNode* root = new BinaryTreeNode(1); 38 | root->left = new BinaryTreeNode(2); 39 | root->right = new BinaryTreeNode(3); 40 | root->left->left = new BinaryTreeNode(4); 41 | root->left->right = new BinaryTreeNode(5); 42 | 43 | // Invert the binary tree using the first approach 44 | BinaryTreeNode* invertedRoot = invertTree(root); 45 | 46 | // Invert the binary tree using the second approach 47 | BinaryTreeNode* invertedRoot2 = invertTree2(root); 48 | 49 | // Additional code for printing or further usage... 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Trees/Binary Trees/invert.go: -------------------------------------------------------------------------------- 1 | // Invert Binary tree 2 | package main 3 | 4 | type BinaryTreeNode struct { 5 | left *BinaryTreeNode 6 | data int 7 | right *BinaryTreeNode 8 | } 9 | // Time Complexity: O(n). Space Complexity: O(n). 10 | // Approach: The inverse of an empty tree is an empty tree 11 | // The inverse of a tree with root r, and subtrees right and left is a tree with 12 | // root, whose right subtree is the inverse of left and whoose left subtree 13 | // is the inverse of right 14 | func InvertTree(root *BinaryTreeNode) *BinaryTreeNode { 15 | if root != nil { 16 | root.left, root.right = InvertTree(root.right), InvertTree(root.left) 17 | } 18 | return root 19 | } 20 | 21 | // Time Complexity: O(n). Space Complexity: O(n). 22 | // Method2 : swap pointers 23 | func InvertTree2(root *BinaryTreeNode) *BinaryTreeNode { 24 | if root == nil { 25 | return root 26 | } 27 | // swap the pointers in this node 28 | root.left, root.right = root.right, root.left 29 | InvertTree(root.left) 30 | InvertTree(root.right) 31 | return root 32 | } 33 | -------------------------------------------------------------------------------- /Trees/Binary Trees/invert.py: -------------------------------------------------------------------------------- 1 | # Invert Binary tree 2 | class BinaryTreeNode: 3 | def __init__(self, data): 4 | self.left = None 5 | self.data = data 6 | self.right = None 7 | 8 | def invert_tree(root): 9 | if root: 10 | root.left, root.right = invert_tree(root.right), invert_tree(root.left) 11 | return root 12 | 13 | def invert_tree2(root): 14 | if root is not None: 15 | # swap the pointers in this node 16 | root.left, root.right = root.right, root.left 17 | invert_tree2(root.left) 18 | invert_tree2(root.right) 19 | return root 20 | 21 | # Example usage: 22 | # Assuming you have a binary tree 23 | root = BinaryTreeNode(1) 24 | root.left = BinaryTreeNode(2) 25 | root.right = BinaryTreeNode(3) 26 | root.left.left = BinaryTreeNode(4) 27 | root.left.right = BinaryTreeNode(5) 28 | 29 | # Invert the binary tree using the first approach 30 | inverted_root = invert_tree(root) 31 | 32 | # Invert the binary tree using the second approach 33 | inverted_root2 = invert_tree2(root) 34 | -------------------------------------------------------------------------------- /Trees/Binary Trees/level_order_traversal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type BinaryTreeNode struct { 4 | left *BinaryTreeNode 5 | data int 6 | right *BinaryTreeNode 7 | } 8 | 9 | // Level order traversal is defined as follows: 10 | // 1 Visit the root. 11 | // 2 While traversing level 􀝈, keep all the elements at level 􀝈 + 1 in queue. 12 | // 3 Go to the next level and visit all the nodes at that level. 13 | // 4 Repeat this until all levels are completed. 14 | // The nodes of the tree are visited in the order: [1] [2 3] [ 4 5 6 7] 15 | // Time Complexity: O(n), Space Complexity: O(n) In the worst case, all the nodes on the entire last level could be in the queue. 16 | func LevelOrder(root *BinaryTreeNode) [][]int { 17 | if root == nil { 18 | return [][]int{} 19 | } 20 | // Data from each level is being returned as a separate list 21 | var result [][]int 22 | queue := []*BinaryTreeNode{root} 23 | for len(queue) > 0 { 24 | qlen := len(queue) 25 | var level []int 26 | for i:= 0; i < qlen; i++ { 27 | node := queue[0] 28 | level = append(level, node.data) 29 | queue = queue[1:] 30 | // if there are left children then append them in queue 31 | if node.left != nil { 32 | queue = append(queue, node.left) 33 | } 34 | // if there are right children then append them in queue 35 | if node.right != nil { 36 | queue = append(queue, node.right) 37 | } 38 | } 39 | } 40 | return result 41 | } 42 | -------------------------------------------------------------------------------- /Trees/Binary Trees/node_depth.go: -------------------------------------------------------------------------------- 1 | /* 2 | The distance between a node in a Binary Tree and the tree's root is called the 3 | node's depth. 4 | 5 | Write a function that takes in a Binary Tree and returns the sum of its nodes' 6 | depths. 7 | 8 | Sample Input: 9 | 1 10 | / \ 11 | 2 3 12 | / \ / \ 13 | 4 5 6 7 14 | / \ 15 | 8 9 16 | Output: 16 17 | */ 18 | 19 | /* 20 | The depth of any node in the tree is equal to the depth of its parent node plus 1. 21 | By starting at the root node whose depth is 0, you can pass down to every node in 22 | the tree its respective depth, and you can implement the algorithm that does this 23 | and that sums up all of the depths either recursively or iteratively. 24 | 25 | Time and Space complexity 26 | Average case: when the tree is balanced 27 | O(n) time | O(h) space - where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree 28 | */ 29 | package main 30 | 31 | type BinaryTree struct { 32 | Value int 33 | Left, Right *BinaryTree 34 | } 35 | 36 | func NodeDepths(root *BinaryTree) int { 37 | return nodeDepthHelper(root, 0) 38 | } 39 | 40 | func nodeDepthHelper(root *BinaryTree, depth int) int { 41 | if root == nil { 42 | return 0 43 | } 44 | return depth + nodeDepthHelper(root.Left, depth + 1) + nodeDepthHelper(root.Right, depth + 1) 45 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/postorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | // Post-Order Traversal of a Binary-Tree 2 | // Program Author : Abhisek Kumar Gupta 3 | /* 4 | 40 5 | / \ 6 | 10 30 7 | / \ / \ 8 | 5 -1 -1 28 9 | / \ / \ 10 | 1 -1 15 20 11 | / \ /\ /\ 12 | -1 -1 -1 -1 -1 -1 13 | Input : 40 10 5 1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 14 | Output : 1->5->10->15->20->28->30->40 15 | */ 16 | #include 17 | using namespace std; 18 | 19 | class Node{ 20 | public: 21 | int data; 22 | Node* left; 23 | Node* right; 24 | 25 | Node(int x){ 26 | data = x; 27 | left = NULL; 28 | right = NULL; 29 | } 30 | }; 31 | 32 | Node* build_binary_tree(){ 33 | int data; 34 | cin >> data; 35 | if(data == -1){ 36 | return NULL; 37 | } 38 | Node* root = new Node(data); 39 | root->left = build_binary_tree(); 40 | root->right = build_binary_tree(); 41 | return root; 42 | } 43 | void print_binary_tree(Node* root){ 44 | if(root == NULL) 45 | return; 46 | print_binary_tree(root->left); 47 | print_binary_tree(root->right); 48 | cout << root->data << "->"; 49 | } 50 | int main(){ 51 | Node* root = build_binary_tree(); 52 | print_binary_tree(root); 53 | return 0; 54 | } 55 | //40 10 5 1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 56 | -------------------------------------------------------------------------------- /Trees/Binary Trees/preorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | // Pre-Order Traversal of a Binary-Tree 2 | // Program Author : Abhisek Kumar Gupta 3 | /* 4 | 40 5 | / \ 6 | 10 30 7 | / \ / \ 8 | 5 -1 -1 28 9 | / \ / \ 10 | 1 -1 15 20 11 | / \ /\ /\ 12 | -1 -1 -1 -1 -1 -1 13 | Input : 40 10 5 1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 14 | Output : 40->10->5->1->30->28->15->20 15 | */ 16 | #include 17 | using namespace std; 18 | class Node{ 19 | public: 20 | int data; 21 | Node *left; 22 | Node *right; 23 | 24 | Node(int x){ 25 | data = x; 26 | left = NULL; 27 | right = NULL; 28 | } 29 | 30 | }; 31 | 32 | Node* build_binary_tree(){ 33 | int data; 34 | cin >> data; 35 | if(data == -1) 36 | return NULL; 37 | Node* root = new Node(data); 38 | root->left = build_binary_tree(); 39 | root->right = build_binary_tree(); 40 | return root; 41 | } 42 | 43 | void print_binary_tree(Node* root){ 44 | if(root == NULL) 45 | return; 46 | cout << root->data << "->"; 47 | print_binary_tree(root->left); 48 | print_binary_tree(root->right); 49 | } 50 | 51 | int main(){ 52 | Node* root = build_binary_tree(); 53 | print_binary_tree(root); 54 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/remove_leaf_nodes.go: -------------------------------------------------------------------------------- 1 | // Remove leaf nodes 2 | package main 3 | 4 | type BinaryTreeNode struct { 5 | left *BinaryTreeNode 6 | data int 7 | right *BinaryTreeNode 8 | } 9 | 10 | // Time Complexity: O(n). Space Complexity: O(n). 11 | // Approach: recurse both left and right subtree and check if the node doesn't have 12 | // left and right children 13 | func RemoveLeafNodes(root *BinaryTreeNode) *BinaryTreeNode { 14 | if root == nil { 15 | return root 16 | } 17 | // if it doesnt have left and right children then delete it 18 | if root.left == nil && root.right == nil { 19 | root = nil 20 | return root 21 | } else { // recurse to left and right subtree 22 | root.left = RemoveLeafNodes(root.left) 23 | root.right = RemoveLeafNodes(root.right) 24 | } 25 | return root 26 | } -------------------------------------------------------------------------------- /Trees/Binary Trees/sum_of_all_nodes.cpp: -------------------------------------------------------------------------------- 1 | // Binary Tree : Sum of all Nodes 2 | // Program Author : Abhisek Kumar Gupta 3 | /* 4 | 40 5 | / \ 6 | 10 30 7 | / \ / \ 8 | 5 -1 -1 28 9 | / \ / \ 10 | 1 -1 15 20 11 | / \ /\ /\ 12 | 1 -1 -1 -1 -1 -1 13 | /\ 14 | -1 -1 15 | Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 16 | Output : 150 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | class Node{ 22 | public: 23 | int data; 24 | Node* left; 25 | Node* right; 26 | 27 | Node(int d){ 28 | data = d; 29 | } 30 | }; 31 | Node* build_binary_tree(){ 32 | int data; 33 | cin >> data; 34 | if(data == -1){ 35 | return NULL; 36 | } 37 | Node* root = new Node(data); 38 | root->left = build_binary_tree(); 39 | root->right = build_binary_tree(); 40 | return root; 41 | } 42 | 43 | int sum_of_all_nodes(Node* root){ 44 | if(root == NULL){ 45 | return 0; 46 | } 47 | return root->data + sum_of_all_nodes(root->right) + sum_of_all_nodes(root->left); 48 | } 49 | int main(){ 50 | Node* root = build_binary_tree(); 51 | int sum_of_nodes = sum_of_all_nodes(root); 52 | cout << sum_of_nodes; 53 | return 0; 54 | } -------------------------------------------------------------------------------- /sorting/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akgmage/data-structures-and-algorithms/a9d5f0c556b70a787a0c834bf2b1ea40ec39858d/sorting/.DS_Store -------------------------------------------------------------------------------- /sorting/bubble_sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here's how the Bubble Sort algorithm works: 3 | 4 | 1. We start by comparing the first two elements of the array. If the first element is greater than the second 5 | element, we swap them. 6 | 2. We then compare the second and third elements. If the second element is greater than the third element, 7 | we swap them. 8 | 3. We continue this process until we reach the end of the array. At this point, the largest element will 9 | be at the end of the array. 10 | 4. We then repeat steps 1-3 for the remaining unsorted portion of the array until the entire array is sorted. 11 | 12 | The time complexity of Bubble Sort is O(n^2) in the worst and average case, and O(n) in the best case when 13 | the input array is already sorted. 14 | 15 | The space complexity is O(1) as Bubble Sort operates on the input array in-place. 16 | 17 | Bubble sort is O(n) on a list that is already sorted i.e. Best case 18 | 19 | Sample Input : [2, 1, 9, 3, 5, 4, 0] 20 | Output : [0 1 2 3 4 5 9] 21 | ''' 22 | 23 | def bubbleSort(arr): 24 | n = len(arr) 25 | # Traverse through all array elements 26 | for i in range(n - 1): 27 | # Last i elements are already sorted 28 | for j in range(0, n - i - 1): 29 | # Swap adjacent elements if they are in the wrong order 30 | if arr[j] > arr[j + 1]: 31 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 32 | 33 | arr = [64, 25, 12, 22, 11] 34 | bubbleSort(arr) 35 | print("Sorted array:", arr) 36 | -------------------------------------------------------------------------------- /sorting/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int Hoare_partition(int arr[],int l,int h) 5 | { 6 | // Here p is the Index of pivot element 7 | // Here We consider first element as pivot, 8 | // But if we Want to consider any element as pivot then just swap that index with the first element 9 | int pivot=arr[l]; 10 | int i=l-1,j=h+1; 11 | 12 | while(true) 13 | { 14 | do{ 15 | i++; 16 | }while(arr[i]pivot); 21 | 22 | if(i>=j) 23 | return j; 24 | swap(arr[i],arr[j]); 25 | } 26 | } 27 | 28 | void Quick_Sort(int arr[],int low,int high) 29 | { 30 | 31 | if(low