├── .clang-format ├── .gitignore ├── Algorithms ├── Backtracking │ ├── combination_sum1.cpp │ ├── combination_sum2.cpp │ ├── letter_case_permutation.cpp │ ├── letter_combination_phone_numbers.cpp │ ├── palindrome_partitioning.cpp │ ├── permutations.cpp │ ├── rat_in_maze.cpp │ ├── restore_ip_address.cpp │ └── subsets.cpp ├── Binary_Search │ ├── advanced_condition │ │ ├── aggressive_cows.cpp │ │ ├── allocate_pages.cpp │ │ ├── koko_bananas.cpp │ │ ├── median_sorted_arr.cpp │ │ ├── minimum_days_m_bouqets.cpp │ │ ├── painter_part.cpp │ │ ├── ship_packages_d_days.cpp │ │ ├── split_array_sum.cpp │ │ └── time_to_repair_cars.cpp │ ├── basic │ │ ├── binary_search.cpp │ │ ├── ceil_sorted.cpp │ │ ├── count_occur.cpp │ │ ├── first_last_occ.cpp │ │ ├── first_one_bin_inf.cpp │ │ ├── floor_sorted.cpp │ │ ├── insert_pos.cpp │ │ ├── min_diff_arr.cpp │ │ ├── pos_inf_arr.cpp │ │ ├── rev_binary_search.cpp │ │ └── sqrt.cpp │ ├── hard │ │ └── find_in_mountain_array.cpp │ ├── medium │ │ ├── first_bad_version.cpp │ │ ├── kth_miss_pos.cpp │ │ ├── median_mat.cpp │ │ ├── next_alpha_element.cpp │ │ ├── number_of_matching_subseq.cpp │ │ ├── peak_element.cpp │ │ ├── peak_element2.cpp │ │ ├── rot_arr_min.cpp │ │ ├── rot_arr_search.cpp │ │ ├── search_mat.cpp │ │ └── single_ele.cpp │ └── readme.txt ├── Bit_manipulation │ ├── all_pair_sum_xor.txt │ ├── all_pair_xor_sum.cpp │ ├── all_pair_xor_sum.txt │ ├── checking_bit_1.txt │ ├── chef_got_recipies.cpp │ ├── chef_got_recipies.txt │ ├── count_bit_1.txt │ ├── hamming_distance.cpp │ ├── min_flip_xor.txt │ ├── power_of_two_op.cpp │ ├── power_of_two_unop.cpp │ ├── single_number_3.cpp │ ├── subset_bitmask.cpp │ ├── subset_sum.txt │ ├── subset_sum_bitmask.cpp │ ├── subsets_bitmask.txt │ ├── xor_properties.txt │ └── xor_query.txt ├── Dynamic_Programming │ ├── 1d_dp │ │ ├── fibonacci.cpp │ │ ├── house_robber.cpp │ │ ├── house_robber2.cpp │ │ ├── min_cost_climbing_stairs.cpp │ │ └── tribonacci.cpp │ ├── LCS_pattern │ │ ├── distinct_subsequences.cpp │ │ ├── edit_dist.cpp │ │ ├── longest_common_subsequence.cpp │ │ ├── longest_common_substring.cpp │ │ ├── longest_palindromic_subsequence.cpp │ │ ├── longest_repeating_subsequence.cpp │ │ ├── min_del_equal_string.cpp │ │ ├── min_del_pal_string.cpp │ │ ├── min_ins_pal_string.cpp │ │ ├── print_longest_common_subsequence.cpp │ │ ├── readme.txt │ │ ├── shortest_common_supersequence.cpp │ │ ├── uncrossed_lines.cpp │ │ └── wildcard_matching.cpp │ ├── LIS_pattern │ │ ├── best_team.cpp │ │ ├── delete_earn.cpp │ │ ├── longest_bitonic_subsequence.cpp │ │ ├── longest_decreasing_subsequence.cpp │ │ ├── longest_divisible_subset.cpp │ │ ├── longest_increasing_subsequence.cpp │ │ ├── longest_string_chain.cpp │ │ ├── max_length_pair_chain.cpp │ │ ├── max_sum_incerasing_subsequence.cpp │ │ ├── maximum_height_stacking_cubiods.cpp │ │ ├── min_deletions_to_make_array_sorted.cpp │ │ ├── number_of_lis.cpp │ │ ├── readme.txt │ │ └── russian_doll_envelopes.cpp │ ├── MCM_pattern │ │ ├── bool_paranth.cpp │ │ ├── egg_dropping.cpp │ │ ├── matrix_chain_mult.cpp │ │ ├── pal_partition.cpp │ │ └── scramble_string.cpp │ ├── README.md │ ├── grid_pattern │ │ ├── grid_path_obstacle.cpp │ │ ├── grid_unique_paths.cpp │ │ └── min_path_sum.cpp │ ├── knapsack_subset_sum │ │ ├── 0_1_knapsack.cpp │ │ ├── count_partition_same_diff.cpp │ │ ├── count_subset_sum_k.cpp │ │ ├── equal_sum.cpp │ │ ├── minimum_sum_partition.cpp │ │ ├── subset_sum.cpp │ │ └── target_sum.cpp │ ├── tree_pattern │ │ ├── diameter_binary_tree.cpp │ │ └── max_path_sum.cpp │ └── unbounded_knapsack │ │ ├── coin_change.txt │ │ ├── coin_change_max_ways.cpp │ │ ├── coin_change_min_coins.cpp │ │ ├── rod_cutting.cpp │ │ └── unbounded_knapsack.cpp ├── Greedy │ ├── activity_selection.cpp │ ├── advantage_shuffle.cpp │ ├── assign_cookies.cpp │ ├── candy.cpp │ ├── fractional_knapsack.cpp │ ├── gas_station.cpp │ ├── job_sequencing.cpp │ ├── lemonade_change.cpp │ ├── max_length_pair_chain.cpp │ ├── merge_interval.cpp │ ├── min_fibonacci_nos.cpp │ ├── min_swaps_strings.cpp │ ├── minimum_platforms.cpp │ └── n_meeting_room.cpp ├── Number_Theory │ ├── Binomial_Coefficient_Inverse_Modulo.cpp │ ├── Binomial_Coefficient_Inverse_Modulo.txt │ ├── Euler_Totient_Function.txt │ ├── Euler_Totient_Function_Part2.txt │ ├── Finding_modulo_multiplicate_inverse.txt │ ├── binary_exponentiation.cpp │ ├── div_from_prime_factors.txt │ ├── divisor_from_prime_factors.txt │ ├── fermat's_mod_mul_inv.cpp │ ├── matrices.cpp │ ├── matrix_exponentiation.cpp │ ├── modulo_arithmetic._problems.txt │ ├── modulo_arithmetic.cpp │ ├── modulo_arithmetic_2.cpp │ ├── modulo_multiplicate_inverse.txt │ ├── primality_sqrt(n).cpp │ ├── primality_sqrt.cpp │ ├── prime_factors.cpp │ └── sieve_of_eratotheses.cpp ├── Prefix_Sum │ ├── 2d_sums │ │ ├── prefix_sum_matrix.png │ │ └── range_sum_queries_2d.cpp │ ├── easy │ │ ├── range_sum_queries_lc.cpp │ │ ├── static_range_sum_queries.cpp │ │ └── xor_queries_subarray.cpp │ ├── hard │ │ └── car_pooling.cpp │ ├── medium │ │ ├── character_occur_max_times.cpp │ │ ├── count_vowels_ranges.cpp │ │ ├── product_last_k.cpp │ │ └── range_addition.cpp │ └── readme.txt ├── Randomized │ ├── notes.txt │ └── random_weight_pick.cpp ├── Recursion │ ├── delete_mid_stack.cpp │ ├── factorial.cpp │ ├── generate_balanced_paran.cpp │ ├── josephus.cpp │ ├── kth_symbol.cpp │ ├── letter_case_change.cpp │ ├── nbit_nos.cpp │ ├── permutation_letter_change.cpp │ ├── power_set.cpp │ ├── print_nums.cpp │ ├── rev_stack_rec.cpp │ ├── sort_stack.cpp │ ├── subset_strings.cpp │ ├── subset_sums.cpp │ ├── tower_of_hanoi.cpp │ └── tree_height.cpp ├── Sliding_Window │ ├── fixed_size │ │ ├── easy │ │ │ ├── max_subarr_k.cpp │ │ │ ├── max_sum_k.cpp │ │ │ ├── min_recolors.cpp │ │ │ ├── sub_arr_avg.cpp │ │ │ └── substring_k_distinct.cpp │ │ ├── hard │ │ │ ├── first_negative.cpp │ │ │ ├── subarray_k_different.cpp │ │ │ └── substring_concat_words.cpp │ │ └── medium │ │ │ ├── count_ana.cpp │ │ │ └── repeated_dna_subsequences.cpp │ └── var_size │ │ ├── easy │ │ ├── longest_uniq_subst.cpp │ │ ├── min_sum_subarr.cpp │ │ ├── pick_toys.cpp │ │ └── subarr_k_sum.cpp │ │ ├── hard │ │ └── min_window_substr.cpp │ │ ├── medium │ │ ├── binary_subarray_sum.cpp │ │ ├── longest_k_atleast_substr.cpp │ │ ├── longest_repeating_character_replacement.cpp │ │ ├── max_conseq_ones.cpp │ │ ├── nice_subarr.cpp │ │ ├── subarr_k_distinct.cpp │ │ ├── subarray_prod_k.cpp │ │ └── substring_k_chars.cpp │ │ └── more_problems.cpp ├── Sorting │ ├── array_partition.cpp │ ├── bubble_sort.cpp │ ├── can_make_ap.cpp │ ├── insert_intervals.cpp │ ├── insertion_sort.cpp │ ├── inv_count.cpp │ ├── merge_intervals.cpp │ ├── merge_sort.cpp │ ├── missing_no.cpp │ ├── reverse_pairs.cpp │ ├── selection_sort.cpp │ ├── sort_parity.cpp │ └── swap_sort.cpp └── Two_Pointer │ ├── easy │ ├── is_subsequence.cpp │ ├── max_pair_sum.cpp │ ├── remove_duplicates.cpp │ ├── squares_sorted_arr.cpp │ ├── two_pointer_technique.cpp │ └── two_sum2.cpp │ ├── medium │ ├── celebrity_problem.cpp │ ├── container_most_water.cpp │ ├── duplicate_zeros.cpp │ ├── four_sum.cpp │ ├── max_consequtive_ones.cpp │ ├── move_pieces.cpp │ ├── move_zeros.cpp │ ├── partition_labels.cpp │ ├── rainwater_trapping.cpp │ ├── three_sum.cpp │ ├── three_sum_closest.cpp │ └── valid_palindrome2.cpp │ └── two_ptr.md ├── C++ ├── OOPS │ ├── access_modifier1.cpp │ ├── classes_intro.cpp │ ├── constructors1.cpp │ ├── destructors.cpp │ ├── friend_class.cpp │ ├── function_overloading.cpp │ ├── function_overloading2.cpp │ ├── function_overloading3.cpp │ ├── hybrid_inheritence.cpp │ ├── inheritence1.cpp │ ├── local_class.cpp │ ├── multilevel_inheritence.cpp │ ├── multiple_inheritence.cpp │ ├── operator_overloading.cpp │ ├── operator_overloading2.cpp │ ├── operator_overloading3.cpp │ ├── operator_overloading4.cpp │ ├── polymorphism.cpp │ ├── single_inheritence.cpp │ ├── static_keyword.cpp │ ├── virtual_destructor1.cpp │ ├── virtual_function3.cpp │ ├── virtual_functions1.cpp │ └── virtual_functions2.cpp ├── STL │ ├── binary_search.cpp │ ├── bitset.cpp │ ├── dequeue_basics.cpp │ ├── iterators.cpp │ ├── list_basics.cpp │ ├── map_basics.cpp │ ├── priority_queue_basics.cpp │ ├── queue_basics.cpp │ ├── set_basics.cpp │ ├── stack_basics.cpp │ ├── template_fn.cpp │ ├── vector_basics.cpp │ └── vector_of_vector.cpp ├── advanced │ ├── functors.cpp │ ├── lambda_exp.cpp │ └── user_def_literals.cpp ├── concurrency │ ├── conditional_variable.cpp │ ├── mutex_example.cpp │ ├── readme.md │ ├── rwlocks.cpp │ └── scoped_lock.cpp ├── directives │ ├── macros1.cpp │ ├── macros2.cpp │ └── pragma.cpp ├── exception_handling │ ├── custom_exception.cpp │ ├── try_catch1.cpp │ ├── try_catch2.cpp │ └── try_catch3.cpp ├── file_handling │ ├── file_handling1.cpp │ ├── file_handling2.cpp │ ├── hello.txt │ └── hello2.txt ├── gdb_tutorial │ ├── Makefile │ ├── main.cc │ └── readme.md ├── namespaces │ ├── namespace3.cpp │ ├── namespace5.cpp │ ├── namespace6.cpp │ ├── namespaces1.cpp │ ├── namespaces2.cpp │ ├── namespaces4.cpp │ └── simple_header.h ├── ptrs │ ├── smart_pointer.cpp │ ├── smart_pointer2.cpp │ ├── smart_pointer3.cpp │ ├── smart_pointer4.cpp │ ├── this_pointer.cpp │ └── unique_ptr.cpp ├── readme.md └── templates │ ├── template3.cpp │ ├── template_specialization.cpp │ ├── templates1.cpp │ ├── templates2.cpp │ ├── templates4.cpp │ └── variadic_templates.cpp ├── Data_Structures ├── Arrays │ ├── closest_pair.cpp │ ├── dup_arr.cpp │ ├── find_target_after_sort.cpp │ ├── game_of_life.cpp │ ├── jump_dist.cpp │ ├── largest_sum_contigous_arr.cpp │ ├── longest_increasing_subs.cpp │ ├── majority_ele1.cpp │ ├── majority_ele2.cpp │ ├── mat_zeros.cpp │ ├── max_asc_sum.cpp │ ├── max_subarr_sum.cpp │ ├── merge_sorted_arrs.cpp │ ├── merge_union_intersection.cpp │ ├── min_distance.cpp │ ├── mov_zeros.cpp │ ├── next_greater.cpp │ ├── next_perm.cpp │ ├── pascal_triangle.cpp │ ├── rearrange_i=i.cpp │ ├── reverse_arr.cpp │ ├── rotate_mat.cpp │ ├── search_2d_mat.cpp │ ├── sort_arr_0_1_2.cpp │ ├── subarray_0.cpp │ └── toeplitz_mat.cpp ├── Binary_Search_Tree │ ├── easy │ │ ├── ceil.cpp │ │ ├── floor.cpp │ │ ├── inorder_traversal.cpp │ │ ├── intro.cpp │ │ └── min_max.cpp │ └── medium │ │ ├── balance_bst.cpp │ │ ├── const_from_inorder.cpp │ │ ├── const_from_preorder.cpp │ │ ├── delete_leaf_nodes.cpp │ │ ├── delete_node_bst.cpp │ │ ├── kth_smallest.cpp │ │ ├── lowest_common_ancestor.cpp │ │ ├── min_difference.cpp │ │ ├── range_sum.cpp │ │ └── search_insert.cpp ├── Binary_Tree │ ├── construction │ │ ├── const_from_inorder_postorder.cpp │ │ ├── const_from_inorder_preorder.cpp │ │ ├── const_from_level_order.cpp │ │ └── const_from_preorder_postorder.cpp │ ├── easy │ │ ├── balanced_tree.cpp │ │ ├── identical_trees.cpp │ │ ├── intro.cpp │ │ ├── klth_argest_sum.cpp │ │ ├── max_height.cpp │ │ ├── max_level_sum.cpp │ │ ├── max_width.cpp │ │ ├── min_height.cpp │ │ ├── mirror.cpp │ │ ├── subtree_check.cpp │ │ ├── subtree_check2.cpp │ │ ├── symmetric_tree.cpp │ │ └── univalued_tree.cpp │ ├── implement │ │ ├── Makefile │ │ └── basic_binary_tree.cpp │ ├── leaves │ │ ├── deepest_leaves.cpp │ │ ├── leaf_similar_trees.cpp │ │ └── sum_left_leaves.cpp │ ├── medium │ │ ├── burn_a_tree.cpp │ │ ├── check_balanced.cpp │ │ ├── count_complete_nodes.cpp │ │ ├── cousins.cpp │ │ ├── diameter.cpp │ │ ├── flatten_tree.cpp │ │ ├── lca_subtree.cpp │ │ ├── lowest_common_ancestor.cpp │ │ ├── node_at_dist_k.cpp │ │ └── serialize_deserialize.cpp │ ├── path_sums │ │ ├── max_path_sum.cpp │ │ ├── path_sum1.cpp │ │ └── path_sum2.cpp │ ├── traversal │ │ ├── boundary_traversal.cpp │ │ ├── in_pre_post_iter.cpp │ │ ├── in_pre_post_rec.cpp │ │ ├── level_order_trav.cpp │ │ ├── level_order_zigzag.cpp │ │ └── vertical_order.cpp │ └── views │ │ ├── bottom_view.cpp │ │ ├── left_view.cpp │ │ ├── right_view.cpp │ │ └── top_view.cpp ├── Graph │ ├── cycle │ │ ├── dfs_cycle_directed_graph.png │ │ ├── directed_cycle_detect_dfs.cpp │ │ ├── longest_cycle_dg.cpp │ │ ├── shortest_cycle_udg.cpp │ │ ├── undirected_cycle_detect_bfs.cpp │ │ └── undirected_cycle_detect_dfs.cpp │ ├── easy │ │ ├── bfs.cpp │ │ ├── center_star_graph.cpp │ │ ├── count_unreachable_nodes.cpp │ │ ├── dfs.cpp │ │ ├── find_path_exists.cpp │ │ ├── number_of_operations_connected.cpp │ │ ├── reorder_routes.cpp │ │ └── steps_by_knight.cpp │ ├── floodfill │ │ ├── 01_matrix.cpp │ │ ├── as_far_as_land.cpp │ │ ├── count_sub_islands.cpp │ │ ├── find_all_groups_farmland.cpp │ │ ├── flood_fill.cpp │ │ ├── max_area_island.cpp │ │ ├── notes.txt │ │ ├── number_of_enclaves.cpp │ │ ├── number_of_islands.cpp │ │ ├── pacific_atlantic_water_flow.cpp │ │ ├── rotten_oranges.cpp │ │ ├── shortest_bridge.cpp │ │ └── surrounded_regions.cpp │ ├── graph_structure.txt │ ├── hard │ │ ├── word_ladder.cpp │ │ └── word_ladder2.cpp │ ├── shortest_paths │ │ ├── cheapest_flight_k_stops.cpp │ │ ├── city_smallest_threshold.cpp │ │ ├── dijkstra.cpp │ │ ├── network_delay_time.cpp │ │ ├── path_max_prob.cpp │ │ ├── path_with_minimum_effort.cpp │ │ ├── shortest_path_binary_maze.cpp │ │ └── snake_ladders.cpp │ └── toplogical_sort │ │ ├── alien_dictionary.cpp │ │ ├── course_schedule.cpp │ │ ├── course_schedule2.cpp │ │ ├── course_schedule4.cpp │ │ ├── eventual_safe_state.cpp │ │ ├── topological_sort_bfs.cpp │ │ └── topological_sort_dfs.cpp ├── Hashing │ ├── easy │ │ ├── anagram.cpp │ │ ├── common_in_strs.cpp │ │ ├── largest_subarray_zero_sum.cpp │ │ ├── longest_pali.cpp │ │ ├── num_pairs.cpp │ │ ├── numbers_smaller_curr.cpp │ │ ├── subarray_given_xor.cpp │ │ ├── sum_uniq.cpp │ │ ├── two_sum.cpp │ │ └── uni_number_of_occur.cpp │ └── medium │ │ ├── count_no_bad_pairs.cpp │ │ ├── count_three_length_palindrome_subsequence.cpp │ │ ├── design_number_container.cpp │ │ ├── find_distinct_colors_balls.cpp │ │ ├── group_anagrams.cpp │ │ ├── identify_largest_outlier.cpp │ │ ├── long_cont_arr.cpp │ │ ├── longest_consequetive_sequence.cpp │ │ └── sort_freq_val.cpp ├── Heap │ ├── easy │ │ ├── connect_m_ropes.cpp │ │ ├── intro_heap.cpp │ │ ├── k_largest_ele.cpp │ │ ├── kth_smallest.cpp │ │ ├── last_stone_weight.cpp │ │ └── values_greater_than_threshold.cpp │ └── medium │ │ ├── data_stream_median.cpp │ │ ├── design_twitter.cpp │ │ ├── freq_sort.cpp │ │ ├── k_closest_nums.cpp │ │ ├── k_closest_pairs.cpp │ │ ├── k_closest_points.cpp │ │ ├── k_freq_nums.cpp │ │ ├── k_smallest_mat.cpp │ │ ├── max_sum_pair.cpp │ │ ├── reduce_arr.cpp │ │ ├── sort_char_fre.cpp │ │ ├── sort_k_sorted_arr.cpp │ │ ├── stock_price_fluctuation.cpp │ │ └── task_scheduler.cpp ├── Linked_lists │ ├── LinkedListProblems.pdf │ ├── add_nums.cpp │ ├── binary_no_linked_list.cpp │ ├── build_and_print_list.cpp │ ├── clone_list.cpp │ ├── del_pos.cpp │ ├── delete_key.cpp │ ├── detect_loop.cpp │ ├── find_length.cpp │ ├── find_mid.cpp │ ├── flatten_list.cpp │ ├── insert.cpp │ ├── intersection_lists.cpp │ ├── intersection_sorted.cpp │ ├── merge_sorted.cpp │ ├── palindrome_list.cpp │ ├── partition_list.cpp │ ├── remove_n_end.cpp │ ├── reorder_list.cpp │ ├── reverse_k_nodes.cpp │ ├── reverse_list.cpp │ ├── rotate_list.cpp │ ├── search_ele.cpp │ └── sort_0_1_2.cpp ├── Queues │ ├── lru_cache.cpp │ ├── queue_implement.cpp │ └── stack_using_queues.cpp ├── Stacks │ ├── additional_problems.txt │ ├── easy │ │ ├── backspace_strings.cpp │ │ ├── baseball_game.cpp │ │ ├── great_string.cpp │ │ ├── next_left_greater.cpp │ │ ├── next_left_smaller.cpp │ │ ├── next_right_greater.cpp │ │ ├── next_right_smaller.cpp │ │ ├── remove_adj_ele.cpp │ │ ├── rev_string.cpp │ │ ├── stack_implementation.cpp │ │ ├── stacks_intro.cpp │ │ └── valid_paranthesis.cpp │ ├── medium │ │ ├── asteroid_collision.cpp │ │ ├── daily_temparatures.cpp │ │ ├── decode_string.cpp │ │ ├── dup_paran.cpp │ │ ├── largest_area_hist.cpp │ │ ├── longest_valid_paran.cpp │ │ ├── min_stack1.cpp │ │ ├── min_stack2.cpp │ │ ├── minimum_remove.cpp │ │ ├── queue_using_stack.cpp │ │ ├── remove_adj_ele2.cpp │ │ ├── remove_all_occurences.cpp │ │ ├── remove_duplicates.cpp │ │ ├── score_paran.cpp │ │ ├── stack_subseq.cpp │ │ ├── stock_span.cpp │ │ └── temp_span.cpp │ └── practice_order.txt ├── Strings │ ├── easy │ │ ├── consecutive_chars.cpp │ │ ├── equivalent_strs.cpp │ │ ├── first_uniq_char.cpp │ │ ├── homo_substr.cpp │ │ ├── is_panagram.cpp │ │ ├── longest_common_prefix.cpp │ │ └── reverse_words_dot.cpp │ └── medium │ │ ├── add_bin_nums.cpp │ │ ├── camelcase_match.cpp │ │ ├── custom_sort.cpp │ │ ├── dest_city.cpp │ │ ├── interleaving_string.cpp │ │ ├── lex_strings.cpp │ │ ├── minstep_ana.cpp │ │ ├── reduce_binary.cpp │ │ ├── roatate_strings.cpp │ │ ├── subtr_with_1s.cpp │ │ ├── swap_longest_string.cpp │ │ └── uniq_email.cpp └── Trie │ ├── design_add_word_data_structure.cpp │ ├── extra_characters_string.cpp │ ├── longest_valid_word_prefix.cpp │ ├── longest_word_dictionary.cpp │ ├── maximum_xor_two_numbers.cpp │ ├── maximum_xor_with_an_element.cpp │ ├── number_distinct_substrings.cpp │ └── trie_implementation.cpp ├── Java ├── arrays │ ├── add_matrix.java │ ├── anonymous_arrays.java │ ├── arr_count.java │ ├── arr_input.java │ ├── array_basics.java │ ├── array_search.java │ ├── bubble_sort.java │ ├── check_identity.java │ ├── intro_2d.java │ ├── jagged_array.java │ ├── pairs_sum.java │ ├── passby_reference.java │ ├── remove_duplicates.java │ ├── reverse_arr.java │ ├── sum_rows.java │ └── transpose_mat.java ├── collections │ ├── arraylist_intro.java │ ├── linkedlist_intro.java │ ├── queue_intro.java │ ├── set_intro.java │ ├── stack_intro.java │ └── vector_intro.java ├── date │ └── date_time.java ├── exception_handling │ ├── custom_exception.java │ ├── custom_exception2.java │ ├── finally_intro.java │ ├── throw_intro.java │ ├── throws_intro.java │ ├── try_catch_intro.java │ └── try_catch_multiple.java ├── file_handling │ ├── buffered_reader.java │ ├── create_file.java │ ├── data_stream.java │ ├── dummy.txt │ ├── dummy2.txt │ ├── dummy3.txt │ ├── dummy4.bin │ ├── dummy4.txt │ ├── dummy5.txt │ ├── file_stream2.java │ ├── file_stream3.java │ ├── file_streams1.java │ ├── file_writer.java │ ├── intro_file_handling.java │ ├── read_files_scanner.java │ ├── saved_student.bin │ ├── serialize_deserialize.java │ └── somename.txt ├── input_output │ ├── armstrong.java │ └── sort_collections.java ├── looping │ ├── first_last.java │ ├── mult_table.java │ └── sum_digits.java ├── nested_loops │ ├── break_13.java │ ├── print_nos.java │ ├── print_rev_nos.java │ ├── print_rev_star.java │ ├── print_star.java │ └── sum_5.java ├── object_oriented │ ├── abstract_classes_intro.java │ ├── access_specifiers.java │ ├── class_association.java │ ├── class_composition.java │ ├── classes_intro.java │ ├── constructor_in_inheritence.java │ ├── constructor_intro.java │ ├── finalize_method.java │ ├── get_set.java │ ├── hybrid_inheritence.java │ ├── inheritence_intro.java │ ├── interfaces_intro.java │ ├── method_overloading.java │ ├── multi_level_inheritence.java │ ├── multiple_inheritence.java │ ├── nested_class_example.java │ ├── nested_classes_intro.java │ ├── overload_main.java │ ├── static_methods.java │ ├── static_methods2.java │ ├── static_nested_class_intro.java │ ├── static_variable.java │ └── super_keyword.java ├── pattern_printing │ ├── lower_triangle.java │ ├── mat_pat.java │ └── triangle_numbers.java ├── regex │ └── regex_basics.java ├── simple_package │ ├── faculty.java │ └── student.java ├── strings │ ├── count_words.java │ ├── intro_string_buffer.java │ ├── palindrome.java │ ├── rev_words.java │ ├── string_arr.java │ ├── string_basics.java │ ├── string_builtin_methods.java │ ├── string_comp.java │ ├── string_ops.java │ ├── string_tokenizer_basics.java │ ├── strings_intro.java │ ├── toggle_case.java │ ├── validate_pass.java │ └── vov_cons.java └── threading │ ├── child_thread.java │ ├── thread_example.java │ ├── thread_pool.java │ ├── thread_scheduling.java │ ├── thread_yield.java │ ├── threading_intro.java │ ├── threading_intro2.java │ ├── threading_intro3.java │ └── threading_priority.java ├── LICENSE ├── Python ├── OOPS │ ├── classes_intro.py │ └── namespaces.py └── basics │ ├── exception_handling1.py │ ├── functions.py │ └── match_keyword.py ├── README.md ├── hello.cpp ├── hello.ii ├── hello.s ├── practice ├── practice2 └── practice4 /Algorithms/Binary_Search/advanced_condition/aggressive_cows.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/problems/aggressive-cows/0 2 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/advanced_condition/median_sorted_arr.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/median-of-two-sorted-arrays/ 2 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/advanced_condition/minimum_days_m_bouqets.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/advanced_condition/time_to_repair_cars.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-time-to-repair-cars/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/basic/insert_pos.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-insert-position/ 2 | 3 | // Given a sorted array of distinct integers and a target value, 4 | // return the index if the target is found. If not, return the index where it 5 | // would be if it were inserted in order. 6 | 7 | // You must write an algorithm with O(log n) runtime complexity. 8 | 9 | // Example 1: 10 | 11 | // Input: nums = [1,3,5,6], target = 5 12 | // Output: 2 13 | 14 | // Example 2: 15 | 16 | // Input: nums = [1,3,5,6], target = 2 17 | // Output: 1 18 | 19 | #include 20 | using namespace std; 21 | 22 | class Solution { 23 | public: 24 | int searchInsert(vector& nums, int target) { 25 | int n = nums.size(); 26 | int left = 0; 27 | int right = n - 1; 28 | 29 | while (left <= right) { 30 | int mid = (left + right) / 2; 31 | 32 | if (nums[mid] == target) { 33 | return mid; 34 | } 35 | 36 | else if (target < nums[mid]) { 37 | right = mid - 1; 38 | } else { 39 | left = mid + 1; 40 | } 41 | } 42 | return left; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/basic/rev_binary_search.cpp: -------------------------------------------------------------------------------- 1 | // Given a reverse sorted array, apply binary search 2 | // int arr[] = {40, 28, 10, 5, 1} 3 | // x = 10; 4 | 5 | // Print element is found. 6 | 7 | #include 8 | using namespace std; 9 | 10 | int bsearch_rev(int arr[], int n, int tgt) { 11 | int left = 0; 12 | int right = n - 1; 13 | while (left <= right) { 14 | // int mid = (left + right) / 2; 15 | int mid = left + (right - left) / 2; 16 | 17 | if (arr[mid] == tgt) { 18 | return mid; 19 | } else if (tgt < arr[mid]) { 20 | left = mid + 1; 21 | } else if (tgt > arr[mid]) { 22 | right = mid - 1; 23 | } 24 | } 25 | return -1; 26 | } 27 | 28 | int main(int argc, char const *argv[]) { 29 | int arr[] = {40, 28, 10, 5, 1}; 30 | int tgt = 10; 31 | int n = sizeof(arr) / sizeof(arr[0]); 32 | int res = bsearch_rev(arr, n, tgt); 33 | if (res) { 34 | cout << "Element is found" << endl; 35 | } else { 36 | cout << "Element is not found" << endl; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/basic/sqrt.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/ 2 | 3 | // Given a non-negative integer x, return the square root of x rounded down to 4 | // the nearest integer. The returned integer should be non-negative as well. 5 | 6 | // You must not use any built-in exponent function or operator. 7 | 8 | // For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. 9 | 10 | // Example 1: 11 | 12 | // Input: x = 4 13 | // Output: 2 14 | // Explanation: The square root of 4 is 2, so we return 2. 15 | 16 | // Example 2: 17 | 18 | // Input: x = 8 19 | // Output: 2 20 | // Explanation: The square root of 8 is 2.82842..., and since we round it down 21 | // to the nearest integer, 2 is returned. 22 | 23 | int mySqrt(int x) { 24 | int left = 0; 25 | int right = x; 26 | int ans = -1; 27 | 28 | while (left <= right) { 29 | int mid = left + (right - left) / 2; 30 | 31 | if ((long long)mid * mid <= x) { 32 | // one of the answers, can do better still 33 | ans = mid; 34 | left = mid + 1; 35 | } 36 | 37 | else { 38 | right = mid - 1; 39 | } 40 | } 41 | 42 | return ans; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/medium/median_mat.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/matrix-median/ 2 | 3 | // Given a matrix of integers A of size N x M in which each row is sorted. 4 | 5 | // Find an return the overall median of the matrix A. 6 | 7 | // Note: No extra memory is allowed. 8 | 9 | // Input 1: 10 | // A = [ [1, 3, 5], 11 | // [2, 6, 9], 12 | // [3, 6, 9] ] 13 | // Output 1: 14 | // 5 15 | // Explanation 1: 16 | // A = [1, 2, 3, 3, 5, 6, 6, 9, 9] 17 | // Median is 5. So, we return 5. 18 | 19 | // Input 2: 20 | // A = [ [5, 17, 100] ] 21 | // Output 2: 22 | // 17 23 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/medium/next_alpha_element.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of letters sorted in ascending order, 2 | // find the smallest letter in the the array which is greater than a given key 3 | // letter. Example arr: {'a', 'b', 'c', 'd', 'g'} tgt : 'f' Ans = 'g'; 4 | 5 | #include 6 | using namespace std; 7 | 8 | char find_next_letter(char letters[], int n, char tgt) { 9 | int left = 0; 10 | int right = n - 1; 11 | char ans = '#'; 12 | 13 | while (left <= right) { 14 | int mid = (left + right) / 2; 15 | int val = letters[mid] - 'a'; 16 | if ((tgt - 'a') < val) { 17 | ans = letters[mid]; 18 | right = mid - 1; 19 | } else if ((tgt - 'a') > val) { 20 | left = mid + 1; 21 | } 22 | } 23 | return ans; 24 | } 25 | 26 | int main(int argc, char const *argv[]) { 27 | char letters[] = {'a', 'b', 'c', 'd', 'g'}; 28 | char tgt = 'f'; 29 | 30 | int n = sizeof(letters) / sizeof(letters[0]); 31 | 32 | cout << find_next_letter(letters, n, tgt) << endl; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/medium/number_of_matching_subseq.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-matching-subsequences/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/medium/peak_element2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ 2 | // Example 1: 3 | 4 | // Input: arr = [0,1,0] 5 | // Output: 1 6 | 7 | // Example 2: 8 | 9 | // Input: arr = [0,2,1,0] 10 | // Output: 1 11 | 12 | // Example 3: 13 | 14 | // Input: arr = [0,10,5,2] 15 | // Output: 1 16 | 17 | // Input: arr = [0,5,7,10,3,2,1] 18 | // Output: 3 19 | 20 | // Input: arr = [0,5,7,10,11,12,3,2,1] 21 | // Output: 5 22 | 23 | // For a increasing and then decreasing array, find the maximum element 24 | 25 | // CONTRAINT ARRAY SIZE > 3 26 | 27 | #include 28 | 29 | using namespace std; 30 | 31 | int peakIndexInMountainArray(vector& arr) { 32 | int n = arr.size(), left = 0, right = n - 1; 33 | 34 | while (left <= right) { 35 | int mid = left + (right - left) / 2; 36 | 37 | if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { 38 | return mid; 39 | } 40 | 41 | else if (arr[mid] > arr[mid - 1]) { 42 | left = mid + 1; 43 | } 44 | 45 | else if (arr[mid] < arr[mid - 1]) { 46 | right = mid - 1; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search/readme.txt: -------------------------------------------------------------------------------- 1 | Do not refer any templates from leetcode etc. 2 | 3 | Only refer errichto's implementation and ideas. 4 | The trick is simple, keep using same pattern. 5 | Reduce the search space correctly. 6 | 7 | https://www.youtube.com/watch?v=GU7DpgHINWQ&list=PLl0KD3g-oDOHpWRyyGBUJ9jmul0lUOD80&index=4&t=654s 8 | 9 | Do not follow different ideas where left = 1 or left +- 1 etc. stick with this. 10 | 11 | This can solve 99% of the problems, never deviate even in interview. 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/all_pair_xor_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | int arr[100]; 5 | int res = 0, n; 6 | cin >> n; 7 | for (int i = 0; i < n; i++) { 8 | cin >> arr[i]; 9 | } 10 | // For every signed 32 bit 11 | for (int i = 0; i < 31; i++) { 12 | int cntz = 0, cnto = 0; 13 | for (int j = 0; j < n; j++) { 14 | if (arr[j] & (1 << i)) { 15 | // if ith bit is one 16 | cnto += 1; 17 | } else { 18 | // if ith bit is zero 19 | cntz += 1; 20 | } 21 | } 22 | int pairs = cntz * cnto; 23 | res += (1 << i) * pairs; 24 | } 25 | cout << res; 26 | return (0); 27 | } -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/checking_bit_1.txt: -------------------------------------------------------------------------------- 1 | Given a number N and index i. Find whether ith bit in binary representation of N is 1. 2 | 3 | Example N = 12 = 1100 4 | i = 0 ans = False 5 | i = 3 ans = True 6 | 7 | --------------------------------------------------------------------------- 8 | 9 | Solution : 10 | We need to just take Bitwise AND 11 | 12 | int F = 1 13 | F << i (to check the ith bit left shift it) 14 | if F AND i == 1 15 | then bit is 1 16 | else: 17 | bit is 0. 18 | 19 | -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/hamming_distance.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/hamming-distance/ 2 | // Hamming Distance 3 | 4 | // The Hamming distance between two integers is the number of positions at which 5 | // the corresponding bits are different. 6 | 7 | // Given two integers x and y, return the Hamming distance between them. 8 | 9 | // Input: x = 1, y = 4 10 | // Output: 2 11 | // Explanation: 12 | // 1 (0 0 0 1) 13 | // 4 (0 1 0 0) 14 | // ↑ ↑ 15 | // The above arrows point to positions where the corresponding bits are 16 | // different. 17 | 18 | // Example 2: 19 | 20 | // Input: x = 3, y = 1 21 | // Output: 1 22 | 23 | // Solution: - 24 | // The basic idea here is to discuss the usage of xor operator (^) ,and 25 | // operator(&) and right shift operator(>>).When we take xor of two numbers the 26 | // bits with same numbers become zero and with different numbers become 1. Then 27 | // we can right shift all the 1's and use & to find the number of ones . 28 | 29 | int hammingDistance(int x, int y) { 30 | int z = x ^ y; 31 | int count = 0; 32 | while (z) { 33 | if (z & 1) { 34 | count += 1; 35 | } 36 | z = z >> 1; 37 | } 38 | 39 | return count; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/power_of_two_op.cpp: -------------------------------------------------------------------------------- 1 | 2 | bool isPowerOfTwo(int n) { 3 | if (n <= 0) { 4 | return false; 5 | } else if ((n & (n - 1)) == 0) { 6 | return true; 7 | } else { 8 | return false; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/power_of_two_unop.cpp: -------------------------------------------------------------------------------- 1 | bool isPowerOfTwo(int n) { 2 | int count = 0; 3 | 4 | while (n > 0) { 5 | count += 1; 6 | n = n & (n - 1); 7 | } 8 | 9 | if (count == 1) { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/single_number_3.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers, every element appears three times except 2 | // for one, which appears exactly once. Find that single one. 3 | 4 | // Input: [2,2,3,2] 5 | // Output: 3 6 | 7 | // https://leetcode.com/problems/single-number/solutions/1772139/c-explained-everything-w-why-xor-works-brute-force-to-optimized-step-by-step-dry-run/?envType=list&envId=503dr9s5 8 | 9 | #include 10 | using namespace std; 11 | 12 | class Solution { 13 | public: 14 | int singleNumber(vector& nums) { 15 | int n = nums.size(); 16 | 17 | for (int i = 0; i < n - 1; i++) { 18 | nums[i + 1] = nums[i] ^ nums[i + 1]; 19 | } 20 | 21 | return nums[n - 1]; 22 | } 23 | }; -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/subset_bitmask.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | char arr[] = {'A', 'B', 'C', 'D'}; 6 | int t, n; 7 | cin >> t; 8 | while (t--) { 9 | cin >> n; // No of elements in the set 10 | int tot = 1 << n; // Total number of subsets = 2^n 11 | for (int mask = 0; mask < tot; mask++) // Totally 2^N elements to check 12 | { 13 | for (int i = 0; i < n; 14 | i++) // For every number n. Check which bit is set to 1. 15 | { 16 | int f = 1 << i; 17 | if ((mask & f) != 0) // Do not forget the bracket 18 | { 19 | // print i th element; 20 | cout << arr[i] << " "; 21 | } 22 | } 23 | cout << endl; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/subset_sum_bitmask.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | int n, arr[15], p, t; 5 | cin >> t; 6 | while (t--) { 7 | cin >> n; 8 | for (int i = 0; i < n; i++) { 9 | cin >> arr[i]; 10 | } 11 | cin >> p; // Number to who the subset sum will be equated 12 | 13 | bool flag = false; 14 | // Generate all the possible subarrays 15 | 16 | int total = 1 << n; 17 | for (int mask = 0; mask < total; mask++) { 18 | int sum = 0; 19 | for (int i = 0; i < n; i++) // Checks if ith element exists or not 20 | { 21 | int f = 1 << i; // To check if ith bit is 1. 22 | if ((mask & f) != 0) { 23 | // ith elemenet exists 24 | // Add the ith element in the sum 25 | sum += arr[i]; 26 | } 27 | } 28 | if (sum == p) { 29 | // There is single subarray that is true 30 | flag = true; 31 | break; 32 | } 33 | } 34 | if (flag == true) { 35 | cout << "YES" << endl; 36 | } else { 37 | cout << "NO" << endl; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Bit_manipulation/xor_properties.txt: -------------------------------------------------------------------------------- 1 | XOR and its properties: - 2 | 3 | A = 011101110 4 | B = 010101001 5 | XOR 001000111 6 | 7 | if both the bits are same result = 0 8 | else result = 1 9 | 10 | A XOR B = A ^ B 11 | 12 | Properties of XOR: - 13 | 14 | 1. A ^ 0 = A 15 | 2. A ^ A = 0 16 | 3. Ordering of XOR does not matter. 17 | 18 | A ^ B ^ C = (A ^ B) ^ C = A ^ (B ^ C) 19 | 20 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/1d_dp/min_cost_climbing_stairs.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/min-cost-climbing-stairs 2 | 3 | // You are given an integer array cost where cost[i] is the cost of ith step on 4 | // a staircase. Once you pay the cost, you can either climb one or two steps. 5 | 6 | // You can either start from the step with index 0, or the step with index 1. 7 | 8 | // Return the minimum cost to reach the top of the floor. 9 | 10 | // Example 1: 11 | 12 | // Input: cost = [10,15,20] 13 | // Output: 15 14 | // Explanation: You will start at index 1. 15 | // - Pay 15 and climb two steps to reach the top. 16 | // The total cost is 15. 17 | 18 | #include 19 | using namespace std; 20 | 21 | int minCostClimbingStairs(vector &cost) { 22 | int n = cost.size(); 23 | vector dp(n, 0); 24 | 25 | dp[0] = cost[0]; 26 | dp[1] = cost[1]; 27 | 28 | for (int i = 2; i < n; i++) { 29 | // cout<= 0. 5 | 6 | // Given n, return the value of Tn. 7 | 8 | // Input: n = 4 9 | // Output: 4 10 | // Explanation: 11 | // T_3 = 0 + 1 + 1 = 2 12 | // T_4 = 1 + 1 + 2 = 4 13 | 14 | // Input: n = 25 15 | // Output: 1389537 16 | 17 | #include 18 | using namespace std; 19 | 20 | int tribonacci(int n) { 21 | if (n == 0) { 22 | return 0; 23 | } 24 | 25 | vector res(n + 2, 0); 26 | res[0] = 0; 27 | res[1] = 1; 28 | res[2] = 1; 29 | 30 | for (int i = 3; i <= n; i++) { 31 | res[i] = res[i - 1] + res[i - 2] + res[i - 3]; 32 | } 33 | 34 | return res[n]; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LCS_pattern/min_del_pal_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Given a string of size ‘n’. 5 | // The task is to remove or delete the minimum number of characters from the 6 | // string so that the resultant string is a palindrome. 7 | 8 | // Input : aebcbda 9 | // Output : 2 10 | // Remove characters 'e' and 'd' 11 | // Resultant string will be 'abcba' 12 | // which is a palindromic string 13 | 14 | // Input : geeksforgeeks 15 | // Output : 8 16 | 17 | // Solution: - 18 | // Find length of longest palindormic subsequence. 19 | // The remaining characters have to be deleted to make the resultant string to a 20 | // palindrome. minimum number of deletions = n - len of longest palindromic 21 | // substring. 22 | // Same as minimum number of insertions needed 23 | 24 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LCS_pattern/readme.txt: -------------------------------------------------------------------------------- 1 | LCS Pattern 2 | 3 | Focus on Bottom Up solution, it is not that hard 4 | 5 | Order of practice 6 | 7 | 1. LCS 8 | 2. Delete operation for 2 strings 9 | 3. Longest Repeating Subsequence 10 | 4. LPS 11 | 5. Minimum insertion to make palindrome subseq 12 | 6. Shortest common supersequence 13 | 7. Uncrossed Lines 14 | 8. Wildcard Matching 15 | 9. Edit Distance 16 | 10. Distinct Subsequences 17 | 11. Longest Common Substring 18 | 12. 19 | 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LCS_pattern/wildcard_matching.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/wildcard-matching/ 2 | 3 | // Given an input string (s) and a pattern (p), implement wildcard pattern 4 | // matching with support for '?' and '*' where: 5 | 6 | // '?' Matches any single character. 7 | // '*' Matches any sequence of characters (including the empty sequence). 8 | 9 | // The matching should cover the entire input string (not partial). 10 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LIS_pattern/delete_earn.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-and-earn/ 2 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LIS_pattern/max_length_pair_chain.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-length-of-pair-chain/ 2 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LIS_pattern/maximum_height_stacking_cubiods.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-height-by-stacking-cuboids/description/ 2 | 3 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/LIS_pattern/readme.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/discuss/post/1068411/guide-to-dynamic-programming-pattern-lon-zray/ 2 | https://astikanand.github.io/techblogs/dynamic-programming-patterns/longest-increasing-subsequence-pattern 3 | 4 | 5 | Follow the guide for pattern 6 | 7 | Order of solving 8 | 1. LIS 9 | 2. Min deletions to make array sorted 10 | 3. Max sum Increasing subsequence 11 | 4. LDS (Longest Decreasing subsequence) 12 | 5. Longest Bitonic subsequence 13 | 6. Number of LIS 14 | 7. Best Team 15 | 8. Delete Earn 16 | 9. Longest String Chain 17 | 10. Longest Divisible Subset 18 | 11. Russian Doll Envelopes 19 | 12. Maximum Height Stacking Cuboids 20 | 21 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/MCM_pattern/egg_dropping.cpp: -------------------------------------------------------------------------------- 1 | // Problem statement: 2 | // You are given N floor and K eggs. 3 | // You have to minimize the number of times you have to drop the eggs 4 | // to find the critical floor where critical floor means the floor 5 | // beyond which eggs start to break. 6 | 7 | // Assumptions of the problem: 8 | 9 | // If egg breaks at ith floor then it also breaks at all greater floors. 10 | // If egg does not break at ith floor then it does not break at all lower 11 | // floors. Unbroken egg can be used again. 12 | 13 | // Note: You have to find minimum trials required to find the critical floor not 14 | // the critical floor. 15 | 16 | // Input: 17 | // 4 18 | // 2 19 | 20 | // Output: 21 | // Number of trials when number of eggs is 2 and number of floors is 4: 3 22 | 23 | // Input: 24 | // 36 25 | // 2 26 | 27 | // Output: 28 | // Number of trials when number of eggs is 2 and number of floors is 36: 8 29 | #include 30 | 31 | using namespace std; 32 | 33 | int main() { cout return (0); } 34 | -------------------------------------------------------------------------------- /Algorithms/Dynamic_Programming/README.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/discuss/study-guide/1437879/dynamic-programming-patterns 2 | -------------------------------------------------------------------------------- /Algorithms/Greedy/advantage_shuffle.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/advantage-shuffle/description/ 2 | // You are given two integer arrays nums1 and nums2 both of the same length. The 3 | // advantage of nums1 with respect to nums2 is the number of indices i for which 4 | // nums1[i] > nums2[i]. 5 | 6 | // Return any permutation of nums1 that maximizes its advantage with respect to 7 | // nums2. 8 | 9 | // Example 1: 10 | 11 | // Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11] 12 | // Output: [2,11,7,15] 13 | 14 | // Solution: - 15 | 16 | // Use Greedy Approach. 17 | // Sort nums1, always find upper bound for every element in 18 | // nums2. If it exists, that is result, otherwise the 19 | // smallest number is result. 20 | 21 | // To sort and find upper bound, use multiset. 22 | 23 | #include 24 | 25 | using namespace std; 26 | 27 | vector advantageCount(vector& nums1, vector& nums2) { 28 | multiset st(begin(nums1), end(nums1)); 29 | 30 | vector res; 31 | 32 | for (auto num : nums2) { 33 | auto p = st.upper_bound(num); 34 | if (p == st.end()) { 35 | p = st.begin(); 36 | } 37 | res.push_back(*p); 38 | st.erase(p); 39 | } 40 | return res; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Greedy/candy.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/candy/ 2 | -------------------------------------------------------------------------------- /Algorithms/Greedy/min_swaps_strings.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/ 2 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/Binomial_Coefficient_Inverse_Modulo.txt: -------------------------------------------------------------------------------- 1 | Calculating Binomial Coefficient using Modulo inverse 2 | 3 | Given q queries of type N, K calculate C(N, K) % P where P > N 4 | C is Combinatorial Coefficient 5 | 6 | If P < N we would have to use Lucas theorom. 7 | Otherwise this method works. 8 | 9 | C(N, K) = (N ! / K ! * (N - K) !) 10 | 11 | Under Modulo P conditions 12 | 13 | C(N, K) = (N ! % P) / ( (K ! % P) * ((N - K)!) % P) 14 | 15 | We will pre calculate N! % P. For 10 ** 6. 16 | 17 | C ++ Code: - 18 | 19 | int F[1000001]; 20 | 21 | int main() 22 | { 23 | F[0] = F[1] = 1; 24 | for(int i=2; i<=1000000; i++) 25 | { 26 | // F[i] = (F[i-1] * i) % P; 27 | Note that the above expression might go out of integer range so we type cast. 28 | F[i] = (F[i-1] * 1LL * i) % P; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/Euler_Totient_Function_Part2.txt: -------------------------------------------------------------------------------- 1 | Euler Totient Function counts the number of positive integers upto n which are coprime to n. 2 | It is denoted by Phi(n) 3 | 4 | 5 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/Finding_modulo_multiplicate_inverse.txt: -------------------------------------------------------------------------------- 1 | 2 Ways to calculate modulo multiplicative inverse 2 | 3 | 1. Fermat's little theorm 4 | 2. Exteneded Euclidean Algorithm 5 | 6 | Running time of both of them is same. 7 | 8 | Fermat's little theorm: - 9 | 10 | For a prime number m and an integer a coprime with m. 11 | 12 | a ^ (m - 1) is congruent to 1 under modulo m 13 | 14 | a ^ (m - 1) == 1 under modulo m 15 | 16 | Divide both sides by a we get. 17 | 18 | a ^ (m - 2) == a ^ (-1) under modulo m. 19 | 20 | So this means that to calculate a inverse we need to calculate a ^ (m - 2) modulo m. 21 | 22 | This is how we can calculate modulo multiplicative inverse. 23 | 24 | To calculate modulo multiplicative inverse of 'a' we need to calculate a ^ (m - 2) modulo m. 25 | 26 | C ++ code to calculate modulo multiplicative inverse of a. 27 | 28 | int main() 29 | { 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/div_from_prime_factors.txt: -------------------------------------------------------------------------------- 1 | Find total number of divisors from prime factorization of number N. 2 | N = 300 3 | N = 2 ^ 2 * 3 ^ 1 * 5 ^ 2 4 | 5 | Total divisors = 18 6 | 7 | Given a number's prime factorization, find total number of divisors and print its modulo 10^9 + 7 8 | 9 | Example 10 | 3 11 | 2 1000 12 | 3 1500 13 | 13 1000000 14 | 15 | Number = 2 ^ 1000 * 3 ^ 1500 * 13 ^ 1000000 16 | 17 | Number is too big to find O(sqrt(n)) time approach. 18 | Number is too big for long long int data structure as well. 19 | 20 | Assume 21 | N = P1 ^ Y1 * P2 ^ Y2 * P3 ^ Y3 * P4 ^ Y4 * ... * Pn ^ Yn 22 | 23 | All Pi are prime numbers and Yi are there respective powers. 24 | 25 | Total number of divisors : - 26 | 27 | => (y1 + 1) * (y2 + 1) * (y3 + 1) ....... * (yn + 1) 28 | 29 | If there are k number of primes then we can calculate in O(k) time this product. 30 | 31 | Example: - 32 | 33 | N = 300 34 | N = 2 ^ 2 * 3 ^ 1 * 5 ^ 2 35 | 36 | Total number of divisors : - 37 | = (2 + 1) * (1 + 1) * (2 + 1) 38 | = 9 * 2 = 18 39 | 40 | Why this approach works ? 41 | 42 | Think divisors as boxes and combine these factors to find the number of divisors. 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/divisor_from_prime_factors.txt: -------------------------------------------------------------------------------- 1 | Find the total number of divisors from prime factorization of number N. 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/fermat's_mod_mul_inv.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int power(int a, int n, int m) { 5 | // Bianry exponentiation to get the power and modulo 6 | int result = 1; 7 | while (n > 0) { 8 | if (n % 2 == 0) { 9 | // n is even 10 | a = (a * a) % m; 11 | n /= 2; 12 | } else { 13 | // n is odd. 14 | result = (result * a) % m; 15 | n -= 1; 16 | } 17 | } 18 | return result; 19 | } 20 | 21 | int main() { 22 | // Time complexity = O(log(m)) 23 | int a, b, m; 24 | cin >> a >> m; 25 | cout << endl << "a^-1 = " << power(a, m - 2, m); 26 | return (0); 27 | } -------------------------------------------------------------------------------- /Algorithms/Number_Theory/matrices.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int m = 3; 6 | int n = 4; 7 | 8 | return (0); 9 | } 10 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/modulo_arithmetic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | 6 | Modulo Arithmetic introduction 7 | 8 | (N1 + N2) % mod = (N1 % mod + N2 % mod) % mod 9 | 10 | (N1 * N2) % mod = ((N1 % mod) * (N2 % mod)) % mod 11 | 12 | Euclid Division Algorithm 13 | 14 | GCD(a, b) = a if b == 0 15 | = GCD(b, a mod b) otherwise 16 | 17 | Note the following 18 | GCD(a, b) = GCD(b, a) 19 | 20 | GCD(A, 0) = GCD(0, A) 21 | 22 | GCD(A, B) = GCD(A-B, B) = GCD(A, B-A) 23 | 24 | GCD(A, B) = GCD(A+B, B) = GCD(A, B+A) 25 | 26 | */ 27 | 28 | int gcd(int a, int b) { 29 | // Complexity = log(max(a, b)) 30 | 31 | if (b == 0) { 32 | return a; 33 | } else { 34 | return (gcd(b, a % b)); 35 | } 36 | } 37 | 38 | int main() { 39 | int a, b, gc; 40 | cin >> a >> b; 41 | gc = gcd(a, b); 42 | cout << "GCD = " << gc << endl; 43 | return (0); 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/primality_sqrt(n).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPrime(int n) { 5 | if (n == 1) { 6 | return false; 7 | } else { 8 | for (int i = 2; i * i <= n; i++) { 9 | if (n % i == 0) { 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | } 16 | 17 | int main() { 18 | int t, n; 19 | cin >> t; 20 | while (t > 0) { 21 | cin >> n; 22 | if (isPrime(n)) { 23 | cout << "yes" << endl; 24 | } else { 25 | cout << "no" << endl; 26 | } 27 | t -= 1; 28 | } 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/primality_sqrt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPrime(int n) { 5 | if (n == 1) { 6 | return false; 7 | } else { 8 | for (int i = 2; i * i <= n; i++) { 9 | if (n % i == 0) { 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | } 16 | 17 | int main() { 18 | int t, n; 19 | cin >> t; 20 | while (t > 0) { 21 | cin >> n; 22 | if (isPrime(n)) { 23 | cout << "yes" << endl; 24 | } else { 25 | cout << "no" << endl; 26 | } 27 | t -= 1; 28 | } 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/prime_factors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void prime_factors_brute(int n) { 5 | // Time complexity = O(N) Even if it does not look by the code it is. 6 | for (int i = 2; i <= n; i++) { 7 | if (n % i == 0) // If i is a factor then 8 | { 9 | int cnt = 0; // Finding how many times it can divide it 10 | while (n % i == 0) { 11 | n /= i; 12 | cnt += 1; 13 | } 14 | cout << i << " ^ " << cnt << endl; 15 | } 16 | } 17 | } 18 | 19 | void prime_factors_opt(int n) { 20 | // If n is a composite number then there is at least 1 prime divisor of N 21 | // below sqrt(N) 22 | 23 | for (int i = 2; i * i <= n; i++) { 24 | if (n % i == 0) { 25 | int cnt = 0; 26 | while (n % i == 0) { 27 | cnt += 1; 28 | n /= i; 29 | } 30 | cout << i << " ^ " << cnt << endl; 31 | } 32 | } 33 | if (n > 1) { 34 | cout << n << " ^ 1 " << endl; 35 | } 36 | } 37 | 38 | int main() { 39 | int n; 40 | cin >> n; 41 | 42 | // prime_factors_brute(n); 43 | prime_factors_opt(n); 44 | 45 | return (0); 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Number_Theory/sieve_of_eratotheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print_arr(int arr[], int n) { 5 | for (int i = 0; i < n; i++) 6 | if (arr[i] == 1) { 7 | cout << i << " "; 8 | } 9 | } 10 | 11 | void sieve(int arr[], int n) { 12 | for (int i = 0; i < n; i++) { 13 | // Assigning that entire array is filled up with primes 14 | arr[i] = 1; 15 | } 16 | // We know this 17 | arr[0] = 0; 18 | arr[1] = 0; 19 | 20 | // Applying sieve which whil pick every number below sqrt(n) and find its 21 | // factors Then mark it's factors which are composite 22 | 23 | for (int i = 2; i * i <= n; i++) { 24 | if (arr[i] == 1) // If it is a composite number then mark all its factors 25 | // as composite 26 | { 27 | for (int j = i * i; j <= n; j += i) { 28 | arr[j] = 0; 29 | } 30 | } 31 | } 32 | 33 | print_arr(arr, n); 34 | } 35 | 36 | int main() { 37 | int arr[101]; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | sieve(arr, n); 40 | return (0); 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Prefix_Sum/2d_sums/prefix_sum_matrix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Algorithms/Prefix_Sum/2d_sums/prefix_sum_matrix.png -------------------------------------------------------------------------------- /Algorithms/Prefix_Sum/2d_sums/range_sum_queries_2d.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-sum-query-2d-immutable/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Prefix_Sum/hard/car_pooling.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/car-pooling/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Prefix_Sum/medium/character_occur_max_times.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/queries-to-print-the-character-that-occurs-the-maximum-number-of-times-in-a-given-range/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Function that answers all the queries 8 | void solveQueries(string str, vector> &query) {} 9 | -------------------------------------------------------------------------------- /Algorithms/Randomized/notes.txt: -------------------------------------------------------------------------------- 1 | How to solve randomized Algorithms ? 2 | 3 | Watch errichto's lecture 4 | 5 | https://www.youtube.com/watch?v=0r2D32esF3Y&list=PLl0KD3g-oDOHpWRyyGBUJ9jmul0lUOD80&index=9&pp=iAQB 6 | 7 | 8 | https://www.youtube.com/watch?v=0r2D32esF3Y&list=PLl0KD3g-oDOHpWRyyGBUJ9jmul0lUOD80&index=9&pp=iAQB 9 | 10 | https://codeforces.com/blog/entry/71097 11 | https://codeforces.com/blog/entry/61587 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Algorithms/Recursion/delete_mid_stack.cpp: -------------------------------------------------------------------------------- 1 | // Delete middle element of stack using Recursion 2 | 3 | #include 4 | using namespace std; 5 | 6 | void delete_mid(stack &s, int n, int curr = 0) { 7 | // if stack is empty or all items are traversed. 8 | if (s.empty() || curr == n) { 9 | return; 10 | } 11 | 12 | // Remove current item 13 | int temp = s.top(); 14 | s.pop(); 15 | 16 | // remove other items 17 | delete_mid(s, n, curr + 1); 18 | 19 | // Put all items back except middle 20 | if (curr != (n / 2)) { 21 | s.push(temp); 22 | } 23 | } 24 | 25 | void print_st(stack s) { 26 | while (!s.empty()) { 27 | cout << s.top() << " "; 28 | s.pop(); 29 | } 30 | cout << endl; 31 | } 32 | 33 | int main(int argc, char const *argv[]) { 34 | stack s; 35 | s.push(1); 36 | s.push(2); 37 | s.push(3); 38 | s.push(4); 39 | s.push(5); 40 | s.push(6); 41 | s.push(7); 42 | 43 | cout << "Stack before deleting: "; 44 | print_st(s); 45 | 46 | delete_mid(s, s.size()); 47 | 48 | cout << "Stack after deleting mid "; 49 | print_st(s); 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Algorithms/Recursion/factorial.cpp: -------------------------------------------------------------------------------- 1 | // Find factorial of number using recursion 2 | 3 | #include 4 | using namespace std; 5 | 6 | int fact_rec(int n) { 7 | if (n == 1) { 8 | return 1; 9 | } else { 10 | return (n * fact_rec(n - 1)); 11 | } 12 | } 13 | 14 | int fact_itr(int n) { 15 | int res = 1; 16 | for (int i = 1; i <= n; i++) { 17 | res *= i; 18 | } 19 | return res; 20 | } 21 | 22 | int main(int argc, char const *argv[]) { 23 | int n = 4; 24 | auto res = fact_rec(n); 25 | auto res2 = fact_itr(n); 26 | cout << res << endl; 27 | cout << res2 << endl; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Recursion/generate_balanced_paran.cpp: -------------------------------------------------------------------------------- 1 | // Given n pairs of parentheses, write a function 2 | // to generate all combinations of well-formed parentheses of length 2*n. 3 | // For example, given n = 3, a solution set is: 4 | 5 | // "((()))", "(()())", "(())()", "()(())", "()()()" 6 | 7 | #include 8 | using namespace std; 9 | 10 | vector res; 11 | 12 | void print_v(vector v) { 13 | for (auto x : v) { 14 | cout << x << " "; 15 | } 16 | cout << endl; 17 | } 18 | 19 | void solve(int open, int close, string op) { 20 | if (open == 0 && close == 0) { 21 | // cout< open) { 30 | op += ")"; 31 | solve(open, close - 1, op); 32 | } 33 | return; 34 | } 35 | 36 | void generate_paran(int n) { 37 | int close = n; 38 | int open = n; 39 | string op = ""; 40 | solve(open, close, op); 41 | } 42 | 43 | int main(int argc, char const *argv[]) { 44 | int n = 3; 45 | generate_paran(n); 46 | print_v(res); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/Recursion/permutation_letter_change.cpp: -------------------------------------------------------------------------------- 1 | // Print all possible strings that can be made by placing spaces 2 | 3 | // Given a string you need to print all possible strings 4 | // that can be made by placing spaces (zero or one) in 5 | // between them. Output should be printed in sorted increasing order of strings. 6 | 7 | // Input: str[] = "ABC" 8 | // Output: (A B C)(A BC)(AB C)(ABC) 9 | 10 | #include 11 | using namespace std; 12 | 13 | void solve(string inp, string op) { 14 | if (inp.length() == 0) { 15 | cout << op << " "; 16 | return; 17 | } 18 | string op1 = op; 19 | string op2 = op; 20 | 21 | op1 += "_"; 22 | op1 += inp[0]; 23 | op2 += inp[0]; 24 | inp.erase(inp.begin() + 0); 25 | 26 | solve(inp, op1); 27 | solve(inp, op2); 28 | return; 29 | } 30 | 31 | void perm_letter(string str) { 32 | string inp = str; 33 | string op = ""; 34 | 35 | op += inp[0]; 36 | inp.erase(inp.begin() + 0); 37 | 38 | // cout< 4 | using namespace std; 5 | 6 | void print_to_n(int n) { 7 | if (n == 1) { 8 | cout << n << " "; 9 | return; 10 | } 11 | print_to_n(n - 1); 12 | cout << n << " "; 13 | } 14 | 15 | void print_n_to(int n) { 16 | if (n == 1) { 17 | cout << n << " "; 18 | return; 19 | } 20 | cout << n << " "; 21 | print_n_to(n - 1); 22 | } 23 | 24 | int main(int argc, char const *argv[]) { 25 | int n = 4; 26 | print_to_n(n); 27 | cout << endl; 28 | print_n_to(n); 29 | cout << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Recursion/subset_sums.cpp: -------------------------------------------------------------------------------- 1 | // Given a list(Arr) of N integers, print sums of all subsets in it. 2 | // Output should be printed in increasing order of sums. 3 | 4 | // Input: 5 | // N = 2 6 | // Arr = [2, 3] 7 | // Output: 8 | // 0 2 3 5 9 | // Explanation: 10 | // When no elements is taken then Sum = 0. 11 | // When only 2 is taken then Sum = 2. 12 | // When only 3 is taken then Sum = 3. 13 | // When element 2 and 3 are taken then 14 | // Sum = 2+3 = 5. 15 | 16 | // Input: 17 | // N = 3 18 | // Arr = [5, 2, 1] 19 | // Output: 20 | // 0 1 2 3 5 6 7 8 21 | -------------------------------------------------------------------------------- /Algorithms/Recursion/tower_of_hanoi.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | void towerOfHanoi(int n, string start_rod, string dest_rod, string help_rod) { 7 | if (n == 1) { 8 | // We have only 1 rod. 9 | cout << "Move 1 from " << start_rod << " to rod " << dest_rod << endl; 10 | return; 11 | } 12 | 13 | towerOfHanoi(n - 1, start_rod, help_rod, dest_rod); 14 | cout << "Move disk " << n << " from rod " << start_rod << " to rod " 15 | << dest_rod << endl; 16 | 17 | towerOfHanoi(n - 1, help_rod, dest_rod, start_rod); 18 | } 19 | 20 | int main(int argc, char const *argv[]) { 21 | int n = 4; 22 | string help_rod = "H"; 23 | string dest_rod = "D"; 24 | string start_rod = "S"; 25 | 26 | towerOfHanoi(n, "S", "D", "H"); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/Sliding_Window/fixed_size/hard/subarray_k_different.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarrays-with-k-different-integers/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Sliding_Window/fixed_size/hard/substring_concat_words.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/ 2 | -------------------------------------------------------------------------------- /Algorithms/Sliding_Window/var_size/medium/longest_k_atleast_substr.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ -------------------------------------------------------------------------------- /Algorithms/Sliding_Window/var_size/medium/subarr_k_distinct.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarrays-with-k-different-integers/description/ 2 | 3 | // Given an integer array nums and an integer k, return the number of good 4 | // subarrays of nums. 5 | 6 | // A good array is an array where the number of different integers in that array 7 | // is exactly k. 8 | 9 | // For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. 10 | 11 | // A subarray is a contiguous part of an array. 12 | 13 | // Example 1: 14 | 15 | // Input: nums = [1,2,1,2,3], k = 2 16 | // Output: 7 17 | // Explanation: Subarrays formed with exactly 2 different integers: [1,2], 18 | // [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] 19 | 20 | // Example 2: 21 | 22 | // Input: nums = [1,2,1,3,4], k = 3 23 | // Output: 3 24 | // Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], 25 | // [2,1,3], [1,3,4]. 26 | -------------------------------------------------------------------------------- /Algorithms/Sliding_Window/var_size/medium/substring_k_chars.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/description/ 2 | // todo 3 | -------------------------------------------------------------------------------- /Algorithms/Sliding_Window/var_size/more_problems.cpp: -------------------------------------------------------------------------------- 1 | 2 | // https://leetcode.com/problems/subarrays-with-k-different-integers/ 3 | // https://leetcode.com/problems/count-number-of-nice-subarrays/ 4 | // https://binarysearch.com/problems/Number-of-Sublists-With-Sum-of-Target 5 | -------------------------------------------------------------------------------- /Algorithms/Sorting/array_partition.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums of 2n integers, group these integers into n pairs 2 | // (a1, b1), (a2, b2), ..., (an, bn) 3 | // such that the sum of min(ai, bi) for all i is maximized. 4 | // Return the maximized sum. 5 | 6 | // https://leetcode.com/problems/array-partition-i/ 7 | 8 | // Example 1: 9 | 10 | // Input: arr = [1,2,2,1,1,3] 11 | // Output: true 12 | // Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two 13 | // values have the same number of occurrences. 14 | 15 | // Example 2: 16 | 17 | // Input: arr = [1,2] 18 | // Output: false 19 | 20 | // Example 3: 21 | 22 | // Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 23 | // Output: true 24 | 25 | // Solution: - 26 | // Sort the array. 27 | // Elements are now paired. Add all the even indices. 28 | // That gives the sum_diff. 29 | 30 | #include 31 | using namespace std; 32 | 33 | int arrayPairSum(vector &nums) { 34 | sort(nums.begin(), nums.end()); 35 | 36 | int sum_diff = 0; 37 | 38 | for (int i = 0; i < nums.size(); i++) { 39 | if (i % 2 == 0) { 40 | sum_diff += nums[i]; 41 | } 42 | } 43 | 44 | return sum_diff; 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Sorting/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | // Bubble Sort is the simplest sorting algorithm that works by 2 | // repeatedly swapping the adjacent elements if they are in wrong order. 3 | 4 | #include 5 | using namespace std; 6 | 7 | void bubble_sort(vector &arr) { 8 | for (int i = 0; i < arr.size(); i++) { 9 | for (int j = 0; j < arr.size() - i - 1; i++) { 10 | if (arr[j] > arr[j + 1]) { 11 | swap(arr[i], arr[j]); 12 | } 13 | } 14 | } 15 | } 16 | 17 | void print_v(vector v) { 18 | for (auto x : v) { 19 | cout << x << " "; 20 | } 21 | cout << endl; 22 | } 23 | 24 | int main(int argc, char const *argv[]) { 25 | vector arr = {1, -2, 3, 4, 7, 6, 5}; 26 | print_v(arr); 27 | 28 | bubble_sort(arr); 29 | 30 | print_v(arr); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Sorting/can_make_ap.cpp: -------------------------------------------------------------------------------- 1 | // A sequence of numbers is called an arithmetic progression if the difference 2 | // between any two consecutive elements is the same. 3 | 4 | // Given an array of numbers arr, return true if the array can be rearranged to 5 | // form an arithmetic progression. Otherwise, return false. 6 | 7 | // Example 1: 8 | 9 | // Input: arr = [3,5,1] 10 | // Output: true 11 | // Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with 12 | // differences 2 and -2 respectively, between each consecutive elements. 13 | 14 | // Example 2: 15 | 16 | // Input: arr = [1,2,4] 17 | // Output: false 18 | // Explanation: There is no way to reorder the elements to obtain an arithmetic 19 | // progression. 20 | 21 | #include 22 | using namespace std; 23 | 24 | bool canMakeArithmeticProgression(vector& arr) { 25 | sort(arr.begin(), arr.end()); 26 | 27 | int n = arr.size(); 28 | 29 | int exp_diff = arr[1] - arr[0]; 30 | 31 | for (int i = 0; i < n - 1; i++) { 32 | int j = i + 1; 33 | int calc_diff = arr[j] - arr[i]; 34 | 35 | if (calc_diff != exp_diff) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Sorting/missing_no.cpp: -------------------------------------------------------------------------------- 1 | // Find the Missing Number 2 | 3 | // You are given a list of n-1 integers and these integers are in the range of 1 4 | // to n. There are no duplicates in the list. One of the integers is missing in 5 | // the list. Write an efficient code to find the missing 6 | 7 | // Input: arr[] = {1, 2, 4, 6, 3, 7, 8} 8 | // Output: 5 9 | 10 | // Input: arr[] = {1, 2, 3, 5} 11 | // Output: 4 12 | 13 | #include 14 | 15 | void miss_no_s(int arr[], int n) { 16 | int ac_sum = (n + 1) * (n + 2) / 2; 17 | int calc_sum = 0; 18 | for (int i = 0; i < n; i++) { 19 | calc_sum += arr[i]; 20 | } 21 | std::cout << ac_sum - calc_sum; 22 | std::cout << std::endl; 23 | } 24 | 25 | void miss_no_xor(int arr[], int n) { 26 | int x_s_cal = arr[0]; 27 | int x_s_act = 0; 28 | for (int i = 1; i <= n + 1; i++) { 29 | x_s_act ^= i; 30 | } 31 | for (int i = 1; i < n; i++) { 32 | x_s_cal ^= arr[i]; 33 | } 34 | std::cout << (x_s_act ^ x_s_cal); 35 | std::cout << std::endl; 36 | } 37 | 38 | int main() { 39 | int arr[] = {1, 2, 4, 6, 3, 7, 8}; 40 | int n = sizeof(arr) / sizeof(arr[0]); 41 | 42 | miss_no_s(arr, n); 43 | miss_no_xor(arr, n); 44 | return (0); 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Sorting/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | // The selection sort algorithm sorts an array by repeatedly finding the minimum 2 | // element (considering ascending order) from unsorted part and putting it at 3 | // the beginning. The algorithm maintains two subarrays in a given array. 1) The 4 | // subarray which is already sorted. 2) Remaining subarray which is unsorted. 5 | 6 | #include 7 | using namespace std; 8 | 9 | void print_v(vector v) { 10 | for (auto x : v) { 11 | cout << x << " "; 12 | } 13 | cout << endl; 14 | } 15 | 16 | void selection_sort(vector &arr) { 17 | int i, j, min_idx; 18 | 19 | for (i = 0; i < arr.size() - 1; i++) { 20 | // find the smallest element index. 21 | min_idx = i; 22 | 23 | for (int j = i + 1; j < arr.size(); j++) { 24 | if (arr[j] < arr[min_idx]) { 25 | min_idx = j; 26 | } 27 | } 28 | // Swap the smallest element and the given index. 29 | swap(arr[min_idx], arr[i]); 30 | } 31 | } 32 | 33 | int main(int argc, char const *argv[]) { 34 | vector arr = {3, 5, -1, 7, 0, 2, 33, 1}; 35 | selection_sort(arr); 36 | print_v(arr); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/easy/is_subsequence.cpp: -------------------------------------------------------------------------------- 1 | // Given two strings s and t, check if s is a subsequence of t. 2 | 3 | // A subsequence of a string is a new string that is formed from the original 4 | // string by deleting some (can be none) of the characters without disturbing 5 | // the relative positions of the remaining characters. 6 | // (i.e., "ace" is a subsequence of "abcde" while "aec" is not). 7 | 8 | // Example 1: 9 | 10 | // Input: s = "abc", t = "ahbgdc" 11 | // Output: true 12 | 13 | // Example 2: 14 | 15 | // Input: s = "axc", t = "ahbgdc" 16 | // Output: false 17 | 18 | #include 19 | 20 | using namespace std; 21 | 22 | bool isSubsequence(string s, string t) { 23 | int m = s.size(); 24 | int n = t.size(); 25 | 26 | int i = 0, j = 0; 27 | 28 | while (i < m && j < n) { 29 | if (s[i] == t[j]) { 30 | i += 1; 31 | } 32 | j += 1; 33 | } 34 | 35 | if (i == m) { 36 | return 1; 37 | } else { 38 | return 0; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/easy/squares_sorted_arr.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums sorted in non-decreasing order, return an 2 | // array of the squares of each number sorted in non-decreasing order. 3 | 4 | // Example 1: 5 | 6 | // Input: nums = [-4,-1,0,3,10] 7 | // Output: [0,1,9,16,100] 8 | // Explanation: After squaring, the array becomes [16,1,0,9,100]. 9 | // After sorting, it becomes [0,1,9,16,100]. 10 | 11 | // Example 2: 12 | 13 | // Input: nums = [-7,-3,2,3,11] 14 | // Output: [4,9,9,49,121] 15 | 16 | // Solution: - 17 | // Square each element and sort the resultant array. 18 | // 19 | 20 | // Two pointer solution: - 21 | // Keep two pointers, square only the element which is abs() bigger. 22 | // 23 | 24 | #include 25 | 26 | using namespace std; 27 | 28 | vector sortedSquares(vector &nums) { 29 | int left = 0, right = nums.size() - 1; 30 | vector res; 31 | 32 | while (left <= right) { 33 | if (abs(nums[left]) > abs(nums[right])) { 34 | res.push_back(nums[left] * nums[left]); 35 | left += 1; 36 | } else { 37 | res.push_back(nums[right] * nums[right]); 38 | right -= 1; 39 | } 40 | } 41 | reverse(res.begin(), res.end()); 42 | return res; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/medium/duplicate_zeros.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/duplicate-zeros/ -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/medium/max_consequtive_ones.cpp: -------------------------------------------------------------------------------- 1 | // Given a binary array, find the maximum number of consecutive 1s in this 2 | // array. 3 | 4 | // Input: [1,1,0,1,1,1] 5 | // Output: 3 6 | // Explanation: The first two digits or the last three digits are consecutive 7 | // 1s. 8 | // The maximum number of consecutive 1s is 3. 9 | 10 | #include 11 | using namespace std; 12 | 13 | int max_conseq_ones(vector v) { 14 | int count = 0; 15 | int max_count = 0; 16 | for (int i = 0; i < v.size(); i++) { 17 | if (v[i] == 1) { 18 | count += 1; 19 | max_count = max(max_count, count); 20 | } else { 21 | count = 0; 22 | } 23 | } 24 | return max_count; 25 | } 26 | 27 | int main(int argc, char const *argv[]) { 28 | vector v = {1, 1, 0, 1, 1, 1}; 29 | int res = max_conseq_ones(v); 30 | cout << res << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/medium/move_zeros.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/ 2 | // 3 | -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/medium/partition_labels.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/partition-labels/ 2 | -------------------------------------------------------------------------------- /Algorithms/Two_Pointer/two_ptr.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/discuss/study-guide/1688903/Solved-all-two-pointers-problems-in-100-days 2 | -------------------------------------------------------------------------------- /C++/OOPS/classes_intro.cpp: -------------------------------------------------------------------------------- 1 | // Simple example for class 2 | 3 | #include 4 | 5 | class Simple { 6 | // Decalre data members 7 | public: 8 | int fees; 9 | std::string name; 10 | 11 | // Declare member functions 12 | // Leave for outside 13 | 14 | void print_fees(); 15 | 16 | // Declare inside. 17 | void print_name() { std::cout << this->name << std::endl; } 18 | 19 | // End the class with ; 20 | }; 21 | 22 | void Simple::print_fees() { 23 | // Continue same function 24 | std::cout << this->fees << std::endl; 25 | } 26 | 27 | int main(int argc, char const *argv[]) { 28 | // Create an object 29 | Simple obj; 30 | 31 | obj.name = "Me"; 32 | obj.fees = 100; 33 | obj.print_name(); 34 | obj.print_fees(); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /C++/OOPS/destructors.cpp: -------------------------------------------------------------------------------- 1 | // Destructor is a member function which destructs or deletes an object. 2 | // It is usually called automatically. 3 | // Destructor function is automatically invoked when the objects are destroyed. 4 | // It cannot be declared static or const. 5 | // The destructor does not have arguments. 6 | // It has no return type not even void. 7 | // An object of a class with a Destructor cannot become a member of the union. 8 | // A destructor should be declared in the public section of the class. 9 | // The programmer cannot access the address of destructor. 10 | 11 | // (1) the function ends 12 | // (2) the program ends 13 | // (3) a block containing local variables ends 14 | // (4) a delete operator is called 15 | 16 | #include 17 | using namespace std; 18 | 19 | class cons2 { 20 | public: 21 | int x, y; 22 | 23 | cons2() { 24 | this->x = x; 25 | this->y = y; 26 | } 27 | 28 | // Destructor. 29 | ~cons2(); 30 | }; 31 | 32 | int main(int argc, char const *argv[]) { 33 | cons2 a; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/OOPS/function_overloading3.cpp: -------------------------------------------------------------------------------- 1 | // If we want to overload a function of a base class, it is possible to unhide 2 | // it by using the ‘using’ keyword. We can mitigate the problem as in 2. 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Base { 8 | public: 9 | int fun() { 10 | cout << "Base::fun() called" << endl; 11 | return 0; 12 | } 13 | }; 14 | 15 | class Derived : public Base { 16 | public: 17 | using Base::fun; 18 | 19 | // Note that this function will not be run. 20 | int fun(char c) { 21 | cout << "Derived::fun(char c) called" << endl; 22 | return 0; 23 | } 24 | }; 25 | 26 | int main(int argc, char const *argv[]) { 27 | Derived d; 28 | auto res = d.fun(); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C++/OOPS/hybrid_inheritence.cpp: -------------------------------------------------------------------------------- 1 | // Hybrid inheritence example 2 | 3 | // Class A 4 | // Class B Class C 5 | // Class D 6 | 7 | #include 8 | using namespace std; 9 | 10 | class A { 11 | public: 12 | int a; 13 | }; 14 | 15 | class B : public A { 16 | public: 17 | int b; 18 | }; 19 | 20 | class C : public A { 21 | public: 22 | int c; 23 | }; 24 | 25 | class D : public B, public C { 26 | public: 27 | int d; 28 | }; 29 | 30 | int main(int argc, char const *argv[]) { 31 | D obj; 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /C++/OOPS/local_class.cpp: -------------------------------------------------------------------------------- 1 | // A class declared inside a function becomes local to that function and is 2 | // called Local Class A local class type name can only be used in the enclosing 3 | // function. 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | void fun() { 10 | class Test {}; 11 | 12 | // We can declare objects from local class. 13 | // In function 14 | Test t; 15 | Test *tp; 16 | } 17 | 18 | // All the methods of Local classes must be defined inside the class only. 19 | 20 | void fun2() { 21 | class Test2 { 22 | void display() { cout << "Hello from here"; } 23 | }; 24 | 25 | // We cannot use :: and declare it from outside. 26 | } 27 | 28 | // A Local class cannot contain static data members. It may contain static 29 | // functions though. 30 | 31 | // Member methods of local class can only access static 32 | // and enum variables of the enclosing function. 33 | // Non-static variables of the enclosing function are not accessible inside 34 | // local classes 35 | 36 | int main(int argc, char const *argv[]) { 37 | // But we cannot use them outside. 38 | // Test t1; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /C++/OOPS/multilevel_inheritence.cpp: -------------------------------------------------------------------------------- 1 | // Simple example for multi-level inheritence. 2 | // Vehicle 3 | // | 4 | // | 5 | // Fourwheeler 6 | // | 7 | // | 8 | // Car 9 | // 10 | // 11 | 12 | #include 13 | using namespace std; 14 | 15 | class Vehicle { 16 | public: 17 | Vehicle() { 18 | cout << "This is a vehicle. Constructor called for Vehicle " << endl; 19 | } 20 | }; 21 | 22 | class FourWheeler : public Vehicle { 23 | public: 24 | FourWheeler() { 25 | cout << "This is FourWheeler. Constructor called Fourwheeler " << endl; 26 | } 27 | }; 28 | 29 | class Car : public FourWheeler { 30 | public: 31 | Car() { cout << "This is Car. Constructor called for Car" << endl; } 32 | }; 33 | 34 | int main(int argc, char const *argv[]) { 35 | Car obj; 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /C++/OOPS/multiple_inheritence.cpp: -------------------------------------------------------------------------------- 1 | // Simple Multiple inheritence in C++ 2 | // Vehicle FourWheeler 3 | // --- Car ----- 4 | // 5 | // 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Vehicle { 11 | public: 12 | Vehicle() { 13 | cout << "This is vehicle, Constructor for Vehicle is called. " << endl; 14 | } 15 | }; 16 | 17 | class FourWheeler { 18 | public: 19 | FourWheeler() { 20 | cout << "This is a FourWheeler, Constructor for Fourwheeler called " 21 | << endl; 22 | } 23 | }; 24 | 25 | class Car : public Vehicle, public FourWheeler { 26 | public: 27 | Car() { cout << "This is Car, Construcotr for car is called" << endl; } 28 | }; 29 | 30 | int main(int argc, char const *argv[]) { 31 | Car obj; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/OOPS/operator_overloading.cpp: -------------------------------------------------------------------------------- 1 | // In C++, we can make operators to work for user defined classes. 2 | // This means C++ has the ability 3 | // to provide the operators with a special meaning for a data type, 4 | // this ability is known as operator overloading. 5 | 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Complex { 11 | private: 12 | int real, img; 13 | 14 | public: 15 | Complex(int real = 0, int img = 0) { 16 | this->real = real; 17 | this->img = img; 18 | } 19 | 20 | // Overloaded operator must have either zero or one argument 21 | Complex operator+(Complex const &c2) { 22 | Complex res; 23 | res.real = this->real + c2.real; 24 | res.img = this->img + c2.img; 25 | 26 | return res; 27 | } 28 | 29 | void print() { cout << this->real << " " << this->img << "i" << endl; } 30 | }; 31 | 32 | // We cannot overload 33 | // . (dot) 34 | // :: 35 | // ?: 36 | // sizeof 37 | 38 | int main(int argc, char const *argv[]) { 39 | Complex c1(10, 2); 40 | Complex c2(10, 3); 41 | 42 | auto res = c1 + c2; 43 | 44 | res.print(); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/OOPS/operator_overloading2.cpp: -------------------------------------------------------------------------------- 1 | // Example to overload ++ operator. 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Overload_inc { 8 | private: 9 | int count; 10 | 11 | public: 12 | Overload_inc() { this->count = 4; } 13 | 14 | // Overloading recieves either 0 or 1 arg. 15 | // This overload ++i . Pre-increment operator. 16 | void operator++() { this->count += 2; } 17 | 18 | // Overloading the i++. Post-increment operator. 19 | // 20 | 21 | void operator++(int) { this->count += 2; } 22 | 23 | void display() { cout << "Count = " << this->count << endl; } 24 | }; 25 | 26 | int main(int argc, char const *argv[]) { 27 | Overload_inc i; 28 | ++i; 29 | i.display(); 30 | 31 | i++; 32 | i.display(); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /C++/OOPS/operator_overloading3.cpp: -------------------------------------------------------------------------------- 1 | // Operator overloading conversion operators 2 | // 3 | // Sometimes we might need to overloading typecasting operators 4 | // to overload typecasting operators, we need to do following 5 | 6 | #include 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | class Complex { 13 | private: 14 | double real, img; 15 | 16 | public: 17 | Complex(double real = 0.0, double img = 0.0) { 18 | this->real = real; 19 | this->img = img; 20 | } 21 | 22 | double mag() { 23 | return sqrt((this->real * this->real) + (this->img * this->img)); 24 | } 25 | 26 | operator double() { return mag(); } 27 | }; 28 | 29 | int main(int argc, char const *argv[]) { 30 | Complex c1 = Complex(8, 6); 31 | double c2 = (double)c1; 32 | cout << c2; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /C++/OOPS/operator_overloading4.cpp: -------------------------------------------------------------------------------- 1 | // Overloading >> and << operators. 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Complex { 8 | private: 9 | int real, img; 10 | 11 | public: 12 | Complex(int real = 0, int img = 0) { 13 | this->real = real; 14 | this->img = img; 15 | } 16 | 17 | friend ostream &operator<<(ostream &out, const Complex &c); 18 | friend istream &operator>>(istream &in, const Complex &c); 19 | }; 20 | 21 | ostream &operator<<(ostream &out, const Complex &c) { 22 | out << c.real; 23 | out << "+ i" << c.img << endl; 24 | 25 | return out; 26 | } 27 | 28 | istream &operator>>(istream &in, const Complex &c) { 29 | cout << "Enter the real part"; 30 | in >> c.real; 31 | 32 | cout << "enter the imag part"; 33 | in >> c.img; 34 | 35 | return in; 36 | } 37 | 38 | int main(int argc, char const *argv[]) { 39 | Complex c1(10, 30); 40 | // cin>>c1; 41 | 42 | cout << "Complex object = " << endl; 43 | cout << c1; 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /C++/OOPS/polymorphism.cpp: -------------------------------------------------------------------------------- 1 | // In C++ polymorphism is mainly divided into two types: 2 | 3 | // Compile time Polymorphism 4 | // Funcion Overloading 5 | // When there are multiple functions with same name 6 | // but different parameters then these functions are said to be overloaded 7 | 8 | // Operator Overloading. 9 | 10 | // Runtime Polymorphism 11 | // Virtual Functions (Function Overriding) 12 | // Function overriding on the other hand occurs 13 | // when a derived class has a definition for one of the member 14 | // functions of the base class. That base function is said to be overridden. 15 | -------------------------------------------------------------------------------- /C++/OOPS/static_keyword.cpp: -------------------------------------------------------------------------------- 1 | // Static variables and methods in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Static members are shared among all objects. 7 | // That is why they are also known as class members or class fields. 8 | // Also, static members can be accessed without any object. 9 | 10 | class st1 { 11 | public: 12 | static int count; 13 | int a, b; 14 | 15 | // Constructor 16 | st1(int a, int b) { 17 | this->a = a; 18 | this->b = b; 19 | count += 1; 20 | } 21 | 22 | // Note that we cannot use this-> with static member 23 | // This is wrong 24 | // this->count += 1; 25 | 26 | // We can even declare static methods 27 | 28 | static int show_count() { return count; } 29 | }; 30 | 31 | // We also need to write a declaration outside. 32 | int st1 ::count = 0; 33 | 34 | int main(int argc, char const *argv[]) { 35 | st1 n1(10, 20), n2(30, 40), n3(50, 60); 36 | 37 | cout << st1::show_count() << endl; 38 | cout << st1::count << endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /C++/OOPS/virtual_destructor1.cpp: -------------------------------------------------------------------------------- 1 | // if a class contains a pure virtual destructor, it must provide a function 2 | // body for the pure virtual destructor. Making base class destructor virtual 3 | // guarantees that the object of derived class is destructed properly, i.e., 4 | // both base class and derived class destructors are called. For example, a 5 | // class becomes abstract class when it contains a pure virtual destructor. 6 | 7 | #include 8 | 9 | class Base { 10 | public: 11 | virtual ~Base() = 0; // Pure virtual destructor 12 | }; 13 | 14 | Base::~Base() { std::cout << "Pure virtual destructor is called"; } 15 | 16 | class Derived : public Base { 17 | public: 18 | ~Derived() { std::cout << "~Derived() is executed\n"; } 19 | }; 20 | 21 | int main() { 22 | Base *b = new Derived(); 23 | delete b; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /C++/STL/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void print_arr(int arr[], int n) { 7 | for (int i = 0; i < n; i++) { 8 | cout << arr[i] << " "; 9 | } 10 | cout << endl; 11 | } 12 | 13 | int main(int argc, char const *argv[]) { 14 | int arr[] = {1, 4, 5, 2, 3, 6, 7}; 15 | int n = sizeof(arr) / sizeof(arr[0]); 16 | 17 | sort(arr, arr + n); 18 | 19 | if (binary_search(arr, arr + n, 2)) { 20 | cout << "Element is found"; 21 | } else { 22 | cout << "Element not found"; 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /C++/STL/bitset.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/C++/STL/bitset.cpp -------------------------------------------------------------------------------- /C++/STL/dequeue_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void print_dq(deque dq) { 7 | for (auto x : dq) { 8 | cout << x << " "; 9 | } 10 | cout << endl; 11 | } 12 | 13 | int main(int argc, char const *argv[]) { 14 | deque d1; 15 | 16 | d1.push_back(10); 17 | d1.push_front(20); 18 | d1.push_back(30); 19 | d1.push_front(40); 20 | d1.push_back(50); 21 | 22 | print_dq(d1); 23 | 24 | cout << "Max size: " << d1.max_size() << endl; 25 | cout << "Size: " << d1.size() << endl; 26 | cout << "At no 2" << d1.at(2) << endl; 27 | cout << "Front element: " << d1.front() << endl; 28 | cout << "Rear element: " << d1.back() << endl; 29 | 30 | d1.pop_front(); 31 | d1.pop_back(); 32 | 33 | print_dq(d1); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/STL/iterators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char const *argv[]) { 8 | vector arr = {1, 2, 3, 4, 5}; 9 | 10 | vector::iterator itr1; 11 | 12 | cout << "Vector eleements printed using iterator are " << endl; 13 | 14 | for (itr1 = arr.begin(); itr1 != arr.end(); itr1++) { 15 | cout << *itr1 << " "; 16 | } 17 | cout << endl; 18 | 19 | auto itr2 = arr.begin(); 20 | advance(itr2, 3); 21 | 22 | cout << "Position after advancing the vector = " << *itr2 << endl; 23 | 24 | auto itr3 = next(itr2); 25 | 26 | cout << "Position next to first iterator = " << *itr3 << endl; 27 | 28 | auto itr4 = prev(itr3); 29 | 30 | cout << "Position prev to first iterator = " << *itr4 << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/STL/list_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void print_list(list l1) { 7 | for (auto x : l1) { 8 | cout << x << " "; 9 | } 10 | cout << endl; 11 | } 12 | 13 | int main(int argc, char const *argv[]) { 14 | list l1; 15 | list l2; 16 | 17 | for (int i = 1; i < 10; i++) { 18 | l1.push_back(i); 19 | l2.push_front(i * 2); 20 | } 21 | 22 | print_list(l1); 23 | print_list(l2); 24 | 25 | cout << endl << "Front element is : " << l1.front(); 26 | l1.pop_front(); 27 | 28 | cout << endl << "Back element is : " << l2.back(); 29 | l2.pop_back(); 30 | 31 | cout << endl; 32 | 33 | print_list(l1); 34 | print_list(l2); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /C++/STL/map_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | int main(int argc, char const *argv[]) { 7 | map m1; 8 | m1[1] = 20; 9 | m1[2] = 40; 10 | 11 | for (auto itr = m1.begin(); itr != m1.end(); itr++) { 12 | cout << itr->first << "\t" << itr->second << endl; 13 | } 14 | 15 | map m2; 16 | m2['a'] = 1; 17 | m2['b'] = 2; 18 | 19 | for (auto itr = m2.begin(); itr != m2.end(); itr++) { 20 | cout << itr->first << "\t" << itr->second << endl; 21 | } 22 | 23 | auto it = m2.find('a'); 24 | 25 | cout << endl; 26 | cout << it->first << "\t" << it->second << endl; 27 | 28 | map::iterator it2; 29 | 30 | it2 = m2.find('c'); 31 | 32 | if (it2 == m2.end()) { 33 | cout << "Key is not present in the map"; 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/STL/priority_queue_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void printpq(priority_queue pq) { 7 | while (!pq.empty()) { 8 | cout << pq.top() << " "; 9 | pq.pop(); 10 | } 11 | cout << endl; 12 | } 13 | 14 | int main(int argc, char const *argv[]) { 15 | priority_queue p1; 16 | p1.push(10); 17 | p1.push(20); 18 | p1.push(5); 19 | p1.push(2); 20 | p1.push(1); 21 | 22 | cout << "Priority queue: "; 23 | printpq(p1); 24 | 25 | cout << endl << "p1.size() : " << p1.size(); 26 | cout << endl << "p1.top() : " << p1.top(); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /C++/STL/queue_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Queues, stacks and priority Queues do not have iterators. 7 | void print_q(queue q1) { 8 | while (!q1.empty()) { 9 | cout << " " << q1.front(); 10 | q1.pop(); 11 | } 12 | cout << endl; 13 | } 14 | 15 | int main(int argc, char const *argv[]) { 16 | queue q; 17 | q.push(10); 18 | q.push(20); 19 | q.push(30); 20 | q.push(40); 21 | 22 | print_q(q); 23 | 24 | cout << "Size of queue " << q.size() << endl; 25 | cout << "Front of queue " << q.front() << endl; 26 | cout << "Back of queue " << q.back() << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /C++/STL/set_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char const *argv[]) { 9 | set> s1; 10 | s1.insert(40); 11 | s1.insert(30); 12 | s1.insert(20); 13 | s1.insert(20); 14 | s1.insert(10); 15 | s1.insert(10); 16 | 17 | set::iterator i1; 18 | cout << "Set s1 is: "; 19 | for (i1 = s1.begin(); i1 != s1.end(); i1++) { 20 | cout << "\t " << *i1; 21 | } 22 | cout << endl; 23 | cout << "Number of occurences of 10 = " << s1.count(10) << endl; 24 | cout << "Number of occurences of 1 = " << s1.count(1) << endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /C++/STL/stack_basics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void print_stack(stack s1) { 7 | while (!s1.empty()) { 8 | cout << s1.top() << " "; 9 | s1.pop(); 10 | } 11 | cout << endl; 12 | } 13 | 14 | int main(int argc, char const *argv[]) { 15 | stack s1; 16 | s1.push(10); 17 | s1.push(20); 18 | s1.push(3); 19 | s1.push(1); 20 | 21 | print_stack(s1); 22 | 23 | cout << "Size of the stack " << s1.size() << endl; 24 | cout << "Top of the stack " << s1.top() << endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /C++/STL/template_fn.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | template 6 | T area_rect(T a, T b) { 7 | T result = a * b; 8 | return result; 9 | } 10 | 11 | int main(int argc, char const *argv[]) { 12 | int a1 = area_rect(10, 5); 13 | int a2 = area_rect(10.5, 2); 14 | cout << a1 << endl; 15 | cout << a2 << endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /C++/STL/vector_of_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void print_vec(vector> v) { 7 | for (int i = 0; i < v.size(); i++) { 8 | for (int j = 0; j < v[i].size(); j++) { 9 | cout << v[i][j] << " "; 10 | } 11 | cout << endl; 12 | } 13 | } 14 | 15 | int main(int argc, char const *argv[]) { 16 | vector> v1 = {{1, 2, 3}, {4, 5, 6}}; 17 | cout << "Number of rows: " << v1.size() << endl; 18 | cout << "Number of columns: " << v1[0].size() << endl; 19 | 20 | print_vec(v1); 21 | 22 | cout << endl; 23 | vector v2 = {1, 1, 1}; 24 | v1.push_back(v2); 25 | print_vec(v1); 26 | 27 | // Remove a complete row from matrix 28 | v1[0].pop_back(); 29 | 30 | cout << endl; 31 | print_vec(v1); 32 | 33 | cout << endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /C++/advanced/functors.cpp: -------------------------------------------------------------------------------- 1 | // Functors are objects that can be treated as though they are a function or 2 | // function pointer. A functor (or function object) is a C++ class that acts 3 | // like a function. Functors are called using the same old function call syntax. 4 | // To create a functor, we create a object that overloads the operator() 5 | -------------------------------------------------------------------------------- /C++/advanced/lambda_exp.cpp: -------------------------------------------------------------------------------- 1 | // C++ 11 introduced lambda expression to allow 2 | // us write an inline function which can be used for 3 | // short snippets of code that are not going to 4 | // be reuse and not worth naming. 5 | 6 | // [ capture clause ] (parameters) -> return-type 7 | // { 8 | // definition of method 9 | // } 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | void print_vector(vector v) { 16 | for_each(v.begin(), v.end(), [](int i) { std::cout << i << " "; }); 17 | } 18 | 19 | int main(int argc, char const* argv[]) { 20 | vector v{4, 1, 3, 5, 2, 3, 1, 7}; 21 | 22 | print_vector(v); 23 | 24 | cout << endl; 25 | 26 | vector::iterator p = 27 | find_if(v.begin(), v.end(), [](int i) { return i > 4; }); 28 | 29 | cout << "First number greater than 4 = " << *p << endl; 30 | 31 | // function to sort vector, lambda expression is for sorting in 32 | // non-decreasing order Compiler can make out return type as 33 | // bool, but shown here just for explanation 34 | sort(v.begin(), v.end(), 35 | [](const int& a, const int& b) -> bool { return a > b; }); 36 | 37 | print_vector(v); 38 | 39 | cout << endl; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /C++/concurrency/mutex_example.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // Includes the mutex library header. 3 | #include 4 | // Includes the thread library header. 5 | #include 6 | 7 | using namespace std; 8 | 9 | int count = 0; 10 | 11 | mutex m; 12 | 13 | void add_count() { 14 | m.lock(); 15 | count += 1; 16 | m.unlock(); 17 | } 18 | 19 | int main(int argc, char const *argv[]) { 20 | thread t1(add_count); 21 | thread t2(add_count); 22 | 23 | t1.join(); 24 | t2.join(); 25 | 26 | cout << "Current count = " << count << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /C++/concurrency/readme.md: -------------------------------------------------------------------------------- 1 | # Useful resources for concurrency and synchronization 2 | 3 | 4 | https://stackoverflow.com/questions/2350544/in-what-situation-do-you-use-a-semaphore-over-a-mutex-in-c 5 | 6 | https://stackoverflow.com/questions/187761/recursive-lock-mutex-vs-non-recursive-lock-mutex/189778#189778 7 | 8 | https://github.com/cmu-db/15445-bootcamp/tree/main 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /C++/concurrency/rwlocks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int g_count = 0; 5 | shared_mutex sm; 6 | 7 | void read_value() { 8 | shared_lock sl(sm); 9 | cout << "count = " << to_string(g_count); 10 | } 11 | 12 | void write_value() { 13 | unique_lock ul(sm); 14 | g_count += 3; 15 | } 16 | 17 | int main(int argc, char const *argv[]) { 18 | thread t1(read_value); 19 | thread t2(write_value); 20 | thread t3(read_value); 21 | thread t4(read_value); 22 | thread t5(write_value); 23 | thread t6(read_value); 24 | 25 | t1.join(); 26 | t2.join(); 27 | t3.join(); 28 | t4.join(); 29 | t5.join(); 30 | t6.join(); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/concurrency/scoped_lock.cpp: -------------------------------------------------------------------------------- 1 | // Includes std::cout (printing) for demo purposes. 2 | #include 3 | // Includes the mutex library header. 4 | #include 5 | // Includes the thread library header. 6 | #include 7 | 8 | using namespace std; 9 | 10 | int count = 0; 11 | mutex m; 12 | 13 | // normal mutex 14 | void update() { 15 | m.lock(); 16 | count += 1; 17 | m.unlock(); 18 | } 19 | 20 | void better_update() { 21 | // The constructor of std::scoped_lock allows for the thread to acquire the 22 | // mutex m. 23 | std::scoped_lock slk(m); 24 | count += 1; 25 | 26 | // Once the function add_count finishes, the object slk is out of scope, and 27 | // in its destructor, the mutex m is released. 28 | } 29 | 30 | int main(int argc, char const *argv[]) { 31 | thread t1(better_update); 32 | thread t2(better_update); 33 | 34 | t1.join(); 35 | t2.join(); 36 | 37 | cout << "Count = " << count; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /C++/directives/macros1.cpp: -------------------------------------------------------------------------------- 1 | // There are 4 main types of preprocessor directives: 2 | // Macros 3 | // File Inclusion 4 | // Conditional Compilation 5 | // Other directives 6 | 7 | // Preprocessor programs provide preprocessors directives which tell 8 | // the compiler to preprocess the source code before compiling. All of these 9 | // preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol 10 | // indicates that, whatever statement starts with #, is going to the 11 | // preprocessor program, and preprocessor program will execute this statemen 12 | 13 | // Let us now learn about each of these directives in detail. 14 | 15 | // Macros: Macros are a piece of code in a program which 16 | // is given some name. Whenever this name is 17 | // encountered by the compiler the compiler 18 | // replaces the name with the actual piece of code. 19 | // The ‘#define’ directive is used to define a macro. 20 | 21 | // https://www.geeksforgeeks.org/macros-and-its-types-in-c-cpp/ 22 | -------------------------------------------------------------------------------- /C++/directives/macros2.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/C++/directives/macros2.cpp -------------------------------------------------------------------------------- /C++/directives/pragma.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/pragma-directive-in-c-c/ 2 | -------------------------------------------------------------------------------- /C++/exception_handling/custom_exception.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class MyException : public std::exception { 7 | public: 8 | const char *what() const throw() { return "C++ Custom exception"; } 9 | }; 10 | 11 | int main(int argc, char const *argv[]) { 12 | try { 13 | throw MyException(); 14 | } catch (MyException &e) { 15 | cout << e.what() << endl; 16 | } 17 | 18 | catch (exception &e) { 19 | cout << "Any other errors" << endl; 20 | } 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /C++/exception_handling/try_catch1.cpp: -------------------------------------------------------------------------------- 1 | // Simple example for try and catch block 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main(int argc, char const *argv[]) { 7 | int x = -1; 8 | cout << endl << "Before try"; 9 | 10 | try { 11 | cout << endl << "Inside try"; 12 | if (x < 0) { 13 | throw x; 14 | cout << "This will not be printed" << endl; 15 | } 16 | } 17 | 18 | catch (int x) { 19 | cout << endl << "Exception Caught"; 20 | } 21 | 22 | cout << endl << "After catch. Stuff will be continued"; 23 | cout << endl; 24 | 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /C++/exception_handling/try_catch2.cpp: -------------------------------------------------------------------------------- 1 | // C++ library has a standard exception class which is base class for all 2 | // standard exceptions. All objects thrown by components of the standard library 3 | // are derived from this class. Therefore, all standard exceptions can be caught 4 | // by catching this type C++, all exceptions are unchecked. Compiler doesn’t 5 | // check whether an exception is caught or not. For example, in C++, it is not 6 | // necessary to specify all uncaught exceptions in a function declaration. 7 | 8 | #include 9 | using namespace std; 10 | 11 | int main(int argc, char const *argv[]) { 12 | try { 13 | throw 10; 14 | } 15 | 16 | catch (char *excp) { 17 | cout << "Caught" << endl; 18 | } 19 | 20 | // Use catch(...) to catch all remaining errors. 21 | catch (...) { 22 | cout << "Default Exception" << endl; 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /C++/exception_handling/try_catch3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | double divide(double a, double b) { 6 | if (b == 0) // !! Division by zero 7 | throw "Division by zero"; 8 | else 9 | return a / b; 10 | } 11 | 12 | int main(int argc, char const *argv[]) { 13 | vector v; 14 | v.push_back(0); 15 | v.push_back(1); 16 | 17 | try { 18 | v.at(2); 19 | } catch (const exception &e) { 20 | cout << "Error occured" << endl; 21 | } 22 | 23 | try { 24 | double res = divide(1, 0); 25 | } catch (const char *c) { 26 | cout << c; 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /C++/file_handling/file_handling2.cpp: -------------------------------------------------------------------------------- 1 | // File handling using fstream 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char const *argv[]) { 9 | // Creation of fstream object 10 | fstream fio; 11 | 12 | string line = "hello world"; 13 | 14 | // by default openmode = ios::in|ios::out mode 15 | // Automatically overwrites the content of file, To append 16 | // the content, open in ios:app 17 | // fio.open("sample.txt", ios::in|ios::out|ios::app) 18 | 19 | fio.open("hello2.txt", ios::trunc | ios::out | ios::in); 20 | 21 | while (fio) { 22 | fio << line << endl; 23 | fio.close(); 24 | } 25 | 26 | fio.seekg(0, ios::beg); 27 | while (fio) { 28 | getline(fio, line); 29 | 30 | cout << line << endl; 31 | 32 | fio.close(); 33 | } 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/file_handling/hello.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | -------------------------------------------------------------------------------- /C++/file_handling/hello2.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | -------------------------------------------------------------------------------- /C++/gdb_tutorial/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | FLAGS = -ggdb -Wall 3 | 4 | main: main.cc 5 | ${CXX} ${FLAGS} -o main main.cc 6 | 7 | clean: 8 | rm -f main 9 | -------------------------------------------------------------------------------- /C++/gdb_tutorial/readme.md: -------------------------------------------------------------------------------- 1 | Refer CMU tutorial 2 | 3 | https://www.cs.cmu.edu/~gilpin/tutorial/ 4 | 5 | https://www.youtube.com/watch?v=PorfLSr3DDI 6 | 7 | 8 | -------------------------------------------------------------------------------- /C++/namespaces/namespace3.cpp: -------------------------------------------------------------------------------- 1 | // Unnamed Namespaces 2 | 3 | // They are directly usable in the same program and are used for declaring 4 | // unique identifiers. In unnamed namespaces, name of the namespace in not 5 | // mentioned in the declaration of namespace. The name of the namespace is 6 | // uniquely generated by the compiler. The unnamed namespaces you have created 7 | // will only be accessible within the file you created it in. Unnamed namespaces 8 | // are the replacement for the static declaration of variables. 9 | 10 | // C++ program to demonstrate working of unnamed 11 | // namespaces 12 | #include 13 | using namespace std; 14 | 15 | // unnamed namespace declaration 16 | namespace { 17 | int rel = 300; 18 | } 19 | 20 | int main() { 21 | cout << rel << "\n"; // prints 300 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /C++/namespaces/namespace5.cpp: -------------------------------------------------------------------------------- 1 | // Using namespace in header files 2 | 3 | // Use "" to include local header files 4 | #include 5 | 6 | #include "simple_header.h" 7 | 8 | int main(int argc, char const *argv[]) { 9 | std::cout << foo::value() << std::endl; 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /C++/namespaces/namespace6.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to demonstrate working of 2 | // inline namespaces 3 | // An inline namespace is a namespace that uses the optional 4 | // keyword inline in its original-namespace-definition. 5 | 6 | #include 7 | using namespace std; 8 | 9 | namespace ns1 { 10 | inline namespace ns2 { 11 | int var = 10; 12 | } 13 | } // namespace ns1 14 | 15 | int main() { 16 | cout << ns1::var; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /C++/namespaces/namespaces1.cpp: -------------------------------------------------------------------------------- 1 | // In each scope, a name can only represent one entity. 2 | // Using namespaces, we can create two variables or member functions having the 3 | // same name 4 | 5 | #include 6 | using namespace std; 7 | 8 | // Variable in a namespace 9 | namespace first { 10 | int val = 100; 11 | } 12 | 13 | // A global variable. 14 | int val = 200; 15 | 16 | int main(int argc, char const *argv[]) { 17 | int val = 300; 18 | 19 | // Variable within the namespace 20 | cout << first::val << endl; 21 | 22 | // Local variable (as it is prefered over global) 23 | cout << val << endl; 24 | 25 | return 0; 26 | } 27 | 28 | // Namespaces allow us to group named entities that otherwise 29 | // would have global scope into narrower scopes, giving them namespace scope. 30 | // This allows organizing the elements of programs into different logical scopes 31 | // referred to by names. A namespace is a declarative region that provides/ a 32 | // scope to the identifiers (names of the types, function, variables etc) inside 33 | // it. Multiple namespace blocks with the same name are allowed. 34 | -------------------------------------------------------------------------------- /C++/namespaces/namespaces2.cpp: -------------------------------------------------------------------------------- 1 | // Namespace declarations appear only at global scope. 2 | // Namespace declarations can be nested within another namespace. 3 | // Namespace declarations don’t have access specifiers. (Public or private) 4 | // No need to give semicolon after the closing brace of definition of namespace. 5 | // We can split the definition of namespace over several units. 6 | 7 | #include 8 | 9 | using namespace std; 10 | 11 | namespace ns1 { 12 | int value() { return 5; } 13 | } // namespace ns1 14 | 15 | namespace ns2 { 16 | const double x = 200; 17 | double value() { return (2 * x); } 18 | 19 | } // namespace ns2 20 | 21 | int main(int argc, char const *argv[]) { 22 | cout << ns1::value() << endl; 23 | cout << ns2::value() << endl; 24 | 25 | // We can also access the variable 26 | cout << ns2::x << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /C++/namespaces/namespaces4.cpp: -------------------------------------------------------------------------------- 1 | // Classes and Namespace: 2 | 3 | // Following is a simple way to create classes in a name space 4 | 5 | // Class can also be declared inside namespace and defined outside namespace 6 | 7 | #include 8 | using namespace std; 9 | 10 | namespace ns1 { 11 | class Simple { 12 | public: 13 | void display() { cout << "Hello from simple" << endl; } 14 | }; 15 | } // namespace ns1 16 | 17 | namespace ns2 { 18 | class Complic; 19 | } 20 | 21 | class ns2 ::Complic { 22 | public: 23 | void display() { cout << "Hi from Complic" << endl; } 24 | }; 25 | 26 | int main(int argc, char const *argv[]) { 27 | ns1::Simple obj; 28 | obj.display(); 29 | 30 | ns2::Complic obj2; 31 | obj2.display(); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /C++/namespaces/simple_header.h: -------------------------------------------------------------------------------- 1 | namespace foo 2 | { 3 | int value() 4 | { 5 | return 5; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /C++/ptrs/smart_pointer.cpp: -------------------------------------------------------------------------------- 1 | // Problem with Normal pointer 2 | // A pointer points to object / variable. 3 | // They are not de allocated automatically. 4 | // We need to free() them. 5 | // Memory leak can occur. 6 | // Smart pointer can avoid these issues. 7 | 8 | #include 9 | using namespace std; 10 | 11 | class Rectangle { 12 | private: 13 | int length, breadth; 14 | }; 15 | 16 | void fun() { 17 | // Create a pointer to rectangle 18 | Rectangle *rp = new Rectangle(); 19 | } 20 | 21 | int main(int argc, char const *argv[]) { 22 | while (true) { 23 | fun(); 24 | } 25 | return 0; 26 | } 27 | 28 | // In above example 29 | // Once the function ends this ‘p’ is deleted because p is a local variable to 30 | // the function but a new rectangle that is allocated inside heap that will not 31 | // be deallocated We will soon be occupying the heap memory space, through 32 | // infinte loops. We need to explicitly delete the pointer. 33 | 34 | // Smart pointers 35 | // Smart pointers are automatically de-allocated when they are not needed. 36 | // Heap memory is automatically retained. 37 | // Smart pointers are already in C++ std lib and we can use them. 38 | -------------------------------------------------------------------------------- /C++/ptrs/this_pointer.cpp: -------------------------------------------------------------------------------- 1 | // This pointer. 2 | // This poiner is used in following cases. 3 | 4 | #include 5 | using namespace std; 6 | 7 | // 1. Constructors in classes. 8 | // This points to the object of class. 9 | // Use this in constructors to allocate data. 10 | 11 | // 2. To return the object passed in class. 12 | // We can simply return *this. (ris) 13 | 14 | class Simple { 15 | private: 16 | int x; 17 | 18 | public: 19 | // A constrcutor. 20 | // Constructor can use this, to assign data. 21 | Simple(int x) { this->x = x; } 22 | 23 | // Member function can use this to acces objects's details. 24 | void print() { cout << endl << "Value of x = " << this->x; } 25 | 26 | // Function that returns object. 27 | Simple return_obj() { return *this; } 28 | }; 29 | 30 | int main(int argc, char const *argv[]) { 31 | Simple obj(12); 32 | obj.print(); 33 | 34 | // We get the object back using ris. 35 | Simple ret = obj.return_obj(); 36 | 37 | ret.print(); 38 | 39 | cout << endl; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /C++/readme.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | - CMU Bootcamp 4 | 5 | https://github.com/cmu-db/15445-bootcamp/tree/main 6 | 7 | 8 | 9 | https://15445.courses.cs.cmu.edu/spring2025/project0/ 10 | 11 | 12 | -------------------------------------------------------------------------------- /C++/templates/template3.cpp: -------------------------------------------------------------------------------- 1 | // Like function templates, class templates are useful when a class defines 2 | // something that is independent of data type 3 | 4 | #include 5 | using namespace std; 6 | 7 | template 8 | class Array { 9 | // Data members 10 | private: 11 | int *ptr; 12 | int size; 13 | 14 | public: 15 | // Constructor 16 | Array(T arr[], int s); 17 | 18 | // Member function. 19 | void print(); 20 | }; 21 | 22 | // Defining the constructor. 23 | template 24 | Array::Array(T arr[], int s) { 25 | this->ptr = new T[s]; 26 | this->size = s; 27 | 28 | for (int i = 0; i < this->size; i++) { 29 | this->ptr[i] = arr[i]; 30 | } 31 | } 32 | 33 | template 34 | void Array::print() { 35 | for (int i = 0; i < this->size; i++) { 36 | cout << *(this->ptr + i) << " "; 37 | } 38 | cout << endl; 39 | } 40 | 41 | int main(int argc, char const *argv[]) { 42 | int arr[5] = {1, 2, 3, 4, 5}; 43 | Array cus_arr(arr, 5); 44 | 45 | cus_arr.print(); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /C++/templates/template_specialization.cpp: -------------------------------------------------------------------------------- 1 | // It is possible in C++ to get a special behavior for 2 | // a particular data type. This is called template specialization. 3 | 4 | // An Example Program for function template specialization 5 | // For example, consider the following simple code where we have general 6 | // template fun() for all data types except int. For int, there is a specialized 7 | // version of fun(). 8 | 9 | #include 10 | using namespace std; 11 | 12 | template 13 | void fun(T a) { 14 | cout << "Template default function is called " << endl; 15 | } 16 | 17 | template <> 18 | void fun(int a) { 19 | cout << "Specialized template for int data type is called" << endl; 20 | } 21 | 22 | int main(int argc, char const *argv[]) { 23 | fun('a'); 24 | fun(10); 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /C++/templates/templates1.cpp: -------------------------------------------------------------------------------- 1 | // Templates are expanded at compiler time. 2 | // This is like macros. The difference is, compiler does type checking before 3 | // template expansion. The idea is simple, source code contains only 4 | // function/class, but compiled code may contain multiple copies of same 5 | // function/class. 6 | 7 | // It eliminates the need to create different 8 | // algorithms if the data type is an integer, string or a character. 9 | 10 | // The advantages of Generic Programming are 11 | 12 | // Code Reusability 13 | // Avoid Function Overloading 14 | // Once written it can be used for multiple times and cases. 15 | 16 | #include 17 | using namespace std; 18 | 19 | // Generic function using template. 20 | 21 | template 22 | T newMax(T x, T y) { 23 | if (x > y) { 24 | return x; 25 | } else { 26 | return y; 27 | } 28 | } 29 | 30 | int main(int argc, char const *argv[]) { 31 | cout << newMax(3, 4) << endl; 32 | cout << newMax(3.2, 4.2) << endl; 33 | cout << newMax('g', 'e') << endl; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/templates/templates2.cpp: -------------------------------------------------------------------------------- 1 | // Bubble sort with templates 2 | 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void bubble_sort(T arr[], int n) { 8 | for (int i = 0; i < n - 1; i++) { 9 | for (int j = 0; j < n - i - 1; j++) { 10 | if (arr[j] > arr[j + 1]) { 11 | swap(arr[j], arr[j + 1]); 12 | } 13 | } 14 | } 15 | } 16 | 17 | int main(int argc, char const *argv[]) { 18 | int arr[5] = {10, 40, 20, 30, 50}; 19 | int n = sizeof(arr) / sizeof(arr[0]); 20 | 21 | bubble_sort(arr, n); 22 | 23 | for (int i = 0; i < n; i++) { 24 | cout << arr[i] << " "; 25 | } 26 | cout << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /C++/templates/templates4.cpp: -------------------------------------------------------------------------------- 1 | // we can pass more than one data types as arguments to templates. The following 2 | // example demonstrates the same. 3 | 4 | #include 5 | using namespace std; 6 | 7 | template 8 | 9 | class A { 10 | T x; 11 | U y; 12 | 13 | public: 14 | A() { cout << "Constructor Called" << endl; } 15 | }; 16 | 17 | int main() { 18 | A a; 19 | A b; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/game_of_life.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/game-of-life/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/jump_dist.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/jump-game/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/largest_sum_contigous_arr.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Largest Sum Contiguous Subarray 3 | 4 | // Write an efficient program to find the sum of contiguous subarray 5 | // within a one-dimensional array of numbers which has the largest sum. 6 | 7 | // We do not know the window size 8 | 9 | // Kadane's Algorithm 10 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/max_subarr_sum.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, 2 | // find the contiguous subarray (containing at least one number) 3 | // which has the largest sum and return its sum. 4 | 5 | // Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 6 | // Output: 6 7 | // Explanation: [4,-1,2,1] has the largest sum = 6. 8 | 9 | // Solution: - 10 | 11 | // We need to use Kadane's algorithm. 12 | // Keep a track of sum so far. 13 | // If sum so far is -ve set it to 0 14 | // Add the new element to sum only if net sum is +ve 15 | // Update maximum sum with sum. 16 | 17 | #include 18 | using namespace std; 19 | 20 | int max_sub_arr(vector &nums) { 21 | int sum = 0, smax = INT_MIN; 22 | 23 | for (int num : nums) { 24 | sum += num; 25 | smax = max(sum, smax); 26 | if (sum < 0) { 27 | sum = 0; 28 | } 29 | } 30 | return smax; 31 | } 32 | 33 | int main(int argc, char const *argv[]) { 34 | vector v = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; 35 | 36 | auto res = max_sub_arr(v); 37 | cout << res << endl; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/next_greater.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/find-next-greater-number-set-digits/ -------------------------------------------------------------------------------- /Data_Structures/Arrays/reverse_arr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print_arr(int arr[], int n) { 5 | for (int i = 0; i < n; i++) { 6 | cout << arr[i] << " "; 7 | } 8 | } 9 | 10 | void reverse_arr(int arr[], int n) { 11 | int start = 0; 12 | int end = n - 1; 13 | while (start < end) { 14 | swap(arr[start], arr[end]); 15 | start += 1; 16 | end -= 1; 17 | } 18 | print_arr(arr, n); 19 | } 20 | 21 | int main() { 22 | int arr[] = {1, 2, 3, 4, 5, 6, 7}; 23 | int n = sizeof(arr) / sizeof(arr[0]); 24 | reverse_arr(arr, n); 25 | return (0); 26 | } 27 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/subarray_0.cpp: -------------------------------------------------------------------------------- 1 | // Check if subarray with 0 sum is exists or not 2 | 3 | #include 4 | using namespace std; 5 | 6 | bool zeroSumSubarray(int arr[], int n) { 7 | unordered_set s1; 8 | // Handle case if arr starts with 0; 9 | s1.insert(0); 10 | 11 | int running_sum = 0; 12 | 13 | // Traverse the array 14 | for (int i = 0; i < n; i++) { 15 | running_sum += arr[i]; 16 | if (s1.find(running_sum) != s1.end()) { 17 | // We found the sum 18 | return true; 19 | } else { 20 | s1.insert(running_sum); 21 | } 22 | } 23 | // We reach end without doing anyting 24 | return false; 25 | } 26 | 27 | int main(int argc, char const *argv[]) { 28 | int arr[] = {4, 2, -3, -1, 0, 4}; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | // Subarray with 0 sum exists 31 | // Subarrays must be with contigous locations, occupy consecutive positions 32 | if (zeroSumSubarray(arr, n)) { 33 | cout << "Yes"; 34 | } else { 35 | cout << "No"; 36 | } 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Data_Structures/Arrays/toeplitz_mat.cpp: -------------------------------------------------------------------------------- 1 | // https://binarysearch.com/problems/Toeplitz-Matrix 2 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/easy/ceil.cpp: -------------------------------------------------------------------------------- 1 | // Ceil in a BST 2 | 3 | class Node { 4 | public: 5 | int data; 6 | Node *left, *right; 7 | }; 8 | 9 | int findCeil(Node *root, int key) { 10 | int ceil = -1; 11 | 12 | while (root) { 13 | if (root->data == key) { 14 | ceil = root->data; 15 | return ceil; 16 | } 17 | 18 | else if (root->data > key) { 19 | ceil = root->data; 20 | root = root->left; 21 | } 22 | 23 | else { 24 | root = root->right; 25 | } 26 | } 27 | return ceil; 28 | } 29 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/easy/floor.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Node { 3 | public: 4 | int data; 5 | Node *left, *right; 6 | }; 7 | 8 | int floor(Node *root, int key) { 9 | int floor = -1; 10 | while (root) { 11 | if (root->data == key) { 12 | floor = root->data; 13 | return floor; 14 | } 15 | 16 | if (root->data < key) { 17 | floor = root->data; 18 | root = root->right; 19 | } else { 20 | root = root->left; 21 | } 22 | } 23 | 24 | return floor; 25 | } 26 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/easy/inorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | // We can use iterative inorder traversal trick 2 | // This helps to solve many BST problems. 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Node { 8 | public: 9 | Node *left, *right; 10 | int data; 11 | }; 12 | 13 | vector inorder_traversal(Node *root) { 14 | vector res; 15 | if (root == NULL) { 16 | return res; 17 | } 18 | 19 | stack stk; 20 | 21 | // While we don't reach the end or we have items to traverse 22 | while (root != NULL || !stk.empty()) { 23 | while (root != NULL) { 24 | stk.push(root); 25 | // left traversal done. 26 | root = root->left; 27 | } 28 | 29 | // Now traverse these elements. 30 | root = stk.top(); 31 | stk.pop(); 32 | // This will add left and middle. 33 | res.push_back(root->data); 34 | // Now traverse right elements. 35 | root = root->right; 36 | } 37 | return res; 38 | } 39 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/easy/intro.cpp: -------------------------------------------------------------------------------- 1 | // Binary Search Tree is a node-based binary tree data structure which has the 2 | // following properties: 3 | 4 | // The left subtree of a node contains only nodes with keys lesser than the 5 | // node’s key. The right subtree of a node contains only nodes with keys greater 6 | // than the node’s key. The left and right subtree each must also be a binary 7 | // search tree. 8 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/easy/min_max.cpp: -------------------------------------------------------------------------------- 1 | // Finding minimum and maximum value in BST. 2 | 3 | // We can exploit the structural property of BST. 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Node { 10 | public: 11 | Node *left, *right; 12 | int data; 13 | }; 14 | 15 | int min_value(Node *node) { 16 | Node *curr = node; 17 | 18 | // smallest is always towards left. 19 | while (curr->left != NULL) { 20 | curr = curr->left; 21 | } 22 | 23 | // Now current has no left. 24 | 25 | return curr->data; 26 | } 27 | 28 | int max_value(Node *node) { 29 | Node *curr = node; 30 | 31 | // Greatest value is always towards right 32 | 33 | while (curr->right != NULL) { 34 | curr = curr->right; 35 | } 36 | 37 | return curr->data; 38 | } 39 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/balance_bst.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/balance-a-binary-search-tree/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/const_from_inorder.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | 3 | // Note that sorted array is a inorder traversal of BST. 4 | // So this is same as constructing from inorder. 5 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/const_from_preorder.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/kth_smallest.cpp: -------------------------------------------------------------------------------- 1 | // Given the root of a binary search tree, and an integer k, 2 | // return the kth (1-indexed) smallest element in the tree. 3 | 4 | // Input: root = [3,1,4,null,2], k = 1 5 | // Output: 1 6 | 7 | // Input: root = [5,3,6,2,4,null,null,1], k = 3 8 | // Output: 3 9 | 10 | #include 11 | using namespace std; 12 | 13 | class Node { 14 | public: 15 | Node *left, *right; 16 | int data; 17 | }; 18 | 19 | int kthSmallest(Node *root, int k) { 20 | stack stk; 21 | 22 | // stk.push(root); 23 | 24 | while (!stk.empty() || root != NULL) { 25 | while (root != NULL) { 26 | stk.push(root); 27 | root = root->left; 28 | } 29 | 30 | root = stk.top(); 31 | stk.pop(); 32 | 33 | k -= 1; 34 | if (k == 0) return root->data; 35 | 36 | root = root->right; 37 | } 38 | return -1; 39 | } 40 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/lowest_common_ancestor.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 2 | 3 | // Given a binary search tree (BST), find the lowest common ancestor (LCA) of 4 | // two given nodes in the BST. 5 | 6 | // According to the definition of LCA on Wikipedia: 7 | // “The lowest common ancestor is defined between two nodes 8 | // p and q as the lowest node in T that has both p and q as 9 | // descendants (where we allow a node to be a descendant of itself).” 10 | 11 | // Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 12 | // Output: 6 13 | // Explanation: The LCA of nodes 2 and 8 is 6. 14 | 15 | // Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 16 | // Output: 2 17 | // Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant 18 | // of itself according to the LCA definition. 19 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/min_difference.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-absolute-difference-in-bst/ 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class TreeNode { 8 | public: 9 | int val; 10 | TreeNode *left, *right; 11 | }; 12 | 13 | int min_diff = INT_MAX; 14 | TreeNode *prev = NULL; 15 | 16 | void dfs(TreeNode *root) { 17 | if (root == NULL) return; 18 | 19 | dfs(root->left); 20 | 21 | if (prev != NULL) { 22 | min_diff = min(min_diff, abs(prev->val - root->val)); 23 | } 24 | 25 | prev = root; 26 | 27 | dfs(root->right); 28 | } 29 | 30 | int getMinimumDifference(TreeNode *root) { 31 | dfs(root); 32 | return min_diff; 33 | } -------------------------------------------------------------------------------- /Data_Structures/Binary_Search_Tree/medium/range_sum.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-sum-of-bst/description/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class TreeNode { 7 | public: 8 | int val; 9 | TreeNode *left, *right; 10 | }; 11 | 12 | int res = 0; 13 | 14 | void inorder(TreeNode* root, int low, int high) { 15 | if (root == NULL) return; 16 | 17 | inorder(root->left, low, high); 18 | if (root->val > high) 19 | return; 20 | else if (root->val >= low) 21 | res += root->val; 22 | 23 | inorder(root->right, low, high); 24 | } 25 | 26 | int rangeSumBST(TreeNode* root, int low, int high) { 27 | inorder(root, low, high); 28 | return res; 29 | } -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/construction/const_from_level_order.cpp: -------------------------------------------------------------------------------- 1 | // https://www.tutorialcup.com/interview/tree/construct-bst-from-its-given-level-order-traversal.htm 2 | 3 | // Given the level order traversal of a Binary Search Tree, 4 | // write an algorithm to construct the Binary Search Tree or 5 | // BST from ITS given level order traversal. 6 | 7 | // Input 8 | // levelOrder[] = {18, 12, 20, 8, 15, 25, 5, 9, 22, 31} 9 | // Output 10 | // In-order : 5 8 9 12 15 18 20 22 25 31 11 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/construction/const_from_preorder_postorder.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 2 | 3 | // Given two integer arrays, preorder and postorder where preorder 4 | // is the preorder traversal of a binary tree of distinct values and postorder 5 | // is the postorder traversal of the same tree, reconstruct and return the 6 | // binary tree. If there exist multiple answers, you can return any of them. 7 | 8 | // Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1] 9 | // Output: [1,2,3,4,5,6,7] 10 | 11 | // Solution: - 12 | 13 | // In this case it is not possible to construct a distinct answer always. 14 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/easy/intro.cpp: -------------------------------------------------------------------------------- 1 | // A Binary Tree node contains following parts. 2 | 3 | // Data 4 | // Pointer to left child 5 | // Pointer to right child 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Node { 11 | public: 12 | int data; 13 | Node *left, *right; 14 | }; 15 | 16 | int main(int argc, char const *argv[]) { 17 | Node *root = new Node(); 18 | root->data = 1; 19 | 20 | root->left->data = 2; 21 | 22 | root->right->data = 3; 23 | 24 | root->left = new Node(); 25 | root->left->data = 4; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/easy/subtree_check2.cpp: -------------------------------------------------------------------------------- 1 | // Given two binary trees with head reference as T and S having at most N nodes. 2 | // The task is to check if S is present as subtree in T. 3 | // A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its 4 | // descendants in T1. 5 | 6 | // Example 1: 7 | 8 | // Input: 9 | // T: 1 S: 3 10 | // / \ / 11 | // 2 3 4 12 | // / \ / 13 | // N N 4 14 | // Output: 1 15 | // Explanation: S is present in T 16 | 17 | // The idea is based on the fact that inorder 18 | // and preorder/postorder uniquely identify a binary tree. 19 | // Tree S is a subtree of T if both inorder and preorder traversals 20 | // of S are substrings of inorder and preorder traversals of T respectively. 21 | // 1) Find inorder and preorder traversals of T, store them in two auxiliary 22 | // arrays inT[] and preT[]. 2) Find inorder and preorder traversals of S, store 23 | // them in two auxiliary arrays inS[] and preS[]. 3) If inS[] is a subarray of 24 | // inT[] and preS[] is a subarray preT[], then S is a subtree of T. Else not. We 25 | // can also use postorder traversal in place of preorder in the above algorithm. 26 | // 27 | // 28 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/easy/univalued_tree.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/univalued-binary-tree/ 2 | 3 | // A binary tree is uni-valued if every node in the tree has the same value. 4 | 5 | // Given the root of a binary tree, return true if the given tree is uni-valued, 6 | // or false otherwise. 7 | 8 | #include 9 | using namespace std; 10 | 11 | class TreeNode { 12 | public: 13 | int val; 14 | TreeNode *left, *right; 15 | }; 16 | 17 | bool isUnivalTree(TreeNode* root) { 18 | int root_val = root->val; 19 | 20 | // Now do a simple bfs / level order 21 | 22 | queue q; 23 | q.push(root); 24 | 25 | while (!q.empty()) { 26 | TreeNode* node = q.front(); 27 | q.pop(); 28 | 29 | if (node->val != root_val) { 30 | return false; 31 | } 32 | 33 | if (node->left != NULL) { 34 | q.push(node->left); 35 | } 36 | 37 | if (node->right != NULL) { 38 | q.push(node->right); 39 | } 40 | } 41 | 42 | return true; 43 | } 44 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/implement/Makefile: -------------------------------------------------------------------------------- 1 | # Compiler 2 | CXX = g++ 3 | 4 | # Compiler flags 5 | CXXFLAGS = -Wall -g 6 | 7 | # Target executable 8 | TARGET = basic_binary_tree 9 | 10 | # Source file 11 | SRCS = basic_binary_tree.cpp 12 | 13 | # Object files 14 | OBJS = $(SRCS:.cpp=.o) 15 | 16 | # Default rule to build the executable 17 | all: $(TARGET) 18 | 19 | # Rule to link object files into the target executable 20 | $(TARGET): $(OBJS) 21 | $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJS) 22 | 23 | # Rule to compile .cpp files into .o files 24 | %.o: %.cpp 25 | $(CXX) $(CXXFLAGS) -c $< -o $@ 26 | 27 | # Rule to run the program 28 | run: $(TARGET) 29 | ./$(TARGET) 30 | 31 | # Clean rule to remove generated files 32 | clean: 33 | rm -f $(TARGET) $(OBJS) 34 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/leaves/deepest_leaves.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/deepest-leaves-sum/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class TreeNode { 7 | public: 8 | int val; 9 | TreeNode *left, *right; 10 | }; 11 | 12 | vector bfs(TreeNode* root) { 13 | queue q; 14 | vector res; 15 | q.push(root); 16 | 17 | while (!q.empty()) { 18 | int n = q.size(); 19 | int sum = 0; 20 | for (int i = 0; i < n; i++) { 21 | TreeNode* node = q.front(); 22 | q.pop(); 23 | sum += node->val; 24 | 25 | if (node->left != NULL) { 26 | q.push(node->left); 27 | } 28 | 29 | if (node->right != NULL) { 30 | q.push(node->right); 31 | } 32 | } 33 | res.push_back(sum); 34 | } 35 | return res; 36 | } 37 | 38 | int deepestLeavesSum(TreeNode* root) { 39 | vector res = bfs(root); 40 | return res[res.size() - 1]; 41 | } 42 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/leaves/leaf_similar_trees.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/leaf-similar-trees/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class TreeNode { 7 | public: 8 | int val; 9 | TreeNode *left, *right; 10 | }; 11 | 12 | void dfs(TreeNode *root, vector &res) { 13 | if (root == NULL) return; 14 | 15 | dfs(root->left, res); 16 | 17 | if (root->left == NULL && root->right == NULL) { 18 | res.push_back(root->val); 19 | } 20 | 21 | dfs(root->right, res); 22 | } 23 | 24 | bool leafSimilar(TreeNode *root1, TreeNode *root2) { 25 | vector leav1; 26 | vector leav2; 27 | 28 | dfs(root1, leav1); 29 | dfs(root2, leav2); 30 | 31 | // print_v(leav1); 32 | // print_v(leav2); 33 | 34 | // sort(begin(leav1), end(leav1)); 35 | // sort(begin(leav2), end(leav2)); 36 | 37 | // print_v(leav1); 38 | // print_v(leav2); 39 | 40 | return leav1 == leav2; 41 | } 42 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/medium/count_complete_nodes.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-complete-tree-nodes/ 2 | 3 | // Given the root of a complete binary tree, return the number of the nodes in 4 | // the tree. 5 | 6 | // According to Wikipedia, every level, except possibly the last, 7 | // is completely filled in a complete binary tree, and all nodes 8 | // in the last level are as far left as possible. It can have between 1 and 2h 9 | // nodes inclusive at the last level h. 10 | 11 | // Design an algorithm that runs in less than O(n) time complexity. 12 | 13 | // Input: root = [1,2,3,4,5,6] 14 | // Output: 6 15 | 16 | // Solution 17 | // Most naive is to do any traversal such as pre / in / post / bfs and increase 18 | // the count once node is visited. Return the count. 19 | 20 | // For an approach under O(n). We need optimization. 21 | 22 | // 23 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/medium/flatten_tree.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ 2 | // 3 | // Given the root of a binary tree, flatten the tree into a "linked list": 4 | // 5 | // The "linked list" should use the same TreeNode class where the 6 | // right child pointer points to the next node in the list and the left child 7 | // pointer is always null. The "linked list" should be in the same order as a 8 | // pre-order traversal of the binary tree. 9 | 10 | // Input: root = [1,2,5,3,4,null,6] 11 | // Output: [1,null,2,null,3,null,4,null,5,null,6] 12 | 13 | // https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/1067000/C%2B%2B-oror-Both-Recursive-andand-Iterative-Solution 14 | -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/path_sums/path_sum1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | // https://leetcode.com/problems/path-sum/ 4 | Given a tree and a sum, return true if there is a path from the root 5 | down to a leaf, such that adding up all the values along the path 6 | equals the given sum. 7 | 8 | Strategy: subtract the node value from the sum when recurring down, 9 | and check to see if the sum is 0 when you run out of tree. 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | class TreeNode { 16 | public: 17 | int val; 18 | TreeNode *left, *right; 19 | }; 20 | 21 | bool dfs(TreeNode *root, int targetSum) { 22 | if (root == NULL) { 23 | return false; 24 | } 25 | 26 | int rem = targetSum - root->val; 27 | 28 | // we have found a solution 29 | if (rem == 0 && root->left == NULL && root->right == NULL) { 30 | return true; 31 | } 32 | return dfs(root->left, rem) || dfs(root->right, rem); 33 | } 34 | 35 | bool hasPathSum(TreeNode *root, int targetSum) { 36 | if (root == NULL) { 37 | return false; 38 | } 39 | return dfs(root, targetSum); 40 | } -------------------------------------------------------------------------------- /Data_Structures/Binary_Tree/traversal/level_order_zigzag.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ 2 | 3 | // Just a small twist to level order traversal. 4 | // We just need to reverse after even levels. 5 | 6 | #include 7 | using namespace std; 8 | 9 | class Node { 10 | public: 11 | int data; 12 | Node *left, *right; 13 | }; 14 | 15 | vector> zigzagLevelOrder(Node* root) { 16 | // just a modification of level order 17 | 18 | vector> res; 19 | 20 | if (root == NULL) return res; 21 | 22 | queue q; 23 | 24 | q.push(root); 25 | int cnt = 0; 26 | 27 | while (!q.empty()) { 28 | vector temp; 29 | int len = q.size(); 30 | 31 | for (int i = 0; i < len; i++) { 32 | Node* node = q.front(); 33 | q.pop(); 34 | temp.push_back(node->data); 35 | 36 | if (node->left != NULL) { 37 | q.push(node->left); 38 | } 39 | 40 | if (node->right != NULL) { 41 | q.push(node->right); 42 | } 43 | } 44 | 45 | if ((cnt % 2 == 1)) { 46 | reverse(temp.begin(), temp.end()); 47 | } 48 | res.push_back(temp); 49 | cnt += 1; 50 | } 51 | 52 | return res; 53 | } 54 | -------------------------------------------------------------------------------- /Data_Structures/Graph/cycle/dfs_cycle_directed_graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Data_Structures/Graph/cycle/dfs_cycle_directed_graph.png -------------------------------------------------------------------------------- /Data_Structures/Graph/cycle/shortest_cycle_udg.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/shortest-cycle-in-a-graph/ 2 | // 3 | // Note this is an undirected graph 4 | -------------------------------------------------------------------------------- /Data_Structures/Graph/easy/count_unreachable_nodes.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/easy/steps_by_knight.cpp: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/problems/steps-by-knight5927/1 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/floodfill/find_all_groups_farmland.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-groups-of-farmland/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/floodfill/notes.txt: -------------------------------------------------------------------------------- 1 | Basic idea here is to dfs on matrix 2 | Imagine matrix to be connected. 3 | Either 4 ways or 8 ways, depending on the question 4 | 5 | Now we need to do dfs to explore all 4 / 8 directions 6 | Use this trick. 7 | 8 | This captures all possible x and y moves. 9 | 10 | vector x_moves = {-1, 1, 0, 0} 11 | vector y_moves = {0, 0, -1, 1} 12 | 13 | now for this 4 combo do do dfs 14 | 15 | for(int i=0; i<4; i++) 16 | { 17 | int new_x = old_x + x_moves[i]; 18 | int new_y = old_y + y_moves[i]; 19 | 20 | if(is_safe()) 21 | { 22 | dfs(new_x, new_y); 23 | } 24 | 25 | } 26 | 27 | safe condition check is obvious 28 | 29 | if(new_x >= 0 && new_x < m && new_y >= 0 && new_y < n && !visited[new_x][new_y] && some more) 30 | 31 | Note we need to keep track of visited! 32 | 33 | Use a matrix of size m x n to track it! 34 | vector> visited(m, vector(n)); 35 | 36 | Since it's a graph! remember to do DFS on EVERY VERTEX. If needed! 37 | Here every vertex is every cell of matrix 38 | loop over the matrix and do dfs on every cell 39 | take care that cell is not visited or any extra condition. 40 | 41 | -------------------------------------------------------------------------------- /Data_Structures/Graph/graph_structure.txt: -------------------------------------------------------------------------------- 1 | Remember structure of graph by adjacency list 2 | is a map> 3 | 4 | { 5 | 0: [3, 4, 5], 6 | 3: [0], 7 | 4: [0], 8 | 5: [0] 9 | } 10 | 11 | This could also be represeneted via vector of vector 12 | here ith index will mark to ith node. 13 | 14 | [[3, 5, 5], [], [], [0], [0], [0]] 15 | 16 | Note the trick in graph is to construct this and understand the given representation 17 | 18 | Keep in mind if graph is given from 0 indexing or 1. 19 | Accordingly we will need visited vector. 20 | 21 | Graph is just a tree, with extra counting for visited. 22 | Keep track correctly. 23 | 24 | 25 | -------------------------------------------------------------------------------- /Data_Structures/Graph/hard/word_ladder.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-ladder/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/hard/word_ladder2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-ladder-ii/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/shortest_paths/city_smallest_threshold.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/description/? 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/shortest_paths/network_delay_time.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/network-delay-time/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/shortest_paths/path_max_prob.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/path-with-maximum-probability/description/? 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/shortest_paths/shortest_path_binary_maze.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/shortest-path-in-binary-matrix/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Graph/shortest_paths/snake_ladders.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Data_Structures/Graph/shortest_paths/snake_ladders.cpp -------------------------------------------------------------------------------- /Data_Structures/Hashing/easy/sum_uniq.cpp: -------------------------------------------------------------------------------- 1 | // You are given an integer array nums. The unique elements of an array are the 2 | // elements that appear exactly once in the array. 3 | 4 | // Return the sum of all the unique elements of nums. 5 | 6 | // https://leetcode.com/problems/sum-of-unique-elements/ 7 | 8 | // Input: nums = [1,2,3,2] 9 | // Output: 4 10 | // Explanation: The unique elements are [1,3], and the sum is 4. 11 | 12 | // Form a hashmap of all the nums 13 | // Check if num count is = 1 is hashmap add it. 14 | 15 | #include 16 | using namespace std; 17 | 18 | int uniq_sum(vector nums) { 19 | // Map to store value and count 20 | map mp; 21 | 22 | for (int i = 0; i < nums.size(); i++) { 23 | mp[nums[i]] += 1; 24 | } 25 | 26 | // Add the sum 27 | int sum = 0; 28 | 29 | for (int i = 0; i < nums.size(); i++) { 30 | if (mp[nums[i]] == 1) { 31 | sum += nums[i]; 32 | } 33 | } 34 | 35 | return sum; 36 | } 37 | 38 | int main(int argc, char const *argv[]) { 39 | vector nums = {1, 2, 3, 2}; 40 | 41 | cout << uniq_sum(nums); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Data_Structures/Heap/easy/intro_heap.cpp: -------------------------------------------------------------------------------- 1 | // Implement Heap using Priority Queue 2 | 3 | #include 4 | using namespace std; 5 | 6 | template 7 | 8 | void print_heap(priority_queue hp) { 9 | while (!hp.empty()) { 10 | cout << hp.top() << " "; 11 | hp.pop(); 12 | } 13 | } 14 | 15 | int main(int argc, char const *argv[]) { 16 | // Creating a max heap using priority queue 17 | priority_queue maxh; 18 | 19 | // This is directly a max heap and it will be sorted. 20 | maxh.push(5); 21 | maxh.push(10); 22 | maxh.push(2); 23 | maxh.push(0); 24 | 25 | cout << "Max Heap " << endl; 26 | 27 | // Note that this is printed in reverse order (as seen in stack) 28 | print_heap(maxh); 29 | 30 | // Creating min heap using priority queue 31 | 32 | priority_queue, greater> minh; 33 | 34 | // This is sorted, with greatest element at bottom of stack. 35 | minh.push(10); 36 | minh.push(32); 37 | minh.push(12); 38 | minh.push(99); 39 | 40 | cout << "Min Heap " << endl; 41 | print_heap(minh); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Data_Structures/Heap/medium/k_smallest_mat.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Linked_lists/LinkedListProblems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Data_Structures/Linked_lists/LinkedListProblems.pdf -------------------------------------------------------------------------------- /Data_Structures/Linked_lists/build_and_print_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node *next; 8 | }; 9 | 10 | void print_ln(Node *node) { 11 | while (node != NULL) { 12 | cout << node->data << " "; 13 | node = node->next; 14 | } 15 | } 16 | 17 | int main(int argc, char const *argv[]) { 18 | Node *head = NULL; 19 | Node *second = NULL; 20 | Node *third = NULL; 21 | head = new Node(); 22 | second = new Node(); 23 | third = new Node(); 24 | 25 | head->data = 1; 26 | head->next = second; 27 | 28 | second->data = 2; 29 | second->next = third; 30 | 31 | third->data = 3; 32 | third->next = NULL; 33 | 34 | print_ln(head); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Data_Structures/Linked_lists/find_length.cpp: -------------------------------------------------------------------------------- 1 | // Find length of linked list 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Node { 7 | public: 8 | int data; 9 | Node *next; 10 | }; 11 | 12 | void insert_head(Node **head_ref, int new_data) { 13 | Node *new_node = new Node(); 14 | new_node->data = new_data; 15 | new_node->next = *head_ref; 16 | *head_ref = new_node; 17 | } 18 | 19 | void print_ln(Node *node) { 20 | while (node != NULL) { 21 | cout << node->data << " "; 22 | node = node->next; 23 | } 24 | cout << endl; 25 | } 26 | 27 | int length(Node *node) { 28 | int count = 0; 29 | while (node != NULL) { 30 | count += 1; 31 | node = node->next; 32 | } 33 | return count; 34 | } 35 | 36 | int main(int argc, char const *argv[]) { 37 | Node *head = NULL; 38 | insert_head(&head, 3); 39 | insert_head(&head, 2); 40 | insert_head(&head, 1); 41 | 42 | print_ln(head); 43 | cout << length(head) << endl; 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/additional_problems.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/asteroid-collision/ 2 | 3 | https://leetcode.com/problems/sum-of-subarray-ranges/ 4 | 5 | https://leetcode.com/problems/remove-k-digits/ 6 | 7 | https://leetcode.com/problems/largest-rectangle-in-histogram/ 8 | 9 | https://leetcode.com/problems/trapping-rain-water/ 10 | 11 | https://leetcode.com/problems/maximal-rectangle/ 12 | 13 | https://leetcode.com/problems/next-greater-element-ii/ 14 | 15 | 16 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/easy/backspace_strings.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/backspace-string-compare/ 2 | // Given two strings s and t, return true if they are equal when both are 3 | // typed into empty text editors. '#' means a backspace character. 4 | // Note that after backspacing an empty text, the text will continue empty. 5 | 6 | // Example 1: 7 | 8 | // Input: s = "ab#c", t = "ad#c" 9 | // Output: true 10 | // Explanation: Both s and t become "ac". 11 | 12 | 13 | 14 | #include 15 | 16 | using namespace std; 17 | 18 | string process_str(stack &stk, string s) { 19 | for (auto ch : s) { 20 | if (ch == '#') { 21 | if (!stk.empty()) { 22 | stk.pop(); 23 | } 24 | } 25 | 26 | else { 27 | stk.push(ch); 28 | } 29 | } 30 | 31 | string res = ""; 32 | while (!stk.empty()) { 33 | res += stk.top(); 34 | stk.pop(); 35 | } 36 | 37 | return res; 38 | } 39 | 40 | bool backspaceCompare(string s, string t) { 41 | stack stk1; 42 | stack stk2; 43 | 44 | string res1 = process_str(stk1, s); 45 | string res2 = process_str(stk2, t); 46 | 47 | return res1 == res2; 48 | } -------------------------------------------------------------------------------- /Data_Structures/Stacks/easy/rev_string.cpp: -------------------------------------------------------------------------------- 1 | // Write code to reverse a string using stack 2 | 3 | #include 4 | using namespace std; 5 | 6 | string rev_string_stack(string s) { 7 | stack st; 8 | string res = ""; 9 | 10 | for (int i = 0; i < s.length(); i++) { 11 | st.push(s[i]); 12 | } 13 | 14 | while (!st.empty()) { 15 | res += st.top(); 16 | st.pop(); 17 | } 18 | 19 | return res; 20 | } 21 | 22 | int main(int argc, char const *argv[]) { 23 | string s = "abc"; 24 | cout << s << endl; 25 | 26 | auto res = rev_string_stack(s); 27 | 28 | cout << res << endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/easy/stack_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define MAX 1000 6 | 7 | class Stack { 8 | int top; 9 | 10 | public: 11 | int a[MAX]; // Maximum size of Stack 12 | 13 | Stack() { top = -1; } 14 | bool push(int x); 15 | int pop(); 16 | int peek(); 17 | bool isEmpty(); 18 | }; 19 | 20 | bool Stack::push(int x) { 21 | if (top >= (MAX - 1)) { 22 | cout << "Stack Overflow"; 23 | return false; 24 | } else { 25 | a[++top] = x; 26 | cout << x << " pushed into stack\n"; 27 | return true; 28 | } 29 | } 30 | 31 | int Stack::pop() { 32 | if (top < 0) { 33 | cout << "Stack Underflow"; 34 | return 0; 35 | } else { 36 | int x = a[top--]; 37 | return x; 38 | } 39 | } 40 | int Stack::peek() { 41 | if (top < 0) { 42 | cout << "Stack is Empty"; 43 | return 0; 44 | } else { 45 | int x = a[top]; 46 | return x; 47 | } 48 | } 49 | 50 | bool Stack::isEmpty() { return (top < 0); } 51 | 52 | // Driver program to test above functions 53 | int main() { 54 | class Stack s; 55 | s.push(10); 56 | s.push(20); 57 | s.push(30); 58 | cout << s.pop() << " Popped from stack\n"; 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Data_Structures/Stacks/easy/stacks_intro.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void showstack(stack s) { 6 | while (!s.empty()) { 7 | cout << " " << s.top(); 8 | s.pop(); 9 | } 10 | } 11 | 12 | int main() { 13 | stack s; 14 | s.push(10); 15 | s.push(20); 16 | s.push(30); 17 | showstack(s); 18 | } -------------------------------------------------------------------------------- /Data_Structures/Stacks/medium/asteroid_collision.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/asteroid-collision/ 2 | 3 | // We are given an array asteroids of integers representing asteroids in a row. 4 | 5 | // For each asteroid, the absolute value represents its size, and the sign 6 | // represents its direction (positive meaning right, negative meaning left). 7 | // Each asteroid moves at the same speed. 8 | 9 | // Find out the state of the asteroids after all collisions. If two asteroids 10 | // meet, the smaller one will explode. If both are the same size, both will 11 | // explode. Two asteroids moving in the same direction will never meet. 12 | 13 | // Example 1: 14 | 15 | // Input: asteroids = [5,10,-5] 16 | // Output: [5,10] 17 | // Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never 18 | // collide. 19 | 20 | // Example 2: 21 | 22 | // Input: asteroids = [8,-8] 23 | // Output: [] 24 | // Explanation: The 8 and -8 collide exploding each other. 25 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/medium/largest_area_hist.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers A of size N. A represents a histogram i.e A[i] 2 | // denotes height of the ith histogram’s bar. Width of each bar is 1. 3 | 4 | // Largest Rectangle in Histogram: Example 1 5 | 6 | // Above is a histogram where width of each bar is 1, given height = 7 | // [2,1,5,6,2,3]. 8 | // 9 | // | | | | | | 10 | // | | | | | 11 | // | | | 12 | // | | 13 | // | | 14 | // | 15 | 16 | // Largest Rectangle in Histogram: Example 2 17 | 18 | // The largest rectangle is shown in the shaded area, which has area = 10 unit. 19 | 20 | // Find the area of largest rectangle in the histogram. 21 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/medium/minimum_remove.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/description/ 2 | 3 | 4 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/medium/remove_duplicates.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicate-letters/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Stacks/practice_order.txt: -------------------------------------------------------------------------------- 1 | 1. stacks_intro.cpp, rev string 2 | 2. valid_parantehsis 3 | 3. next left greater etc 4 | 4. remove adj elem1 5 | 5. remove adj elem2 6 | 6. 7 | 8 | -------------------------------------------------------------------------------- /Data_Structures/Strings/easy/first_uniq_char.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | 3 | // Given a string s, return the first non-repeating character in it 4 | // and return its index. If it does not exist, return -1. 5 | 6 | // Store the 7 | 8 | #include 9 | using namespace std; 10 | 11 | int firstUniqChar(string s) { 12 | map mp; 13 | for (int i = 0; i < s.length(); i++) { 14 | mp[s[i]]++; 15 | } 16 | 17 | for (int i = 0; i < s.length(); i++) { 18 | // Appeared only once so didn't repeat. 19 | if (mp[s[i]] == 1) { 20 | return i; 21 | } 22 | } 23 | 24 | return -1; 25 | } 26 | -------------------------------------------------------------------------------- /Data_Structures/Strings/easy/homo_substr.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-number-of-homogenous-substrings/ 2 | 3 | #include 4 | using namespace std; 5 | -------------------------------------------------------------------------------- /Data_Structures/Strings/easy/is_panagram.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/check-if-the-sentence-is-pangram/ 2 | 3 | // A pangram is a sentence where every letter of the English alphabet appears at 4 | // least once. 5 | 6 | // Given a string sentence containing only lowercase English letters, 7 | // return true if sentence is a pangram, or false otherwise. 8 | 9 | // Example 1: 10 | 11 | // Input: sentence = "thequickbrownfoxjumpsoverthelazydog" 12 | // Output: true 13 | // Explanation: sentence contains at least one of every letter of the English 14 | // alphabet. 15 | 16 | // Example 2: 17 | 18 | // Input: sentence = "leetcode" 19 | // Output: false 20 | 21 | #include 22 | using namespace std; 23 | 24 | bool checkIfPangram(string sentence) { 25 | set st; 26 | 27 | for (char c : sentence) { 28 | st.insert(c); 29 | } 30 | 31 | return (st.size() == 26); 32 | } 33 | -------------------------------------------------------------------------------- /Data_Structures/Strings/easy/reverse_words_dot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | string s1; 6 | char cmp = '.'; 7 | int t; 8 | cin >> t; 9 | while (t--) { 10 | cin >> s1; 11 | string temp = ""; 12 | for (int i = 0; i < s1.length(); i++) { 13 | if (s1[i] == cmp) { 14 | for (int j = temp.length(); j >= 0; j--) { 15 | cout << temp[j]; 16 | } 17 | temp = ""; 18 | cout << "."; 19 | } else { 20 | temp += s1[i]; 21 | } 22 | } 23 | for (int k = temp.length(); k >= 0; k--) { 24 | cout << temp[k]; 25 | } 26 | cout << endl; 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/add_bin_nums.cpp: -------------------------------------------------------------------------------- 1 | // https://binarysearch.com/problems/Add-Binary-Numbers 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/camelcase_match.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/camelcase-matching/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/custom_sort.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/custom-sort-string/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/dest_city.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/destination-city/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/interleaving_string.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/interleaving-string/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/lex_strings.cpp: -------------------------------------------------------------------------------- 1 | // https://binarysearch.com/problems/Ancient-Astronaut-Theory 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/reduce_binary.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/roatate_strings.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-string/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/subtr_with_1s.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-substrings-with-only-1s/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/swap_longest_string.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/swap-for-longest-repeated-character-substring/ -------------------------------------------------------------------------------- /Data_Structures/Strings/medium/uniq_email.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-email-addresses/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Trie/design_add_word_data_structure.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/design-add-and-search-words-data-structure/description/ 2 | 3 | -------------------------------------------------------------------------------- /Data_Structures/Trie/extra_characters_string.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/extra-characters-in-a-string/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Trie/longest_valid_word_prefix.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Data_Structures/Trie/longest_valid_word_prefix.cpp -------------------------------------------------------------------------------- /Data_Structures/Trie/longest_word_dictionary.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-word-in-dictionary/description/ 2 | -------------------------------------------------------------------------------- /Data_Structures/Trie/maximum_xor_two_numbers.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/description/ 2 | 3 | -------------------------------------------------------------------------------- /Data_Structures/Trie/maximum_xor_with_an_element.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-xor-with-an-element-from-array/description/ 2 | 3 | 4 | -------------------------------------------------------------------------------- /Data_Structures/Trie/number_distinct_substrings.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-distinct-substrings-in-a-string/description/ 2 | 3 | -------------------------------------------------------------------------------- /Java/arrays/anonymous_arrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class anonymous_arrays 4 | { 5 | public static void print_arr(int arr[]) 6 | { 7 | for(int x: arr) 8 | { 9 | System.out.print(x + " "); 10 | } 11 | System.out.println(); 12 | } 13 | 14 | public int [] return_arr(int arr[]) 15 | { 16 | return(new int [] {1, 2, 3, 4}); 17 | } 18 | 19 | public static void main(String[] args) 20 | { 21 | print_arr(new int[] {2, 3, 4, 6}); 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/arrays/arr_count.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class arr_count 4 | { 5 | public static void main(String[] args) 6 | { 7 | int [] arr = {1, 2, 3, 4, 5, 1 ,1}; 8 | int se = 1; 9 | int count = 0; 10 | 11 | for(int i=0; i arr[j+1]) 22 | { 23 | int temp = arr[j]; 24 | arr[j] = arr[j+1]; 25 | arr[j+1] = temp; 26 | } 27 | } 28 | } 29 | 30 | for(int i=0; i st = new Stack(); 10 | st.push(10); 11 | st.push(20); 12 | st.push(30); 13 | 14 | System.out.println(st); 15 | 16 | while(!st.isEmpty()) 17 | { 18 | System.out.print(st.pop() + " "); 19 | } 20 | System.out.println(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Java/collections/vector_intro.java: -------------------------------------------------------------------------------- 1 | package collections; 2 | 3 | import java.util.*; 4 | 5 | public class vector_intro 6 | { 7 | public static void main(String[] args) 8 | { 9 | Vector v1 = new Vector(); 10 | v1.add(60); 11 | v1.add(30); 12 | 13 | System.out.println(v1); 14 | 15 | v1.add(1, 40); 16 | 17 | System.out.println(v1); 18 | 19 | System.out.println(v1.elementAt(2)); 20 | 21 | Vector v2 = new Vector(); 22 | v2.add(60); 23 | v2.add(40); 24 | v2.add(30); 25 | 26 | if(v2.equals(v1)) 27 | { 28 | System.out.println("Yes"); 29 | } 30 | else 31 | { 32 | System.out.println("No"); 33 | } 34 | 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java/date/date_time.java: -------------------------------------------------------------------------------- 1 | package date; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.*; 5 | 6 | public class date_time 7 | { 8 | public static void main(String[] args) 9 | { 10 | // Date date = new Date(); 11 | // System.out.print(date.toString()); 12 | 13 | Date dnow = new Date(); 14 | SimpleDateFormat ft = new SimpleDateFormat("E dd.MM.YYYY 'at' hh:mm:ss a zzz"); 15 | System.out.println("Current Date: " + ft.format(dnow)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java/exception_handling/throw_intro.java: -------------------------------------------------------------------------------- 1 | // The Java throw keyword is used to explicitly throw an exception. 2 | // We can throw either checked or unchecked exception in java by throw keyword. 3 | // The throw keyword is mainly used to throw custom exception 4 | 5 | // Throw keyword 6 | // Throws an excpetion 7 | // Followed by an instance 8 | // Used within a method 9 | // Cannot throw multiple exceptions. 10 | 11 | 12 | 13 | public class throw_intro 14 | { 15 | public static void validate(int age) 16 | { 17 | if(age < 18 || age > 27) 18 | { 19 | throw new ArithmeticException("Invalid Age"); 20 | } 21 | } 22 | 23 | public static void main(String[] args) 24 | { 25 | int age = 5; 26 | 27 | try 28 | { 29 | validate(age); 30 | } 31 | catch (ArithmeticException e) 32 | { 33 | System.out.println(e.getMessage()); 34 | System.out.println(e.getCause()); 35 | } 36 | finally 37 | { 38 | System.out.println("For more information do not contact us"); 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Java/file_handling/buffered_reader.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedInputStream; 2 | import java.io.BufferedOutputStream; 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | 7 | class buffered_reader 8 | { 9 | public static void main(String[] args) 10 | { 11 | try 12 | { 13 | File obj = new File("dummy5.txt"); 14 | 15 | // Buffered output stream 16 | FileOutputStream fout = new FileOutputStream(obj); 17 | BufferedOutputStream bout = new BufferedOutputStream(fout); 18 | bout.write(104); 19 | bout.close(); 20 | fout.close(); 21 | 22 | // Read from saved file 23 | FileInputStream fin = new FileInputStream(obj); 24 | BufferedInputStream bin = new BufferedInputStream(fin); 25 | int data = bin.read(); 26 | System.out.println((char) data); 27 | 28 | bin.close(); 29 | fin.close(); 30 | 31 | } 32 | 33 | catch (Exception e) 34 | { 35 | System.out.println(e.getMessage()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Java/file_handling/create_file.java: -------------------------------------------------------------------------------- 1 | // package file_handling; 2 | import java.io.File; 3 | import java.io.IOException; 4 | 5 | 6 | public class create_file 7 | { 8 | public static void main(String[] args) 9 | { 10 | // Java Program to create a file 11 | try 12 | { 13 | // Create file object 14 | File obj = new File("somename.txt"); 15 | 16 | // Create a file 17 | if(obj.createNewFile()) 18 | { 19 | System.out.println("File is created " + obj.getName()); 20 | } 21 | 22 | // File exists 23 | else 24 | { 25 | System.out.println("File already exists"); 26 | } 27 | } 28 | catch (IOException e) 29 | { 30 | System.out.println("IO Exception occured"); 31 | System.out.println(e.getStackTrace()); 32 | System.out.println(e.getMessage()); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Java/file_handling/dummy.txt: -------------------------------------------------------------------------------- 1 | hello -------------------------------------------------------------------------------- /Java/file_handling/dummy2.txt: -------------------------------------------------------------------------------- 1 | ēėĞĝċď -------------------------------------------------------------------------------- /Java/file_handling/dummy3.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Java/file_handling/dummy3.txt -------------------------------------------------------------------------------- /Java/file_handling/dummy4.bin: -------------------------------------------------------------------------------- 1 |  who are you? -------------------------------------------------------------------------------- /Java/file_handling/dummy4.txt: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Java/file_handling/dummy5.txt: -------------------------------------------------------------------------------- 1 | h -------------------------------------------------------------------------------- /Java/file_handling/file_stream2.java: -------------------------------------------------------------------------------- 1 | // package file_handling; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.IOException; 7 | 8 | public class file_stream2 9 | { 10 | public static void main(String[] args) throws IOException 11 | { 12 | File obj = new File("dummy.txt"); 13 | 14 | System.out.println(obj.getName()); 15 | 16 | FileOutputStream fout = new FileOutputStream(obj); 17 | 18 | fout.write(104); 19 | fout.write(101); 20 | fout.write(108); 21 | fout.write(108); 22 | fout.write(111); 23 | fout.close(); 24 | 25 | 26 | FileInputStream fin = new FileInputStream(obj); 27 | int data; 28 | 29 | while((data = fin.read()) != -1) 30 | { 31 | System.out.print((char) data); 32 | } 33 | 34 | System.out.println(); 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java/file_handling/file_stream3.java: -------------------------------------------------------------------------------- 1 | // package file_handling; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | import java.io.OutputStreamWriter; 10 | 11 | public class file_stream3 12 | { 13 | // Reading utf-16 encoding files. 14 | public static void main(String[] args) throws IOException 15 | { 16 | File obj = new File("dummy2.txt"); 17 | FileInputStream fin = new FileInputStream(obj); 18 | InputStreamReader iread = new InputStreamReader(fin, "UTF-16"); 19 | int data = iread.read(); 20 | System.out.println((char) data); 21 | 22 | // Writing utf-16 characters to file 23 | 24 | File obj2 = new File("dummy3.txt"); 25 | FileOutputStream fout = new FileOutputStream(obj2); 26 | OutputStreamWriter iwrite = new OutputStreamWriter(fout, "UTF-16"); 27 | iwrite.write(1011); 28 | iwrite.write(1012); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java/file_handling/file_streams1.java: -------------------------------------------------------------------------------- 1 | // package file_handling; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.io.File; 6 | 7 | public class file_streams1 8 | { 9 | public static void main(String[] args) throws IOException 10 | { 11 | File obj = new File("dummy.txt"); 12 | 13 | System.out.println(obj.getName()); 14 | 15 | FileInputStream fs = new FileInputStream(obj); 16 | 17 | int data = fs.read(); 18 | System.out.println(data); 19 | 20 | // Read characters 21 | System.out.println((char) data); 22 | 23 | // Get file channel 24 | System.out.println(fs.getChannel()); 25 | 26 | // Get file descriptor 27 | System.out.println(fs.getFD()); 28 | 29 | 30 | while((data = fs.read()) != -1) 31 | { 32 | System.out.print((char) data); 33 | } 34 | 35 | System.out.println(); 36 | 37 | 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Java/file_handling/file_writer.java: -------------------------------------------------------------------------------- 1 | // package file_handling; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | // File writer can read only utf-8 encoding data 7 | // It cannot read utf-16 or other encodings. 8 | 9 | public class file_writer 10 | { 11 | public static void main(String[] args) 12 | { 13 | try 14 | { 15 | // Crreate fileWriter object 16 | FileWriter fwriter = new FileWriter("somename.txt"); 17 | // Write content to file 18 | fwriter.write("Writing this line to the file"); 19 | fwriter.close(); 20 | System.out.println("Successfully wrote to the file"); 21 | 22 | } 23 | catch (Exception e) 24 | { 25 | System.out.println("An error occured"); 26 | System.out.println(e.getMessage()); 27 | System.out.println(e.getStackTrace()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/file_handling/intro_file_handling.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.IOException; 3 | 4 | // package file_handling; 5 | 6 | public class intro_file_handling 7 | { 8 | public static void main(String[] args) 9 | { 10 | // Path can be relative or absolute. 11 | File obj = new File("file_handling/dummy.txt"); 12 | System.out.println(obj.getName()); 13 | System.out.println(obj.getAbsolutePath()); 14 | 15 | // Boolean attributes for files. 16 | 17 | // obj.canRead(); 18 | // obj.canWrite(); 19 | // obj.canExecute(); 20 | // obj.exists() 21 | 22 | // Print all files in directory 23 | 24 | File obj2 = new File("."); 25 | File names [] = obj2.listFiles(); 26 | 27 | for(File f: names) 28 | { 29 | System.out.println(f.getName()); 30 | } 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Java/file_handling/saved_student.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/Java/file_handling/saved_student.bin -------------------------------------------------------------------------------- /Java/file_handling/somename.txt: -------------------------------------------------------------------------------- 1 | Writing this line to the file -------------------------------------------------------------------------------- /Java/input_output/armstrong.java: -------------------------------------------------------------------------------- 1 | package input_output; 2 | 3 | import java.util.*; 4 | 5 | public class armstrong { 6 | public static void main(String argv[]) 7 | { 8 | Scanner scanner = new Scanner(System.in); 9 | int n = scanner.nextInt(); 10 | int copy_n = n; 11 | int result = 0; 12 | while(n > 0) 13 | { 14 | int dig = n % 10; 15 | result += (dig * dig * dig); 16 | n = n / 10; 17 | } 18 | if(result == copy_n) 19 | { 20 | System.out.println("Armstrong Number"); 21 | } 22 | else 23 | { 24 | System.out.println("Not armstrong Number"); 25 | } 26 | scanner.close(); 27 | } 28 | } 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Java/input_output/sort_collections.java: -------------------------------------------------------------------------------- 1 | package input_output; 2 | 3 | import java.util.*; 4 | 5 | public class sort_collections 6 | { 7 | public static void main(String[] args) 8 | { 9 | Scanner scanner = new Scanner(System.in); 10 | int n = scanner.nextInt(); 11 | ArrayList al1 = new ArrayList (); 12 | 13 | for(int i=0; i 0) 13 | { 14 | n2 = i % 10; 15 | i /= 10; 16 | } 17 | System.out.println(" " + n2 + " " + n); 18 | scanner.close(); 19 | } 20 | } -------------------------------------------------------------------------------- /Java/looping/mult_table.java: -------------------------------------------------------------------------------- 1 | package looping; 2 | 3 | import java.util.Scanner; 4 | 5 | class mult_table 6 | { 7 | public static void main(final String[] array) 8 | { 9 | Scanner scanner = new Scanner(System.in); 10 | int n = scanner.nextInt(); 11 | for (int i = 1; i <= 10; ++i) 12 | { 13 | System.out.println(" " + i + "x " + n + " " + (n * i)); 14 | } 15 | scanner.close(); 16 | } 17 | } -------------------------------------------------------------------------------- /Java/looping/sum_digits.java: -------------------------------------------------------------------------------- 1 | package looping; 2 | 3 | import java.util.Scanner; 4 | 5 | 6 | class sum_digits 7 | { 8 | public static void main(final String[] array) 9 | { 10 | Scanner scanner = new Scanner(System.in); 11 | int i = scanner.nextInt(); 12 | int n = 0; 13 | while (i > 0) 14 | { 15 | n += i % 10; 16 | i /= 10; 17 | } 18 | System.out.println(n); 19 | scanner.close(); 20 | } 21 | } -------------------------------------------------------------------------------- /Java/nested_loops/break_13.java: -------------------------------------------------------------------------------- 1 | package nested_loops; 2 | 3 | import java.util.*; 4 | 5 | public class break_13 6 | { 7 | public static void main(String[] args) 8 | { 9 | Scanner scanner = new Scanner(System.in); 10 | int lucky_num = 0; 11 | boolean is_lucky = false; 12 | for(int i=0; i<5; i++) 13 | { 14 | lucky_num = scanner.nextInt(); 15 | if(lucky_num == 13) 16 | { 17 | System.out.println("You are lucky"); 18 | is_lucky = true; 19 | break; 20 | } 21 | } 22 | if(!is_lucky) 23 | { 24 | System.out.println("Not Lucky"); 25 | } 26 | scanner.close(); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Java/nested_loops/print_nos.java: -------------------------------------------------------------------------------- 1 | package nested_loops; 2 | 3 | import java.util.*; 4 | 5 | public class print_nos 6 | { 7 | public static void main(String[] args) 8 | { 9 | Scanner scanner = new Scanner(System.in); 10 | System.out.println("Enter number of lines"); 11 | int n = scanner.nextInt(); 12 | 13 | for(int i=1; i=1; i--) 15 | { 16 | for(int j=1; j<=i; j++) 17 | { 18 | System.out.print(j); 19 | } 20 | System.out.println(); 21 | } 22 | scanner.close(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Java/nested_loops/print_rev_star.java: -------------------------------------------------------------------------------- 1 | package nested_loops; 2 | 3 | import java.util.*; 4 | 5 | public class print_rev_star 6 | { 7 | public static void main(String[] args) 8 | { 9 | Scanner scanner = new Scanner(System.in); 10 | System.out.println("Enter number of lines"); 11 | int n = scanner.nextInt(); 12 | 13 | for(int i=n; i>=1; i--) 14 | { 15 | for(int j=1; j<=i; j++) 16 | { 17 | System.out.print("*"); 18 | } 19 | System.out.println(); 20 | } 21 | scanner.close(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Java/nested_loops/print_star.java: -------------------------------------------------------------------------------- 1 | // Print this pattern for n lines   2 | 3 | // * 4 | // ** 5 | // *** 6 | // **** 7 | 8 | package nested_loops; 9 | 10 | import java.util.*; 11 | 12 | class print_star 13 | { 14 | public static void main(String[] args) 15 | { 16 | Scanner scanner = new Scanner(System.in); 17 | System.out.println("Enter number of lines"); 18 | int n = scanner.nextInt(); 19 | 20 | for(int i=1; i= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') 14 | { 15 | if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' 16 | || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') 17 | { 18 | System.out.println("Vowel"); 19 | } 20 | else 21 | { 22 | System.out.println("Consonant"); 23 | } 24 | } 25 | else 26 | { 27 | System.out.println("Not an alphabet"); 28 | } 29 | scanner.close(); 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Java/threading/child_thread.java: -------------------------------------------------------------------------------- 1 | // package threading; 2 | 3 | // Runnable interface is a type of functional interface which is designed to 4 | // provide a common protocol for objects that wish to execute code while they are active. 5 | 6 | // The Runnable interface should be implemented by any class 7 | // whose instances are intended to be executed by a thread. 8 | // The class must define a method run. It is used to create thread. 9 | 10 | // public void run(): is used to perform action for a thread. 11 | 12 | class SimpleThread4 13 | { 14 | public static void display() 15 | { 16 | System.out.println("Hello"); 17 | } 18 | 19 | } 20 | 21 | class ChildThread1 extends SimpleThread4 implements Runnable 22 | { 23 | public void run() 24 | { 25 | System.out.println("Child Thread"); 26 | } 27 | } 28 | 29 | public class child_thread 30 | { 31 | public static void main(String[] args) 32 | { 33 | ChildThread1 th = new ChildThread1(); 34 | SimpleThread4.display(); 35 | 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Java/threading/thread_yield.java: -------------------------------------------------------------------------------- 1 | // package threading; 2 | 3 | // The yield() method of thread class causes the currently executing 4 | // thread object to temporarily pause and allow other threads to execute 5 | 6 | class SimpleThread7 extends Thread 7 | { 8 | public void run() 9 | { 10 | System.out.print(Thread.currentThread().getName()); 11 | } 12 | } 13 | 14 | public class thread_yield 15 | { 16 | public static void main(String[] args) 17 | { 18 | SimpleThread7 th = new SimpleThread7(); 19 | SimpleThread7.yield(); 20 | for(int i=0; i<3; i++) 21 | { 22 | System.out.println(Thread.currentThread().getName()); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/threading/threading_intro.java: -------------------------------------------------------------------------------- 1 | // package threading; 2 | 3 | // Thread can be craeted in 2 ways 4 | // extending the Thread class 5 | // implementing the Runnable interface 6 | 7 | import java.lang.Thread; 8 | 9 | public class threading_intro { 10 | public static void main(String[] args) { 11 | Thread Thr1 = new Thread(new Runnable() { 12 | public void run() { 13 | // Thread.wait(); 14 | Thr1.wait(); 15 | } 16 | }); 17 | Thr1.start(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/threading/threading_intro2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | // Thread can be craeted in 2 ways 4 | // extending the Thread class 5 | // implementing the Runnable interface 6 | 7 | class SimpleThread extends Thread 8 | { 9 | public void run() 10 | { 11 | System.out.println("Thread is running"); 12 | } 13 | } 14 | 15 | 16 | public class threading_intro2 17 | { 18 | public static void main(String[] args) 19 | { 20 | SimpleThread newt = new SimpleThread(); 21 | newt.start(); 22 | // Cannot restart the thread again once started 23 | // newt.start(); 24 | newt.run(); 25 | newt.run(); 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Java/threading/threading_intro3.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class SimpleThread2 extends Thread 4 | { 5 | public void run() 6 | { 7 | try 8 | { 9 | System.out.println(Thread.currentThread()); 10 | } 11 | catch (Exception e) 12 | { 13 | System.out.println("Error in Thread"); 14 | } 15 | } 16 | } 17 | 18 | public class threading_intro3 19 | { 20 | public static void main(String[] args) 21 | { 22 | // int n = 5; 23 | Scanner scnaner = new Scanner(System.in); 24 | int n = scnaner.nextInt(); 25 | 26 | for(int i=0; i None: 4 | self.id = id 5 | self.fees = fees 6 | 7 | # Describe the class 8 | def __str__(self) -> str: 9 | return f"Student = {student.id} and {student.fees}" 10 | 11 | def study(self): 12 | self.state = "studying" 13 | 14 | 15 | if __name__ == "__main__": 16 | student = Student(id=1, fees=10) 17 | print(student) 18 | student.study() 19 | print(student.state) 20 | -------------------------------------------------------------------------------- /Python/basics/functions.py: -------------------------------------------------------------------------------- 1 | # def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): 2 | # ----------- ---------- ---------- 3 | # | | | 4 | # | Positional or keyword | 5 | # | - Keyword only 6 | # -- Positional only 7 | 8 | 9 | def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): 10 | pass 11 | 12 | 13 | # Lambda fn 14 | 15 | def make_incrementor(n: int): 16 | return lambda x: x + n 17 | 18 | # equivalent code 19 | 20 | if __name__ == "__main__": 21 | f = make_incrementor(10) 22 | print(f(0)) 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Python/basics/match_keyword.py: -------------------------------------------------------------------------------- 1 | def http_error(status: int) -> str: 2 | match status: 3 | case 400: 4 | return "Bad request" 5 | case 404: 6 | return "Not found" 7 | case 418: 8 | return "I'm a teapot" 9 | 10 | case 401 | 401 | 403: 11 | return "Not allowed" 12 | 13 | # Wild card in case nothing matches 14 | case _: 15 | return "Internet is broken" 16 | 17 | 18 | class Point: 19 | x: int 20 | y: int 21 | 22 | 23 | def point_matcher(point: Point) -> str: 24 | match point: 25 | case point(x=0, y=0): 26 | return "Origin" 27 | case point(x=x, y=0): 28 | return f"X axis (x) = {x}" 29 | case point(x=0, y=y): 30 | return f"Y axis (y) = {y}" 31 | case Point(): 32 | return f"X axis (x) = {x}, Y axis (y) = {y}" 33 | case _: 34 | return "Not a point" 35 | 36 | 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms 2 | 3 | - Data Structures and Algorithms practice. 4 | - Contains solutions to lot of problems commonly asked. 5 | 6 | ## Places I learnt and referred from 7 | 8 | ### YouTube Channels 9 | 10 | [Aditya Verma YouTube Channel](https://www.youtube.com/c/AdityaVermaTheProgrammingLord) 11 | 12 | [Hussein Nasser YouTube Channel](https://www.youtube.com/c/HusseinNasser-software-engineering/playlists) 13 | 14 | [Take U Forward YouTube Channel](https://www.youtube.com/channel/UCJskGeByzRRSvmOyZOz61ig/playlists) 15 | ## Questions taken from 16 | 17 | Leetcode 18 | 19 | [K Nauid's Book](https://knaidu.gitbooks.io/problem-solving/content/) 20 | 21 | -------------------------------------------------------------------------------- /hello.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | std::cout << "Hello World \n"; 5 | 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /practice: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/practice -------------------------------------------------------------------------------- /practice2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/practice2 -------------------------------------------------------------------------------- /practice4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oke-aditya/dsa/a57244314fbeb4657aed89592b0a730ae001ced1/practice4 --------------------------------------------------------------------------------