├── .gitignore ├── .vscode └── settings.json ├── 01-getting-started-with-c++ ├── 01_hello_world.cpp ├── 02_simple_interest.cpp ├── 03_sum_of_number.cpp ├── 04_sum_of_digits_of_number.cpp ├── 05_print_pattern.cpp ├── 06_input_file.txt ├── 06_output_file.txt └── 06_von_neuman_loves_binary.cpp ├── 02-programming-fundamentals-I ├── 01_fahrenheit_to_celsius.cpp ├── 02_number_divisible_by_2_3_both.cpp ├── 03_min_max_of_number.cpp ├── 04_print_number_pyramid.cpp └── 05_square_root_basic_approach.cpp ├── 03-programming-fundamentals-II ├── 01_break_and_continue.cpp ├── 02_prime_number_checker.cpp ├── 03_scope_of_variables.cpp ├── 04_cin_get_for_input.cpp ├── 05_shortest_path_string.cpp ├── 06_operators.cpp ├── 07_operators_precedence.cpp ├── 08_switch_case.cpp ├── 09_pattern_0s_and_1s.cpp ├── 10_unique_number_1.cpp ├── 11_type_conversion.cpp └── 12_buzz_fizz.cpp ├── 04-functions ├── 01_abcd_pattern.cpp ├── 02_trailing_zero.cpp ├── 03_nth_fibonacci.cpp ├── 04_all_prime.cpp └── 05_factorial_ncr.cpp ├── 05_arrays ├── 01_array_basic.cpp ├── 02_linear_search.cpp ├── 03_largest_smallest_number.cpp ├── 04_binary_search.cpp ├── 05_selection_sort.cpp ├── 06_bubble_sort.cpp ├── 07_insertion_sort.cpp ├── 08_inbuilt_sort.cpp ├── 09_comparator_understanding_the_working.cpp ├── 10_generating_subarrays.cpp ├── 11_maximum_subarray_sum1.cpp ├── 12_maximum_subarray_sum2.cpp ├── 13_maximum_subarray_sum3.cpp └── 14_two_pointer_approach_pair_sum_problem.cpp ├── 06_2D_arrays ├── 01_2D_array_basic.cpp ├── 02_wave_print.cpp ├── 03_spiral_print_2D_array.cpp ├── 04_person_with_magical_park.cpp ├── 05_rotate_image.cpp └── 06_staircase_search.cpp ├── 07_character_arrays ├── 01_character_array_basic.cpp ├── 02_reading_sentences.cpp ├── 03_palindromic_string.cpp ├── 04_string_removeconsecutive_duplicates.cpp └── 05_largest_string.cpp ├── 08_strings ├── 01_2D_chararcter_arrays.cpp ├── 01_reading_list_of_string.cpp ├── 01_string_basic.cpp ├── 02_string_class.cpp ├── 02_strlen_vs_length.cpp ├── 03_sorting.cpp ├── 04_tokenization_using_strtok.cpp ├── 05_designing_string_tokeniser.cpp └── 06_string_challenge_sort_variation.cpp ├── 09_2D_array_problems ├── 01_sum of_all_submatrix_approach_1.cpp ├── 02_sum of_all_submatrix_approach_2.cpp ├── 03_sum of_all_submatrix_approach_3.cpp ├── 04_submatrix_sum_query.cpp ├── 05_max_sum_submatrix_in_row_colwise_sorted_matrix.cpp └── 06_search_in_row_colwise_sorted_matrix.cpp ├── 10_pointers ├── 01_address_of_operator.cpp ├── 02_pointers.cpp ├── 03_dereference_operator.cpp ├── 04_pass_by_reference.cpp └── 05_reference_variable.cpp ├── 11_dynamic_memory_allocation ├── 01_type_of_memory_allocation.cpp ├── 02_using_new_delete_operator.cpp ├── 03_allocating_2d_dynamic_arrays.cpp └── 04_returning_local_vs_dynamic_arrays.cpp ├── 12_algorithms_stl ├── 01_find_finction.cpp ├── 02_binary_search_stl.cpp ├── 03_sort_function.cpp ├── 04_money_change_problem.cpp ├── 05_rotate_and_next_permutation.cpp ├── 06_some_more_methods_stl.cpp └── 07_pair_class.cpp ├── 13_binary_search_divide_&_conquer ├── 01_binary_search_on_array.cpp ├── 02_binary_search_first_&_last_occerence.cpp ├── 03_binary_search_stl.cpp ├── 04_search_in_sorted_&_rotated.cpp ├── 05_binary_search_in_monotonic_search_space.cpp ├── 06_aggressive_cows.cpp ├── 07_book_allocation.cpp ├── 08_cheese_prata.cpp ├── 09_winning_scholarship.cpp └── 10_painter_partition_problem.cpp ├── 14_bit_manipulation ├── 01_bitwise_operators.cpp ├── 02_unique_number_1.cpp ├── 03_bit_manipulation_get_n_set_bit.cpp ├── 04_bit_manipulation_clear_n_update.cpp ├── 05_bit_manipulation_clear_range_of_bits.cpp ├── 06_replace_bits_in_n_by_m.cpp ├── 07_counting_set_bits_n_optimisations.cpp ├── 08_decimal_to_binary_using_bitwise.cpp ├── 09_unique_number_II.cpp ├── 10_unique_number_III.cpp ├── 11_fast_exponentiation_using_bitmasking.cpp └── 12_generate_subsets_using_bitmasking.cpp ├── 15_number_theory_basics ├── 01_prime_sieve_or_eratosthenes_sieve.cpp ├── 02_prime_visits.cpp ├── 03_prime_factorisation_using_sieve.cpp ├── 04_prime_factorisation_using_optimised_trail_divisions.cpp ├── 05_counting_divisors.cpp ├── 06_sum_of_divisors.cpp ├── 07_large_prime_check_using_sieve.cpp ├── 08_gcd_euclid_algorithm.cpp ├── 09_modulo_properties.cpp ├── 10_divisible_subarray.cpp ├── 11_counting_problem_inclusion_exclusion_principle.cpp └── 12_not_so_easy_math_inclusion_exclusion_concept.cpp ├── 16_recursion_I_basics ├── 01_recursion_introduction.cpp ├── 02_fibonacci_recursion_n_call_stack_visualisation.cpp ├── 03_increasing_decreasing_recursion.cpp ├── 04_recursion_array_is_sorted.cpp ├── 05_recursion_binary_search.cpp └── 06_recursion_power_n_multiply.cpp ├── 17_recursion_II_implementation ├── 01_recursion_first_occurence_linear_search.cpp ├── 02_last_occurence.cpp ├── 03_all_occurence_print_n_store.cpp ├── 04_fast_power_recursion.cpp ├── 05_bubble_sort_recursion.cpp ├── 06_merge_sort.cpp ├── 07_inversion_count.cpp └── 08_quick_sort.cpp ├── 18_recursion_III_quick_thinking ├── 01_2048_problem_recursion.cpp ├── 02_string_to_integer_recursion.cpp ├── 03_replace_pi_recursion.cpp ├── 04_tiling_problem_recursion.cpp ├── 05_ladders_problem_recursion.cpp ├── 06_friends_problem.cpp ├── 07_optimal_binary_strings_recursion.cpp └── 08_tower_of_hanoi_Recursion.cpp ├── 19_recursion_IV_subset_based ├── 01_subsequences_generation_recursion.cpp ├── 02_generate_brackets_recursion.cpp ├── 03_0-1_knapsack_recursion.cpp ├── 04_phone_keypad_problem.cpp └── 05_string_generation_acode.cpp ├── 20_recursion_V_backtracking ├── 01_recursion_rat_in_maze.cpp ├── 02_permutations.cpp ├── 03_unique_permutations_using_set.cpp ├── 04_n_queen_using_backtracking.cpp ├── 05_sudoku_solver.cpp ├── 06_n_queen_using_bitset.cpp └── 07_n_queen_advance_backtracking.cpp ├── 21_more_Sorting_techniques_n_problems ├── 01_merge_sort.cpp ├── 02_inversion_count.cpp ├── 03_quick_sort.cpp ├── 04_counting_sort.cpp ├── 05_bucket_sort.cpp ├── 06_dnf_sort.cpp └── 07_wave_sort.cpp ├── 22_space_time_complexity_analysis ├── 01_space_time_complexity_introduction.cpp ├── 02_time_complexity_of_single_for_n_while_loops.cpp ├── 03_time_complexity_of_nested_loops.cpp ├── 04_time_complexity_of_loops.cpp ├── 05_time_complexity_if_condition.cpp ├── 06_time_complexity_bubble_sort.cpp ├── 07_time_complexity_binary_search.cpp ├── 08_time_complexity_using_recurrence_method.cpp ├── 09_time_complexity_of_polynomial_evaluation.cpp ├── 10_time_complexity_of_recursion.cpp ├── 11_time_complexity_exercise.cpp ├── 12_space_complexity_introduction.cpp ├── 13_space_n_time_complexity_merge_sort.cpp └── 14_space_n_time_complexity_quick_sort.cpp ├── 23_object_oriented_programming_concepts ├── 01_introduction_to_classes_n_objects.cpp ├── 02_data_members_and_functions.cpp ├── 03_getters_n_setters.cpp ├── 04_constructor_and_parameterised_constructor.cpp ├── 05_copy_constructor.cpp ├── 06_shallow _and_deep_copy.cpp ├── 07_copy_assigment_operator.cpp ├── 08_destructors.cpp ├── 09_initialization_list_n_const.cpp ├── 10_friend_class_n_function.cpp ├── 11_this_pointer_in_cpp.cpp └── 12_four_pillars_of_oops.cpp ├── 24_generic_programming_in_cpp ├── 01_generic_programming_with_templates.cpp ├── 02_stl_containers_introduction.cpp ├── 03_iterators_introduction_n_example.cpp └── 04_comparator_class.cpp ├── 25_vectors ├── 01_vectors_introduction.cpp ├── 02_vectors_methods.cpp ├── 03_using_vector.cpp ├── 04_car_sorting_problem.cpp ├── 05_container_design.cpp ├── 06_templates.cpp ├── vector.h └── vector2.h ├── 26_linked_lists ├── 01_data_structures_introduction.cpp ├── 02_linked_list_introduction.cpp ├── 03_linked_list_insertion_1.cpp ├── 04_linked_list_insertion_2.cpp ├── 05_linked_list_deletion.cpp ├── 06_linked_list_searching.cpp ├── 07_input.txt ├── 07_linked_list_taking_input.cpp ├── 08_linked_list_operator_overloading.cpp ├── 09_linked_list_reverse.cpp ├── 10_linked_list_recursive_reverse.cpp ├── 11_mid_point_runner_technique.cpp ├── 12_kth_node_from_the_end.cpp ├── 13_merge_two_sorted_linked_lists.cpp ├── 14_merge_sort.cpp ├── 15_linked_list_floyds_cycle.cpp ├── 16_doubly_linked_list_introduction.cpp ├── 17_circular_linked_list_insertion.cpp ├── 18_circular_linked_list_delete.cpp ├── 19_forward_list_stl.cpp ├── 20_list_stl_I.cpp ├── 21_list_stl_II.cpp ├── 22_list _stl_example_adjacency_list_for_weighted_graph.cpp └── 23_cpp_notes_on_linked_list.cpp ├── 27_stacks └── 01_stack_introduction.cpp ├── LICENSE ├── README.md ├── exercise_01_fundamentals ├── 01_von_neuman_loves_binary.cpp ├── 02_pythagoras_triplets.cpp ├── 03_fahrenheit_to_celsius.cpp ├── 04_simple_input.cpp ├── 05_print_series.cpp ├── 06_traffic_odd_even.cpp ├── 07_transport_fare.cpp ├── 08_counts_digits.cpp ├── 09_basic_calculator.cpp ├── 10_increase_decrease_sequence.cpp ├── 11_decimal_tooctal.cpp ├── 12_quadratic_equation.cpp ├── 13_is_armstrong_number.cpp ├── 14_check_prime.cpp ├── 15_binary_to_decimal.cpp └── 16_print_reverse.cpp ├── exercise_02_patterns ├── 01_fibonacci_pattern.cpp ├── 02_pattern_I.cpp ├── 03_pattern_II.cpp ├── 04_pattern_mountain.cpp ├── 05_pattern_with_zero.cpp ├── 06_pattern_triangle.cpp ├── 07_double_sideed_arrow.cpp ├── 08_pattern _inverted_HourGlass.cpp ├── 09_swastika_pattern.cpp ├── 10_hollow_diamond_pattern.cpp ├── 11_hollow_rhombus_pattern.cpp ├── 12_pascal_triangle_1.cpp ├── 13_pattern_and_star_1.cpp └── 14_pattern_and_star_2.cpp ├── exercise_03_arrays ├── 01_max_value_in_array.cpp ├── 02_wave_print_column_wise.cpp ├── 03_target_sum_pairs.cpp ├── 04_target_sum_triplets.cpp ├── 05_rain_water_harvesting.cpp ├── 06_maximum_subarray_sum.cpp ├── 07_maximum_circular_sum.cpp ├── 08_maximum_length_bitonic_subarray.cpp ├── 09_array_spiral_print_anticlockwise.cpp ├── 10_rotate_image_90_degree.cpp ├── 11_chewbacca_and_number.cpp ├── 12_broken_calculator.cpp ├── 13_matrix_search.cpp ├── 14_sum_of_two_arrays.cpp └── 15_median_of_sorted_array.cpp ├── exercise_04_strings ├── 01_difference_in_ascii_codes.cpp ├── 02_ultra_fast_mathematicians.cpp ├── 03_max_frequency_character.cpp ├── 04_string_compression.cpp ├── 05_is_palindrome.cpp ├── 06_max_length_substring_after_k_changes.cpp ├── 07_find_words_from_camelcase_string.cpp ├── 08_character_type.cpp ├── 09_lower_upper.cpp ├── 10_person_and_magical_park.cpp └── 11_find_csd_number.cpp ├── exercise_05_algorithms_stl ├── 01_next_permutation.cpp └── 02_activity_selection_problems.cpp ├── exercise_06_sorting_n_searching ├── 01_kth_root.cpp ├── 02_binary_search.cpp ├── 03_book_allocation_problem.cpp ├── 04_sorting_in_linear_time.cpp ├── 05_bubble_sort.cpp ├── 06_aggressive_cows.cpp ├── 07_selection_sort.cpp ├── 08_painter_problem.cpp ├── 09_counting_sort.cpp ├── 10_insertion_sort.cpp ├── 11_winning_scholarship.cpp ├── 12_string_sort.cpp ├── 13_help_aman_to_search.cpp ├── 14_find_upper_and_lower_bound.cpp ├── 15_pivot_of_sorted_and_rotated_array.cpp └── 16_sort_game.cpp ├── exercise_07_bitmasking ├── 01_playing_with_bits.cpp ├── 02_unique_number_I.cpp ├── 03_xor_profit_problem.cpp ├── 04_count_set_bits.cpp ├── 05_unique_number_II.cpp ├── 06_unique_number_III.cpp ├── 07_incredible_hulk.cpp └── 08_power.cpp ├── exercise_08_number_theory ├── 01_modular_exponentiation.cpp ├── 02_raman_and_primes.cpp ├── 03_gcd.cpp ├── 04_amit_loves_candy.cpp ├── 05_divisible_subarray.cpp ├── 06_lcm.cpp └── 07_prime_visits.cpp ├── exercise_10_space_time_complexity └── 01_exercise_time_space_complexity.pdf ├── misc ├── QnA.cpp ├── array_rotation.cpp ├── binary_search.cpp ├── linear_search.c ├── reverse_elements_of_array.cpp └── tower_of_hanoi.cpp └── misc_js ├── approach.md ├── array.js ├── links.txt └── misc.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # custom files 35 | template.txt 36 | 37 | #ide 38 | .vscode 39 | 40 | #directory 41 | /practice 42 | 43 | .DS_Store -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "climits": "cpp", 4 | "array": "cpp", 5 | "atomic": "cpp", 6 | "bit": "cpp", 7 | "*.tcc": "cpp", 8 | "cctype": "cpp", 9 | "clocale": "cpp", 10 | "cmath": "cpp", 11 | "cstdarg": "cpp", 12 | "cstddef": "cpp", 13 | "cstdint": "cpp", 14 | "cstdio": "cpp", 15 | "cstdlib": "cpp", 16 | "cwchar": "cpp", 17 | "cwctype": "cpp", 18 | "deque": "cpp", 19 | "unordered_map": "cpp", 20 | "vector": "cpp", 21 | "exception": "cpp", 22 | "algorithm": "cpp", 23 | "functional": "cpp", 24 | "iterator": "cpp", 25 | "memory": "cpp", 26 | "memory_resource": "cpp", 27 | "numeric": "cpp", 28 | "optional": "cpp", 29 | "random": "cpp", 30 | "string": "cpp", 31 | "string_view": "cpp", 32 | "system_error": "cpp", 33 | "tuple": "cpp", 34 | "type_traits": "cpp", 35 | "utility": "cpp", 36 | "fstream": "cpp", 37 | "initializer_list": "cpp", 38 | "iosfwd": "cpp", 39 | "iostream": "cpp", 40 | "istream": "cpp", 41 | "limits": "cpp", 42 | "new": "cpp", 43 | "ostream": "cpp", 44 | "sstream": "cpp", 45 | "stdexcept": "cpp", 46 | "streambuf": "cpp", 47 | "typeinfo": "cpp", 48 | "cstring": "cpp", 49 | "bitset": "cpp", 50 | "set": "cpp" 51 | }, 52 | "cmake.configureOnOpen": false 53 | } -------------------------------------------------------------------------------- /01-getting-started-with-c++/01_hello_world.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This is a 3 | multi line comment 4 | */ 5 | 6 | #include // header file 7 | using namespace std; // standard c++ namespace 8 | 9 | int main(int argc, char const *argv[]){ //start 10 | cout<<"Hello World"< Implicit 7 | Eg:- integer/integer = integer 8 | float/integer = float 9 | integer/float = float 10 | 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | int main(){ 17 | 18 | // Declare a variable 19 | int principle, rate, time; 20 | float si; 21 | 22 | cout<<"Enter Principle, Rate & Time : "; 23 | 24 | // Taking input from console & assigning value to a buckets (storage in memory) 25 | cin>>principle>>rate>>time; // 26 | 27 | si = (principle*rate*time)/100.0; 28 | 29 | cout<<"Simple Interset = "< 10 | using namespace std; 11 | 12 | int main(){ 13 | int num, sum=0; 14 | 15 | cout<<"Enter the number: "; 16 | cin>>num; 17 | 18 | while (num > 0){ // Stopping Criteria 19 | sum = sum + num; 20 | num --; // Update Statement 21 | } 22 | 23 | cout<<"Sum of numbers = "< Remainder 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | int main(){ 12 | int num, sum=0; 13 | 14 | cout<<"Enter the number: "; 15 | cin>>num; 16 | 17 | while(num > 0){ 18 | sum = sum + (num%10); 19 | num = num/10; 20 | } 21 | 22 | cout<<"Sum of digits = "< 14 | using namespace std; 15 | 16 | int main(){ 17 | int rows, col, step = 1; 18 | 19 | cout<<"Enter the rows: "; 20 | cin>>rows; 21 | 22 | while (step <= rows){ 23 | col = 1; 24 | if(step%2 != 0){ 25 | while(col <= step){ 26 | cout<<"1"; 27 | col++; 28 | } 29 | }else{ 30 | cout<<1; 31 | while(col <= step-2){ 32 | cout<<"0"; 33 | col++; 34 | } 35 | cout<<1; 36 | } 37 | step++; 38 | cout< output_file.txt 7 | 8 | */ 9 | #include 10 | using namespace std; 11 | 12 | int main(){ 13 | int total_values, binary_number, decimal_number, power; 14 | 15 | cin>>total_values; 16 | 17 | while(total_values > 0){ 18 | decimal_number = 0; 19 | power = 1; 20 | cin>>binary_number; 21 | while(binary_number > 0){ 22 | decimal_number = decimal_number + (power * (binary_number%10)); 23 | binary_number = binary_number/10; 24 | power = power * 2; 25 | } 26 | cout< 21 | using namespace std; 22 | 23 | int main(){ 24 | int fahren_value = 0, celsius_value; 25 | 26 | while(fahren_value <= 200){ 27 | celsius_value = (5*(fahren_value - 32))/9; 28 | // Catch: don't do 5/9(fahren_value - 32) 29 | cout< 9 | using namespace std; 10 | 11 | int main(){ 12 | int num; 13 | 14 | cout<<"Enter the Number :"; 15 | cin>>num; 16 | 17 | if(num%2 == 0 and num%3 ==0){ 18 | cout<<"Number divisible by both 2 & 3"< 6 | #include 7 | using namespace std; 8 | 9 | int main(){ 10 | int total_num, num, min_so_far, max_so_far; 11 | 12 | cout<<"Enter total numbers : "; 13 | cin>>total_num; 14 | 15 | max_so_far = INT_MIN; 16 | min_so_far = INT_MAX; 17 | 18 | while(total_num > 0){ 19 | cin>>num; 20 | if(num < min_so_far){ 21 | min_so_far = num; 22 | } 23 | if(num > max_so_far){ 24 | max_so_far = num; 25 | } 26 | total_num--; 27 | } 28 | 29 | cout<<"Minimum Number: "< 11 | using namespace std; 12 | 13 | int main(){ 14 | int total_rows, row=1, col, value=0; 15 | 16 | cout<<"Enter total number of rows: "; 17 | cin>>total_rows; 18 | 19 | while(row <= total_rows){ 20 | //Print Spaces 21 | col = total_rows-row; 22 | while(col > 0){ 23 | cout<<" "; 24 | col--; 25 | } 26 | 27 | //Print Increasing Values 28 | col = row; 29 | while(col>0){ 30 | value++; 31 | cout<0){ 38 | value--; 39 | cout< 12 | #include 13 | using namespace std; 14 | 15 | int main(){ 16 | int number, precision; 17 | cout<<"Enter the number: "; 18 | cin>>number; 19 | cout<<"Enter the precision: "; 20 | cin>>precision; 21 | 22 | float ans = 0; 23 | float inc = 1.0; 24 | 25 | while(precision >=0){ 26 | // Finalize the correct digit for correct place 27 | while(ans*ans <= number){ 28 | ans = ans + inc; 29 | } 30 | ans = ans-inc; 31 | // Update the increment for the next precision position 32 | inc = inc/10; 33 | precision--; 34 | } 35 | 36 | cout< 11 | using namespace std; 12 | 13 | int main(){ 14 | int num; 15 | 16 | while(true){ 17 | // No Stopping Condition as of now 18 | cout<<"Enter number: "; 19 | cin>>num; 20 | 21 | if(num%2 == 0){ 22 | continue; // stops processing further & take you out to line 16 (i.e staring of loop) 23 | } 24 | if(num%3 == 0){ 25 | break; // stops processing further & take you out to line 30 26 | } 27 | cout<<"No: "< 6 | using namespace std; 7 | 8 | int main(){ 9 | int num, checker; 10 | cout<<"Enter the number: "; 11 | cin>>num; 12 | 13 | for(checker=2;checker defined for variable (accessibile) 3 | 4 | Two type of scope in c++:- 5 | - Local Scope (inside curly brackets {}) 6 | - Global Scope 7 | 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | // Global Scope 14 | int var = 100; 15 | 16 | int main(){ 17 | // Local Scope 18 | int var = 10; 19 | cout< Input Buffer -> 9 | Loop 10 | "Output" on console <- Output Buffer <- 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | int main(){ 17 | char character; 18 | cout<<"**** Enter your Characters ****"<>character; 23 | 24 | while(character != '.'){ 25 | // Print the last character that we have read 26 | cout<>character; 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /03-programming-fundamentals-II/05_shortest_path_string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Problem - Find the displacement N ^ 4 | | 5 | Input String: NNNSSEEWE | 6 | Output : NEE | 7 | W<-------o------->E 8 | (0,0)| 9 | | 10 | | 11 | S v 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | int main(){ 18 | char path; 19 | int x=0, y=0; 20 | 21 | cout<<"Enter your path: "; 22 | path = cin.get(); 23 | 24 | while (path != '\n'){ 25 | if(path == 'N' or path == 'n'){ 26 | y++; 27 | } 28 | else if(path == 'S' or path == 's'){ 29 | y--; 30 | } 31 | else if(path == 'E' or path == 'e'){ 32 | x++; 33 | } 34 | else if(path == 'W' or path == 'w'){ 35 | x--; 36 | } 37 | path = cin.get(); 38 | } 39 | 40 | cout<<"Final Displacement: x="<< x<<" y="<0){ 44 | while(x>0){ 45 | cout<<"E"; 46 | x--; 47 | } 48 | }else{ 49 | while(x<0){ 50 | cout<<"W"; 51 | x++; 52 | } 53 | } 54 | if(y>0){ 55 | while(y>0){ 56 | cout<<"N"; 57 | y--; 58 | } 59 | }else{ 60 | while(y<0){ 61 | cout<<"S"; 62 | y++; 63 | } 64 | } 65 | cout< 6 | using namespace std; 7 | 8 | int main(){ 9 | int digits=0; 10 | int alphabets=0; 11 | int spaces=0; 12 | int other=0; 13 | 14 | char ch; 15 | cout<<"Enter you characters :"; 16 | ch = cin.get(); // Note: If you want to read spaces then use cin.get() 17 | // cin>>ch; 18 | 19 | while(ch!='$'){ 20 | if(ch>='0' and ch<='9'){ 21 | digits++; 22 | } 23 | else if((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')){ 24 | alphabets++; 25 | } 26 | else if(ch==' ' or ch=='\n' or ch=='\t'){ 27 | spaces++; 28 | } 29 | else{ 30 | other++; 31 | } 32 | ch = cin.get(); // Note: If you want to read spaces then use cin.get() 33 | // cin>>ch; 34 | } 35 | 36 | cout<<"Digits :"< 14 | using namespace std; 15 | 16 | int main(){ 17 | char ch; 18 | cout<<"Enter you option: "; 19 | cin>>ch; 20 | 21 | switch(ch){ 22 | case 'b': 23 | case 'B': cout<<"Burger"< 18 | using namespace std; 19 | 20 | int main(){ 21 | int total_rows, row, col; 22 | 23 | cout<<"Enter total number of rows :"; 24 | cin>>total_rows; 25 | 26 | for(row=1; row<=total_rows; row++){ 27 | int value = row%2!=0?0:1; 28 | 29 | // Print i rows in ith line 30 | for(col=1; col<=row; col++){ 31 | cout< 10 | using namespace std; 11 | 12 | int main(){ 13 | int total_num, num, ans=0; 14 | 15 | cout<<"Enter total numbers: "; 16 | cin>>total_num; 17 | cout<<"Enter you numbers: "; 18 | 19 | for(int step=0; step>num; 21 | ans = ans^num; //Bitwise XOR Operator to solve, It helped to not use any storage 22 | } 23 | 24 | cout<<"Unique No. is : "< 17 | using namespace std; 18 | 19 | int main() 20 | { 21 | for(int num=1; num<=100; num++) 22 | { 23 | if(num%15 == 0) 24 | { 25 | cout << "FizzBuzz, "; 26 | } 27 | else if(num%3 == 0) 28 | { 29 | cout << "Fizz, "; 30 | } 31 | else if(num%5 == 0) 32 | { 33 | cout << "Buzz, "; 34 | } 35 | else 36 | { 37 | cout << num << ", "; 38 | } 39 | } 40 | return 0; 41 | } 42 | 43 | 44 | /* 45 | OUTPUT: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 46 | 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 47 | 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 48 | 46, 47, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 49 | 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz, 50 | 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86, Fizz, 88, 89, FizzBuzz, 51 | 91, 92, Fizz, 94, Buzz, Fizz, 97, 98, Fizz, Buzz, 52 | 53 | Reference: [For Optimised Version] - https://www.enjoyalgorithms.com/blog/fizz-buzz-problem 54 | */ 55 | -------------------------------------------------------------------------------- /04-functions/01_abcd_pattern.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ABCD Pattern Function 3 | 4 | Print the following pattern for given N=5 5 | ABCDE 6 | ABCD 7 | ABC 8 | AB 9 | A 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | void printABCDPattern(int total_rows) 16 | { 17 | // int alphabet_count = total_rows; 18 | for (int row = 1; row <= total_rows; row++) 19 | { 20 | int alphabet_count = total_rows - row + 1; 21 | char alphabet = 'A'; 22 | for (int col = 1; col <= alphabet_count; col++) 23 | { 24 | cout << alphabet; 25 | alphabet++; 26 | } 27 | // alphabet_count--; 28 | cout << endl; 29 | } 30 | } 31 | 32 | int main() 33 | { 34 | int rows; 35 | cout << "Enter the number of rows for ABCD Pattern: "; 36 | cin >> rows; 37 | printABCDPattern(rows); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /04-functions/02_trailing_zero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Trailing Zero Function 3 | 4 | Given a interger n, write a function that return count of trailing zeros in n! 5 | 6 | Constraint: 1 <= N <= 10^9 7 | 8 | Input: A single interger N 9 | 10 | Output: A single interger denoting the count of trailing zero's in N! 11 | 12 | Sample Input: 5 13 | 14 | Sample Output: 1 15 | 16 | Explanation: Factorial of 5 is 120 which has one trailing zero. 17 | 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | 23 | int findZeros(int number) 24 | { 25 | int divisor; 26 | int ans = 0; 27 | 28 | for (divisor = 5; number / divisor >= 1; divisor *= 5) 29 | { 30 | ans += number / divisor; 31 | } 32 | return ans; 33 | } 34 | 35 | int main() 36 | { 37 | long long int number; 38 | 39 | cout << "Enter to number: "; 40 | cin >> number; 41 | 42 | cout << findZeros(number) << endl; 43 | return 0; 44 | } 45 | 46 | /* 47 | Formula to calculate power of a number "D" present in N! :- 48 | 49 | N/D + N/D^2 + N/D^3 + ---------- until it is greater than zero 50 | */ -------------------------------------------------------------------------------- /04-functions/03_nth_fibonacci.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Nth Fibonacci Function 3 | 0, 1, 1, 2, 3, 5, 8, 13 ... 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | int fibonacci(int num) 10 | { 11 | int first = 0; 12 | int second = 1; 13 | int curr = 0; 14 | 15 | for (int index = 1; index <= num; index++) 16 | { 17 | if (index == 1){ 18 | curr = first; 19 | } 20 | else if (index == 2){ 21 | curr = second; 22 | } 23 | else{ 24 | curr = first + second; 25 | first = second; 26 | second = curr; 27 | } 28 | } 29 | return curr; 30 | } 31 | 32 | int main() 33 | { 34 | int num; 35 | cout << "Enter the number: "; 36 | cin >> num; 37 | 38 | cout << fibonacci(num) < 6 | using namespace std; 7 | 8 | // check if number is prime 9 | bool isPrime(int num) 10 | { 11 | for (int index = 2; index < num; index++){ 12 | if (num % index == 0){ 13 | return false; 14 | } 15 | } 16 | return true; 17 | } 18 | 19 | // print all prime numbers 20 | void printPrime(int range) 21 | { 22 | for(int num = 2; num <= range; num++){ 23 | if(isPrime(num)) 24 | cout << num << " "; 25 | } 26 | cout << endl; 27 | } 28 | 29 | int main() 30 | { 31 | int num; 32 | cout << "Enter the range: "; 33 | cin >> num; 34 | 35 | printPrime(num); 36 | } -------------------------------------------------------------------------------- /04-functions/05_factorial_ncr.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Calculate the nCr. 3 | 4 | C(n,r) = ____n!_____ where n = the set or population 5 | r!(n-r)! r = subset or sample set 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | int factorial(int num){ 12 | int ans = 1; 13 | for (int seq = 1; seq<=num; seq++){ 14 | ans = ans*seq; 15 | } 16 | return ans; 17 | } 18 | 19 | int nCr(int n, int r){ 20 | int ans = factorial(n) / (factorial(r)*factorial(n-r)); 21 | return ans; 22 | } 23 | 24 | int main(){ 25 | int n ,r; 26 | cout << "Enter values of n & r to calculate nCr: "; 27 | cin >> n >> r; 28 | 29 | cout << nCr(n,r) << endl; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /05_arrays/01_array_basic.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Array basics 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | // create array 11 | int arr[] = {9, 55}; // array declaration & initilizations 12 | cout << "Elements in array: " << sizeof(arr)/sizeof(int) << endl; 13 | 14 | 15 | // create array 16 | int arr1[10]; // array declaration 17 | int arr2[10] = {5}; // array declaration & initilizations 18 | 19 | // size of array 20 | cout << "Size of array: " << sizeof(arr1) << endl; 21 | int arr_total_elements = sizeof(arr1) / sizeof(int); 22 | cout << "Total elements in array: " << arr_total_elements << endl; 23 | 24 | // Adding 5 elements in array by user 25 | cout << "Enter 5 elements in array: "; 26 | for(int index = 0 ; index < 5; index++){ 27 | cin >> arr1[index]; 28 | } 29 | 30 | // update a single index 31 | arr2[5] = 56; 32 | 33 | // print array 34 | for(int index = 0 ; index < arr_total_elements; index++){ 35 | cout << arr1[index] << " "; // arr1 with remaining values as garbage values 36 | } 37 | cout << endl; 38 | for(int index = 0 ; index < arr_total_elements; index++){ 39 | cout << arr2[index] << " "; // arr2 with remaining values as zeros 40 | } 41 | cout << endl; 42 | 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /05_arrays/02_linear_search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Linear Search Algorithm 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main(){ 9 | int range, key; 10 | int arr[1000]; 11 | 12 | cout << "How many elements you want to enter in array: "; 13 | cin >> range; 14 | 15 | cout << "Enter array elements: "; 16 | for (int index=0; index> arr[index]; 18 | } 19 | //Ask for the element we want to search 20 | cout << "Enter the key you want to search: "; 21 | cin >> key; 22 | 23 | // Find out the index of that element by traversing the array 24 | // Linear Search Algorithm 25 | int index; 26 | for(index=0; index 6 | #include 7 | using namespace std; 8 | 9 | int main(){ 10 | int range; 11 | cout << "How many elements you want to enter: "; 12 | cin >> range; 13 | 14 | int arr[100]; 15 | cout << "Enter array elements: "; 16 | for(int index=0; index> arr[index]; 18 | } 19 | 20 | int smallest = INT_MAX; 21 | int largest = INT_MIN; 22 | 23 | for(int index=0; indexlargest){ 25 | largest = arr[index]; 26 | } 27 | if(arr[index] 7 | using namespace std; 8 | 9 | int binary_search(int arr[], int range, int key) 10 | { 11 | int start = 0; 12 | int end = range; 13 | 14 | while (start <= end) 15 | { 16 | int mid = (start + end) / 2; // calculating the middle value 17 | 18 | if (arr[mid] == key) 19 | { 20 | return mid; 21 | } 22 | else if (arr[mid] > key) 23 | { 24 | end = mid - 1; 25 | } 26 | else 27 | { 28 | start = mid + 1; 29 | } 30 | } 31 | return -1; 32 | } 33 | 34 | int main() 35 | { 36 | int range, key; 37 | int arr[1000]; 38 | 39 | cout << "How many elements you want to enter inside array: "; 40 | cin >> range; 41 | 42 | cout << "Enter the array elemets in sorted order: "; 43 | for (int index = 0; index < range; index++){ 44 | cin >> arr[index]; 45 | } 46 | //Ask for the element we want to search 47 | cout << "Enter the value to search: "; 48 | cin >> key; 49 | 50 | int index = binary_search(arr, range, key); // searching the value 51 | 52 | if (index == -1){ 53 | cout << key << " is not present" << endl; 54 | }else{ 55 | cout << key << " is present at " << index << endl; 56 | } 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /05_arrays/05_selection_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Selection Sort 3 | Arrange a randomly shuffled array in increasing & descreasing order. 4 | 5 | The selection sort algorithm sorts an array by repeatedly finding the minimum element 6 | from unsorted part and putting it at the beginning of unsorted array. 7 | The algorithm maintains two subarrays in a given array. 8 | 1) The subarray which is already sorted. 9 | 2) Remaining subarray which is unsorted. 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | // function to print array 16 | void print_array(int arr[], int range){ 17 | for (int index = 0; index < range; index++) 18 | { 19 | cout << arr[index] << " "; 20 | } 21 | cout << endl; 22 | } 23 | 24 | // selection sort 25 | void selection_sort(int arr[], int range) 26 | { 27 | // loop for moving boundary of unsorted array 28 | for (int i=0; i <= range-2; i++) 29 | { 30 | // find out the smallest index in unsorted part 31 | int min_index = i; 32 | for (int j = i+1; j<=range-1; j++) 33 | { 34 | if (arr[j] < arr[min_index]) 35 | { 36 | min_index = j; 37 | } 38 | } 39 | // We are only doing swap outside the loop because swap is a costly function. 40 | int temp = arr[i]; 41 | arr[i] = arr[min_index]; // Swap first element with the min value 42 | arr[min_index] = temp; 43 | 44 | // print array 45 | cout << "Step " << i+1 << " : "; 46 | print_array(arr, range); 47 | } 48 | } 49 | 50 | // funtion to drive code 51 | int main() 52 | { 53 | int range; 54 | int arr[1000]; 55 | 56 | cout << "How many elements you want to enter inside array: "; 57 | cin >> range; 58 | 59 | // Taking array values from user 60 | cout << "Enter the array elements for sorting: "; 61 | for (int index = 0; index < range; index++){ 62 | cin >> arr[index]; 63 | } 64 | 65 | // Sorting array 66 | selection_sort(arr, range); 67 | 68 | // print the sorted array 69 | cout << "Sorted Array: "; 70 | print_array(arr, range); 71 | 72 | return 0; 73 | } 74 | 75 | /* 76 | OUTPUT: 77 | How many elements you want to enter inside array: 5 78 | Enter the array elements for sorting: 5 1 4 3 2 79 | 80 | Step 1 : 1 5 4 3 2 81 | Step 2 : 1 2 4 3 5 82 | Step 3 : 1 2 3 4 5 83 | Step 4 : 1 2 3 4 5 84 | 85 | Sorted Array: 1 2 3 4 5 86 | */ -------------------------------------------------------------------------------- /05_arrays/06_bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Bubble Sort 3 | Take the largest element towards end! (Pairwise swapping) 4 | */ 5 | #include 6 | using namespace std; 7 | 8 | // function to print array 9 | void print_array(int arr[], int range){ 10 | for (int index = 0; index < range; index++) 11 | { 12 | cout << arr[index] << " "; 13 | } 14 | cout << endl; 15 | } 16 | 17 | // bubble sort 18 | void bubble_sort(int arr[], int range) 19 | { 20 | // iteration count 21 | for (int step = 1; step < range; step++) 22 | { 23 | // iterating unsorted array 24 | for (int idx=0; idx < (range-step); idx++) // [range-step] -> To decrease length of unsorted array from the end. 25 | { 26 | // pairwise swapping 27 | if (arr[idx] > arr[idx + 1]) 28 | { 29 | swap(arr[idx], arr[idx + 1]); 30 | } 31 | } 32 | 33 | // print array 34 | cout << "Step " << step << " : "; 35 | print_array(arr, range); 36 | } 37 | } 38 | 39 | // funtion to drive code 40 | int main() 41 | { 42 | int range; 43 | int arr[1000]; 44 | 45 | cout << "How many elements you want to enter inside array: "; 46 | cin >> range; 47 | 48 | // Taking array values from user 49 | cout << "Enter the array elements for sorting: "; 50 | for (int index = 0; index < range; index++) 51 | { 52 | cin >> arr[index]; 53 | } 54 | 55 | // Sorting array 56 | bubble_sort(arr, range); 57 | 58 | // print the sorted array 59 | cout << "Sorted Array: "; 60 | print_array(arr, range); 61 | 62 | return 0; 63 | } 64 | 65 | /* 66 | OUTPUT: 67 | 68 | How many elements you want to enter inside array: 5 69 | Enter the array elements for sorting: 5 1 4 3 2 70 | 71 | Step 1 : 1 4 3 2 5 72 | Step 2 : 1 3 2 4 5 73 | Step 3 : 1 2 3 4 5 74 | Step 4 : 1 2 3 4 5 75 | 76 | Sorted Array: 1 2 3 4 5 77 | */ -------------------------------------------------------------------------------- /05_arrays/07_insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Insertion Sort 3 | Insert the "current" element in right position 4 | 5 | The array is virtually split into a sorted and an unsorted part. 6 | Values from the unsorted part are picked and placed at the correct position in the sorted part. 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | // function to print array 13 | void print_array(int arr[], int range){ 14 | for (int index = 0; index < range; index++) 15 | { 16 | cout << arr[index] << " "; 17 | } 18 | cout << endl; 19 | } 20 | 21 | // insertion sort 22 | void insertion_sort(int arr[], int range) 23 | { 24 | // iteration for sorted array 25 | for(int itr=1; itr<=range-1; itr++) 26 | { 27 | int curr = arr[itr]; 28 | // placing "current" element on right position in sorted array 29 | int index = itr-1; 30 | while(arr[index]>curr and index>=0){ 31 | arr[index+1] = arr[index]; 32 | index--; 33 | } 34 | arr[index+1] = curr; 35 | 36 | // print array 37 | cout << "Step " << itr << " : "; 38 | print_array(arr, range); 39 | } 40 | } 41 | 42 | // funtion to drive code 43 | int main() 44 | { 45 | int range; 46 | int arr[1000]; 47 | 48 | cout << "How many elements you want to enter inside array: "; 49 | cin >> range; 50 | 51 | // Taking array values from user 52 | cout << "Enter the array elements for sorting: "; 53 | for (int index = 0; index < range; index++) 54 | { 55 | cin >> arr[index]; 56 | } 57 | 58 | // Sorting array 59 | insertion_sort(arr, range); 60 | 61 | // print the sorted array 62 | cout << "Sorted Array: "; 63 | print_array(arr, range); 64 | 65 | return 0; 66 | } 67 | 68 | /* 69 | OUTPUT: 70 | 71 | How many elements you want to enter inside array: 5 72 | Enter the array elements for sorting: 5 2 3 4 1 73 | 74 | Step 1 : 2 5 3 4 1 75 | Step 2 : 2 3 5 4 1 76 | Step 3 : 2 3 4 5 1 77 | Step 4 : 1 2 3 4 5 78 | 79 | Sorted Array: 1 2 3 4 5 80 | */ -------------------------------------------------------------------------------- /05_arrays/08_inbuilt_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Inbuilt sort in C++ Standard Template Library 3 | 4 | - Sorting a array using sort() function of C++ STL is more effective than selection, bubble & insertion sort. 5 | */ 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | //Define a comparator function 12 | bool compare(int a, int b){ 13 | return a > b; 14 | } 15 | 16 | int main() 17 | { 18 | int range; 19 | int arr[1000]; 20 | 21 | cout << "How many elements you want to enter inside array: "; 22 | cin >> range; 23 | 24 | // Taking array values from user 25 | cout << "Enter the array elements for sorting: "; 26 | for (int index = 0; index < range; index++) 27 | { 28 | cin >> arr[index]; 29 | } 30 | 31 | // Inbuit - Sorting function 32 | sort(arr, arr+range, compare); 33 | 34 | // print the sorted array 35 | cout << "Sorted Array: "; 36 | for (int index = 0; index < range; index++) 37 | { 38 | cout << arr[index] << " "; 39 | } 40 | cout << endl; 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /05_arrays/09_comparator_understanding_the_working.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Comparator - understanding the working 3 | - Add a comparator function in bubble sort method 4 | - Alter bubble sort function to accept function 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | bool compare(int val1, int val2){ // comparator function 11 | return val1 > val2; 12 | } 13 | 14 | void bubble_sort(int arr[], int range, bool (&cmp) (int val1, int val2)) 15 | { 16 | // iteration count 17 | for (int itr = 1; itr < range; itr++) 18 | { 19 | // iterating unsorted array 20 | for (int index = 0; index < range - itr; index++) 21 | { 22 | // parewise swapping 23 | if (cmp(arr[index], arr[index + 1])) // using compare function 24 | { 25 | swap(arr[index], arr[index + 1]); 26 | } 27 | } 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | int range; 34 | int arr[1000]; 35 | 36 | cout << "How many elements you want to enter inside array: "; 37 | cin >> range; 38 | 39 | // Taking array values from user 40 | cout << "Enter the array elements for sorting: "; 41 | for (int index = 0; index < range; index++) 42 | { 43 | cin >> arr[index]; 44 | } 45 | 46 | // Sorting array 47 | bubble_sort(arr, range, compare); // Function as Parameter 48 | 49 | // print the sorted array 50 | cout << "Sorted Array: "; 51 | for (int index = 0; index < range; index++) 52 | { 53 | cout << arr[index] << " "; 54 | } 55 | cout << endl; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /05_arrays/10_generating_subarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Generating Subarrays 3 | >> Given a aray, print all the subarrays 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | void subarrays(int arr[], int range){ 10 | cout << "Subarrays :- \n"; 11 | // Generating all subarays 12 | for(int start=0; start> range; 27 | 28 | cout << "Enter values: "; 29 | for(int itr=0; itr>arr[itr]; 31 | } 32 | 33 | subarrays(arr, range); 34 | 35 | return 0; 36 | } 37 | 38 | /* 39 | OUTPUT: 40 | Enter total elements: 5 41 | 42 | Enter values: 1 2 3 4 5 43 | 44 | Subarrays :- 45 | 1, 46 | 1,2, 47 | 1,2,3, 48 | 1,2,3,4, 49 | 1,2,3,4,5, 50 | 2, 51 | 2,3, 52 | 2,3,4, 53 | 2,3,4,5, 54 | 3, 55 | 3,4, 56 | 3,4,5, 57 | 4, 58 | 4,5, 59 | 5, 60 | */ -------------------------------------------------------------------------------- /05_arrays/11_maximum_subarray_sum1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Largest/maxmimum subarrays sum I 3 | (using brute force) - 3 Nesting loop 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | void subarrays(int arr[], int range){ 10 | int maxSum = 0; 11 | int left = -1; // for storing maximum subarray left index 12 | int right = -1; // for storing maximum subarray right index 13 | 14 | for(int start=0; start maximumSum 24 | if(currentSum > maxSum){ 25 | maxSum = currentSum; 26 | left = start; 27 | right = end; 28 | } 29 | } 30 | } 31 | // print the maximum sum 32 | cout << "Maximun Sum: " << maxSum << endl; 33 | 34 | // print the subarray 35 | cout << "Subarray having Maximum Sum: "; 36 | for(int k=left; k<=right; k++){ 37 | cout << arr[k] << ","; 38 | } 39 | cout << endl; 40 | } 41 | 42 | 43 | int main(){ 44 | int arr[100], range; 45 | cout << "Enter total elements: "; 46 | cin >> range; 47 | 48 | cout << "Enter values: "; 49 | for(int itr=0; itr>arr[itr]; 51 | } 52 | 53 | subarrays(arr, range); 54 | 55 | return 0; 56 | } 57 | 58 | 59 | /* 60 | OUTPUT: 61 | Enter total elements: 9 62 | Enter values: -4 1 3 -2 6 2 -1 -4 -7 63 | 64 | Maximun Sum: 10 65 | Subarray having Maximum Sum: 1,3,-2,6,2, 66 | */ -------------------------------------------------------------------------------- /05_arrays/13_maximum_subarray_sum3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Largest/maxmimum subarrays sum III 3 | (Kadane's Algorithm) - 1 loop 4 | 5 | Eg: Array : -4 1 3 -2 6 2 -1 -4 -7 6 | Current Sum : 0 1 4 2 8 10 9 5 0 7 | Max Sum : 0 1 4 4 8 10 10 10 10 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | void subarrays(int arr[], int range){ 14 | int currentSum = 0; 15 | int maxSum = 0; 16 | 17 | // Using Kadane's Algorithm 18 | for(int i=0; i> range; 35 | 36 | cout << "Enter values: "; 37 | for(int itr=0; itr>arr[itr]; 39 | } 40 | 41 | subarrays(arr, range); 42 | 43 | return 0; 44 | } 45 | 46 | /* 47 | OUTPUT: 48 | Enter total elements: 9 49 | Enter values: -4 1 3 -2 6 2 -1 -4 -7 50 | Maximun Sum: 10 51 | */ -------------------------------------------------------------------------------- /05_arrays/14_two_pointer_approach_pair_sum_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pair Sum Problem (Two Pointer Approach) 3 | 4 | >> Given a sorted array, Find pair of elements that sum to k(Given) 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | // int arr[] = {1,3,5,7,10,11,12,13}; 12 | int arr[] = {1,3,4,5,7,10,11,12,13}; // Remember array must be sorted 13 | int k=16; 14 | 15 | int i = 0; // "i" is pointing at array beginning 16 | int j = (sizeof(arr)/sizeof(int))-1; // "j" is pointing at last 17 | 18 | while(i k){ 25 | j--; 26 | }else{ 27 | i++; 28 | } 29 | } 30 | 31 | return 0; 32 | } 33 | 34 | /* 35 | 36 | OUTPUT: 3 and 13 37 | 4 and 12 38 | 5 and 11 39 | */ -------------------------------------------------------------------------------- /06_2D_arrays/01_2D_array_basic.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 2D Array Basic 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main(){ 9 | int arr[4][3] = {0,4,5,7}; // 2D-Array 1 10 | 11 | cout << "arr[4][3] = {0,4,5,7}" <> m >> n; // user input 24 | int val=1; 25 | // Iterate over array 26 | for(int row=0; row<=m-1; row++){ 27 | for(int col=0; col<=n-1; col++){ 28 | arr[row][col] = val; // assigning values 29 | val++; 30 | cout << arr[row][col] << " "; 31 | } 32 | cout << endl; 33 | } 34 | 35 | return 0; 36 | } 37 | 38 | /* 39 | OUTPUT: 40 | 41 | arr[4][3] = {0,4,5,7} 42 | 0 4 5 43 | 7 0 0 44 | 0 0 0 45 | 0 0 0 46 | 47 | Enter Row & Col for 2D-Array: 3 3 48 | 1 2 3 49 | 4 5 6 50 | 7 8 9 51 | */ -------------------------------------------------------------------------------- /06_2D_arrays/02_wave_print.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Wave Print of 2D Array 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main(){ 9 | int arr[1000][1000] = {0}; 10 | int rows, cols; 11 | cout << "Enter Array Rows & Cols: "; 12 | cin >> rows >> cols; 13 | 14 | int val=1; 15 | for(int row=0; row=0; row--){ 34 | cout << arr[row][col] << " "; 35 | } 36 | } 37 | cout << " "; 38 | } 39 | cout << endl; 40 | 41 | return 0; 42 | } 43 | 44 | /* 45 | OUTPUT: 46 | 47 | Case1: 48 | Enter Array Rows & Cols: 3 3 49 | 1 2 3 50 | 4 5 6 51 | 7 8 9 52 | Wave Print: 1 4 7 8 5 2 3 6 9 53 | 54 | Case2: 55 | Enter Array Rows & Cols: 3 6 56 | 1 2 3 4 5 6 57 | 7 8 9 10 11 12 58 | 13 14 15 16 17 18 59 | Wave Print: 1 7 13 14 8 2 3 9 15 16 10 4 5 11 17 18 12 6 60 | */ -------------------------------------------------------------------------------- /06_2D_arrays/03_spiral_print_2D_array.cpp: -------------------------------------------------------------------------------- 1 | // Spiral Pattern in 2D Array 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int arr[1000][1000]; 8 | int rows, cols; 9 | cout << "Enter Rows & Cols: "; 10 | cin >> rows >> cols; 11 | 12 | int val=1; 13 | for(int row=0; row<=rows-1; row++){ 14 | for(int col=0; col<=cols-1; col++){ 15 | arr[row][col] = val++; 16 | cout << arr[row][col] << " "; 17 | } 18 | cout << endl; 19 | } 20 | cout << "Spiral Pattern: "; 21 | int startRow=0; 22 | int startCol=0; 23 | int endRow=rows-1; 24 | int endCol=cols-1; 25 | 26 | while(startRow<=endRow && startCol <= endCol){ 27 | // 1. First Row 28 | for(int i=startCol; i<=endCol; i++){ 29 | cout << arr[startRow][i] << " "; 30 | } 31 | startRow++; 32 | cout << " "; 33 | 34 | // 2. Last Col 35 | for(int i=startRow; i<=endRow; i++){ 36 | cout << arr[i][endCol] << " "; 37 | } 38 | endCol--; 39 | cout << " "; 40 | 41 | // 3. Last Row 42 | // to skip some rows in the ODD case. 43 | if(startRow<=endRow){ 44 | for(int i=endCol; i>=startCol; i--){ 45 | cout << arr[endRow][i] << " "; 46 | } 47 | endRow--; 48 | cout << " "; 49 | } 50 | 51 | // 4. First Col 52 | // to skip some cols in the ODD case. 53 | if(startCol<=endCol){ 54 | for(int i=endRow; i>=startRow; i--){ 55 | cout << arr[i][startCol] << " "; 56 | } 57 | startCol++; 58 | cout << " "; 59 | } 60 | } 61 | 62 | cout << "\n"; 63 | return 0; 64 | } 65 | 66 | /* 67 | OUTPUT: 68 | 69 | Case1: 70 | Enter Rows & Cols: 4 4 71 | 1 2 3 4 72 | 5 6 7 8 73 | 9 10 11 12 74 | 13 14 15 16 75 | Spiral Pattern: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 76 | 77 | Case2: 78 | Enter Rows & Cols: 3 6 79 | 1 2 3 4 5 6 80 | 7 8 9 10 11 12 81 | 13 14 15 16 17 18 82 | Spiral Pattern: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 83 | */ -------------------------------------------------------------------------------- /06_2D_arrays/05_rotate_image.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate Image 3 | - Given a 2D array of size NxN, Rotate the array 90 degrees anti-clockwise. 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | void rotate(int arr[][1000], int rows, int cols){ 11 | // reverse each row 12 | for(int row=0; row<=rows-1; row++){ 13 | int start_col = 0; 14 | int end_col = cols-1; 15 | while(start_col> reverse(start_container,end_container) 35 | for(int row=0; row<=rows-1; row++){ 36 | reverse(arr[row], arr[row]+cols); 37 | } 38 | // transpose 39 | for(int row=0; row<=rows-1; row++){ 40 | for(int col=0; col<=cols-1; col++){ 41 | if(row> rows >> cols; 58 | 59 | int val = 1; 60 | for(int row=0; row<=rows-1; row++){ 61 | for(int col=0; col<=cols-1; col++){ 62 | arr[row][col] = val++; 63 | cout << arr[row][col] << " "; 64 | } 65 | cout << endl; 66 | } 67 | 68 | // rotate(arr, rows, cols); 69 | rotate_stl(arr, rows, cols); 70 | 71 | // display output 72 | cout << "After rotating 90 degree anticlockwise: \n"; 73 | for(int row=0; row<=rows-1; row++){ 74 | for(int col=0; col<=cols-1; col++){ 75 | cout << arr[row][col] << " "; 76 | } 77 | cout << endl; 78 | } 79 | 80 | return 0; 81 | } 82 | 83 | /* 84 | OUTPUT: 85 | 86 | Enter Rows & Cols: 4 4 87 | 1 2 3 4 88 | 5 6 7 8 89 | 9 10 11 12 90 | 13 14 15 16 91 | 92 | After rotating 90 degree anticlockwise: 93 | 4 8 12 16 94 | 3 7 11 15 95 | 2 6 10 14 96 | 1 5 9 13 97 | */ -------------------------------------------------------------------------------- /06_2D_arrays/06_staircase_search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Staircase Search 3 | (Search element in a row-wise & column-wise sorted array) 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | // function to search element in row-wise & col-wise sorted array 10 | void staircase_search(int arr[][100], int rowSize, int colSize, int key){ 11 | int rowStart = 0; 12 | int colEnd = colSize-1; 13 | bool success = false; 14 | 15 | while(rowStart <= rowSize-1 && colEnd >= 0){ 16 | if(key == arr[rowStart][colEnd]){ 17 | success = true; 18 | break; 19 | }else if(key > arr[rowStart][colEnd]){ 20 | rowStart++; 21 | }else{ 22 | colEnd--; 23 | } 24 | } 25 | if(success){ 26 | cout << "Values found at Index: " << rowStart <<"," << colEnd << endl; 27 | }else{ 28 | cout << "Values Not Found" << endl; 29 | } 30 | } 31 | 32 | // function to print array 33 | void print_array(int arr[][100], int rowSize, int colSize){ 34 | for(int row=0; row<=rowSize-1; row++){ 35 | for(int col=0; col<=colSize-1; col++){ 36 | cout << arr[row][col] << " "; 37 | } 38 | cout << "\n"; 39 | } 40 | cout << "\n"; 41 | } 42 | 43 | // function to drive code 44 | int main(){ 45 | int arr[100][100] ={{1,4,8,10},{2,5,9,15},{6,16,18,20},{11,17,19,23}}; 46 | int rowSize = 4; 47 | int colSize = 4; 48 | 49 | // display array 50 | print_array(arr, rowSize, colSize); 51 | 52 | int key; 53 | cout << "Enter the search value: "; 54 | cin >> key; 55 | 56 | // search value 57 | staircase_search(arr, rowSize, colSize, key); 58 | 59 | return 0; 60 | } 61 | 62 | /* 63 | OUTPUT: 64 | 65 | Case1: 66 | 1 4 8 10 67 | 2 5 9 15 68 | 6 16 18 20 69 | 11 17 19 23 70 | 71 | Enter the search value: 16 72 | Values found at Index: 2,1 73 | 74 | Case2: 75 | 1 4 8 10 76 | 2 5 9 15 77 | 6 16 18 20 78 | 11 17 19 23 79 | 80 | Enter the search value: 33 81 | Values Not Found 82 | */ -------------------------------------------------------------------------------- /07_character_arrays/01_character_array_basic.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Character Array Basic 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main(){ 10 | int a[] = {1,2,3}; // Interger Array 11 | cout << "(int) a: " << a << endl; 12 | /* we get starting of address (Default behaviour of any array) */ 13 | 14 | char b[] = {'m','o','n','d','a','y','\0'}; // Character Array 15 | cout << "(char) b: " << b << "\n\n"; 16 | /* we get the content of array 'b'. It prints character unless it find '\0' (NULL) character. 17 | This special behaviour is because of Operator Overloading. 18 | "cout" when used with "<<" (left shift operator) & "charactr array" 19 | */ 20 | 21 | 22 | // Size of character array 23 | char s1[] = {'h','e','l','l','o'}; // doesn't terminated with NULL. (So, it can return return Garbage after printing "hello") 24 | char s2[] = {'h','e','l','l','o','\0'}; 25 | char s3[] = "hello"; // another way (Null character added automatically) 26 | 27 | cout << "s1: " << s1 << " | SIZE: " << sizeof(s1) << endl; // 5 bytes 28 | cout << "s2: " << s2 << " | SIZE: " << sizeof(s2) << endl; // 6 bytes 29 | cout << "s3: " << s3 << " | SIZE: " << sizeof(s3) << "\n\n"; // 6 bytes 30 | 31 | 32 | // User Input 33 | char s4[10]; // atmost 10 characters (10 bytes) 34 | cout << "Enter your characters: "; 35 | cin >> s4; // Instead of Loop we can directly use cin. Also, remember null character is automatically added. 36 | 37 | cout << "s4: " << s4 << endl; 38 | cout << "Size: " << sizeof(s4) << endl; // 10 bytes (because s4[10]) 39 | 40 | return 0; 41 | } 42 | 43 | /* 44 | OUTPUT: 45 | 46 | (int) a: 0x7ffdebf80418 47 | (char) b: monday 48 | 49 | s1: hellohello | SIZE: 5 50 | s2: hello | SIZE: 6 51 | s3: hello | SIZE: 6 52 | 53 | Enter your characters: hello 54 | s4: hello 55 | Size: 10 56 | */ -------------------------------------------------------------------------------- /07_character_arrays/02_reading_sentences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Read a sentence/paragraph and store it 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | void readline(char arr[], int maxLen, char delim = '\n'){ 9 | int index = 0; 10 | char ch = cin.get(); 11 | while(ch != delim){ // Terminating on "newline" 12 | arr[index] = ch; 13 | index++; 14 | if(index == maxLen-1){ // maxLen-1 because we need to add NULL character at last 15 | break; 16 | } 17 | ch = cin.get(); 18 | } 19 | // once out of the loop 20 | arr[index] = '\0'; // Adding null character at last 21 | return; 22 | } 23 | 24 | int main(){ 25 | char arr[1000]; 26 | cout << "ENTER YOUR SENTENCE: "; 27 | 28 | /* reading sentence using cin */ 29 | // cin >> arr; // cin doesn't read "spaces" & "newline" 30 | 31 | 32 | /* reading sentence using cin.get(). 33 | But, cin.get() reads single character at a time. 34 | So, create a funtion by putting a loop to read characters. */ 35 | readline(arr,1000,'\n'); 36 | 37 | 38 | /* reading sentence using cin.getline() */ 39 | // cin.getline(arr,1000); 40 | // cin.getline(arr,1000,'$'); 41 | 42 | cout << "OUTPUT: " << arr << endl; 43 | return 0; 44 | } 45 | 46 | /* 47 | OUTPUT: 48 | 49 | ENTER YOUR SENTENCE: 50 | Hello Guest, Hope you are enjoying the session. Bye!! 51 | 52 | OUTPUT: 53 | Hello Guest, Hope you are enjoying the session. Bye!! 54 | 55 | */ -------------------------------------------------------------------------------- /07_character_arrays/03_palindromic_string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Palindromic String 3 | - Read a sentence/paragraph & check if it is palindrome or not 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | bool isPalindrome(char arr[]){ 11 | int start = 0; 12 | int end = strlen(arr) - 1; 13 | 14 | while(start < end){ 15 | if(arr[start] == arr[end]){ 16 | start++; 17 | end--; 18 | }else{ 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | 25 | int main(){ 26 | char arr[1000]; 27 | cout << "Enter your sentence: "; 28 | cin.getline(arr, 1000); 29 | 30 | if(isPalindrome(arr)){ 31 | cout << "Yes, it's Palendromic string" << endl; 32 | }else{ 33 | cout << "Not a Palendromic string" << endl; 34 | } 35 | 36 | return 0; 37 | } 38 | 39 | /* 40 | OUTPUT: 41 | 42 | Case1: 43 | Enter your sentence: abc121cba 44 | Yes, it's Palendromic string 45 | 46 | Case2: 47 | Enter your sentence: ab cd dc ba 48 | Yes, it's Palendromic string 49 | 50 | Case3: 51 | Enter your sentence: aman 52 | Not a Palendromic string 53 | */ -------------------------------------------------------------------------------- /07_character_arrays/04_string_removeconsecutive_duplicates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove consecutive duplicate characters from a string. 3 | eg: INPUT: cccooding 4 | OUTPUT: coding 5 | */ 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | void removeDuplicate(char arr[]){ 12 | int len = strlen(arr); 13 | if(len <= 1){ 14 | return; 15 | } 16 | int prev=0; 17 | for(int current=1; current<=len-1; current++){ 18 | if(arr[prev] != arr[current]){ 19 | prev++; 20 | arr[prev] = arr[current]; 21 | } 22 | } 23 | arr[prev+1] = '\0'; 24 | return; 25 | } 26 | 27 | int main(){ 28 | char arr[1000]; 29 | cout << "Enter your string: "; 30 | cin.getline(arr, 1000); 31 | 32 | removeDuplicate(arr); 33 | cout << "Output: "; 34 | cout << arr << endl; 35 | return 0; 36 | } 37 | 38 | /* 39 | OUTPUT: 40 | 41 | Enter your string: coodddddiinggg 42 | Output: coding 43 | */ -------------------------------------------------------------------------------- /07_character_arrays/05_largest_string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Largest String 3 | - Read N, followed by N strings and print the largest string and its length 4 | */ 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int totalStr; 12 | cout << "Enter total number of Strings: "; 13 | cin >> totalStr; 14 | 15 | cin.get(); // to consume extra "\n" 16 | 17 | char currString[1000]; 18 | char maxString[1000]; 19 | int currLen = 0; 20 | int maxLen = 0; 21 | 22 | cout << "Enter your strings: \n;"; 23 | for(int itr=0; itr<=totalStr-1; itr++){ 24 | cin.getline(currString, 1000); 25 | currLen = strlen(currString); 26 | if(currLen > maxLen){ 27 | maxLen = currLen; 28 | strcpy(maxString,currString); 29 | } 30 | } 31 | 32 | cout << "\nMaximum String: " << maxString << "\nlength - " << maxLen << endl; 33 | 34 | return 0; 35 | } 36 | 37 | /* 38 | OUTPUT: 39 | 40 | Enter total number of Strings: 5 41 | 42 | Enter your strings: 43 | raman deep 44 | amarjeet singh 45 | ravinder sharma 46 | mandeep sharma 47 | ravi juneja 48 | 49 | Maximum String: ravinder sharma 50 | length - 15 51 | */ -------------------------------------------------------------------------------- /08_strings/01_2D_chararcter_arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 2D Character Array | Strings 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main(){ 10 | 11 | // example-1 12 | char arr1[10][10]; 13 | arr1[0][0] = 'A'; // assign value at first row first character 14 | cout << "arr1 : " << arr1 << endl; // print address 15 | cout << "arr1[0] : " << arr1[0] << endl; // complete rows (i.e print first character & garbage value) 16 | cout << "arr1[0][0] : " << arr1[0][0] << "\n\n"; // single character (first row first character) 17 | 18 | // example-2 [character by character] 19 | char arr2[][10] = {{'a','b','\0'},{'d','e','f'}}; 20 | cout << "arr2[0] : " << arr2[0] << endl; // complete rows 21 | cout << "arr2[1] : " << arr2[1] << endl; 22 | cout << "arr2[1][1] : " << arr2[1][1] << "\n\n"; // single character (second row second character) 23 | 24 | // example-3 [string] 25 | char arr3[][10] = {"xyz","hello","hi"}; 26 | cout << "arr3 : " << arr3 << endl; 27 | cout << "arr3[0] : " << arr3[0] << endl; 28 | cout << "arr3[1] : " << arr3[1] << endl; // complete row 29 | cout << "arr3[2] : " << arr3[2] << endl; 30 | cout << "arr3[2][0] : " << arr3[2][0] << endl; // single character (third row first character) 31 | 32 | return 0; 33 | } 34 | 35 | /* 36 | OUTPUT: 37 | 38 | arr1 : 0x7ffe0c90f630 39 | arr1[0] : A��� 40 | arr1[0][0] : A 41 | 42 | arr2[0] : ab 43 | arr2[1] : def 44 | arr2[1][1] : e 45 | 46 | arr3 : 0x7ffe0c90f610 47 | arr3[0] : xyz 48 | arr3[1] : hello 49 | arr3[2] : hi 50 | arr3[2][0] : h 51 | */ -------------------------------------------------------------------------------- /08_strings/01_reading_list_of_string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Read a list of strings and we will store them in 2D character array 3 | 4 | - cin : It doesn't read spaces & newline 5 | - cin.get() : Read single character (including spaces & newline) 6 | - cin.getline(char* ch, int size) : Read a line from an input stream (Syntax for Character Array) 7 | - getline(istream& cin, string& str) : Read a line from an input stream (Syntax for String) 8 | 9 | Where, 10 | char* : It is a character pointer that points to the array. 11 | size : It acts as a delimiter that defines the size of the array means input cannot cross this size. 12 | string& : It is a string object, the input is stored in this object after being read from the stream. 13 | istream& : It is an object of istream class and tells the function about the stream from where to read the input from 14 | 15 | Syntax: 16 | 1. istream& getline (istream& is, string& str, char delim); 17 | 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | 23 | 24 | int main(){ 25 | char arr[100][1000]; 26 | 27 | int totalStrings; 28 | cout << "Enter total number of strings: "; 29 | cin >> totalStrings; 30 | cin.get(); // To consume the extra "Enter" that is followed after "totalString" 31 | 32 | // Take input 33 | cout << "Enter your strings: \n"; 34 | for(int row=0; row<=totalStrings-1; row++){ 35 | cin.getline(arr[row], 1000); // Taking input row by row & string in i-th row 36 | } 37 | cout << endl; 38 | 39 | // Print out all the strings 40 | cout << "Output: \n"; 41 | for(int row=0; row<=totalStrings-1; row++){ 42 | cout << arr[row] << endl; 43 | } 44 | 45 | return 0; 46 | } 47 | 48 | /* 49 | OUTPUT: 50 | 51 | Enter total number of strings: 3 52 | 53 | Enter your strings: 54 | ram 55 | shyam 56 | raman 57 | 58 | Output: 59 | ram 60 | shyam 61 | raman 62 | */ -------------------------------------------------------------------------------- /08_strings/03_sorting.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sorting 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | bool compare(string s1, string s2){ 11 | if(s1.length() == s2.length()){ // if length is same, then compare lexicographic 12 | return s1> totalStr; 21 | cin.get(); 22 | 23 | string s[100]; 24 | 25 | cout << "Enter Strings: \n"; 26 | for(int seq=0; seq <= totalStr-1; seq++){ 27 | getline(cin,s[seq]); 28 | } 29 | 30 | cout << "\nAfter Sorting: " << endl; 31 | sort(s, s+totalStr, compare); // sorting 32 | 33 | for(int seq=0; seq <= totalStr-1; seq++){ 34 | cout << s[seq] << endl; 35 | } 36 | return 0; 37 | } 38 | 39 | /* 40 | OUTPUT: 41 | 42 | Enter total number of strings: 6 43 | 44 | Enter Strings: 45 | Amandeep Verma 46 | deep 47 | aman 48 | Govind 49 | Arvind 50 | Bhim Gupta 51 | 52 | After Sorting: 53 | aman 54 | deep 55 | Arvind 56 | Govind 57 | Bhim Gupta 58 | Amandeep Verma 59 | */ -------------------------------------------------------------------------------- /08_strings/04_tokenization_using_strtok.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Tokenization using 'strtok()' 3 | 4 | - char *strtok(char *s, char *delimiters) 5 | - returns a token on each subsequent call 6 | - on the first call function should be passes with string argument for 's' 7 | - on subsequent calls we should pass the string argument as NULL 8 | */ 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int main(){ 15 | char s[100] = "Today is a rainy day"; 16 | 17 | char *ptr = strtok(s, " "); 18 | // It creates a new array & then copy the first token & return the address of this array 19 | cout << ptr << endl; 20 | 21 | while(ptr!=NULL){ 22 | // strtok() maintains a static variable that stores the state of the string 23 | ptr = strtok(NULL, " "); 24 | cout << ptr << endl; 25 | } 26 | return 0; 27 | } 28 | 29 | /* 30 | OUTPUT: 31 | 32 | Today 33 | is 34 | a 35 | rainy 36 | day 37 | */ -------------------------------------------------------------------------------- /08_strings/05_designing_string_tokeniser.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Designing String Tokeniser 3 | */ 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Function accepts string & single character act as delimiter 10 | char *mystrtok(char *str, char delim) 11 | { 12 | // state of static variable is initalize only once in a function call & 13 | // in every subsequent call it will the same state as in the previous call. 14 | static char*input = NULL; 15 | 16 | // we are making the first call 17 | if(str != NULL){ 18 | input = str; 19 | } 20 | 21 | //checkhere - base case after the final token has been returned 22 | if(input == NULL){ 23 | return NULL; 24 | } 25 | 26 | // start extracting tokens & store them in an array 27 | char *output = new char(strlen(input)+1); 28 | int i=0; 29 | for( ;input[i] != '\0'; i++){ 30 | if(input[i] != delim){ 31 | output[i] = input[i]; 32 | }else{ 33 | output[i] = '\0'; 34 | input = input + i+1; 35 | return output; 36 | } 37 | } 38 | 39 | // corner case (i.e last entry) 40 | output[i] = '\0'; 41 | input = NULL; 42 | return output; 43 | } 44 | 45 | int main(){ 46 | char s1[100] = "Have a nice day" ; 47 | char *ptr = mystrtok(s1,' '); 48 | cout << ptr << endl; 49 | while(ptr != NULL){ 50 | ptr = mystrtok(NULL,' '); 51 | cout << ptr << endl; 52 | } 53 | return 0; 54 | } 55 | 56 | /* 57 | OUTPUT: 58 | 59 | Today 60 | is 61 | a 62 | rainy 63 | day 64 | */ -------------------------------------------------------------------------------- /10_pointers/01_address_of_operator.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Address of Operator (&) 3 | - It is used to find address of variable 4 | - C++ display address in HexaDecimal format (Base 16) 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int x=10; 12 | cout << "[Integer] Address of x [&x]: " << &x << endl; 13 | 14 | float y=9.5; 15 | cout << "[Float] Address of y [&y]: " << &y << "\n\n"; 16 | 17 | // It doesn't work for character variables bcz of operator overloading 18 | char ch = 'A'; 19 | cout << "[Character] Address of ch [&ch]: " << ch << endl; 20 | 21 | // Explicit typecasting from char* to void* 22 | cout << "[Character] Address of ch [(void*)&ch]: " << (void*)&ch << endl; 23 | return 0; 24 | } 25 | 26 | /* 27 | OUTPUT: 28 | 29 | [Integer] Address of x [&x]: 0x7ffd67f494e0 30 | [Float] Address of y [&y]: 0x7ffd67f494e4 31 | [Character] Address of ch [&ch]: A 32 | [Character] Address of ch [(void*)&ch]: 0x7ffd67f494df 33 | */ -------------------------------------------------------------------------------- /10_pointers/03_dereference_operator.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Dereference Operator (*) 3 | 4 | asterisk (*) has many use cases :- 5 | 1. For multiplication // 5*2 6 | 2. to declaring pointer // int * ptr; 7 | 3. to dereference any address // *ptr + 1 8 | 9 | Dereference: 10 | - In simple words, dereferencing means accessing the value from a certain memory location against 11 | which that pointer is pointing. 12 | - So, by dereferencing pointer we can access the variable, in which they are pointing to. 13 | 14 | */ 15 | 16 | #include 17 | using namespace std; 18 | 19 | int main(){ 20 | int a = 10; 21 | int *ptr = &a; // declaration & initilization 22 | 23 | cout << "&a - " << &a << endl; // OUTPUT: (Address of bucket "a") 24 | cout << "ptr - " << ptr << "\n\n"; // OUTPUT: (Address of bucket "a") 25 | 26 | // dereferencing 27 | cout << "*(&a) - " << *(&a) << endl; // OUTPUT: 10 (value -> address a) 28 | cout << "*(ptr) - " << *(ptr) << "\n\n"; // OUTPUT: 10 (value -> address stored at ptr) 29 | 30 | cout << "*(&ptr) - " << *(&ptr) << endl; // OUTPUT: (Address of bucket "a") [=> value stored at ptr) => value at &ptr] 31 | cout << "&(*ptr) - " << &(*ptr) << "\n\n"; // OUTPUT: (Address of bucket "a") [i.e *ptr = bucket "a"] 32 | 33 | // Know the difference :- 34 | cout << "*(ptr) + 1 - " << *(ptr)+1 << endl; // OUTPUT: 11 (i.e 10+1) 35 | cout << "*(ptr+1) - " << *(ptr+1) << "\n\n"; // OUTPUT: Unknown/Garbage Value 36 | // (value at next memory address) 37 | 38 | // Double Pointer 39 | int ** newptr = &ptr; 40 | cout << "Double Pointer: " << endl; 41 | cout << "newptr: " << newptr << endl; // OUTPUT: (address of ptr) 42 | cout << "&ptr: " << &ptr << endl; // OUTPUT: (address of ptr) 43 | 44 | return 0; 45 | } 46 | 47 | /* 48 | OUTPUT: 49 | 50 | &a - 0x7ffe49b6db94 51 | ptr - 0x7ffe49b6db94 52 | 53 | *(&a) - 10 54 | *(ptr) - 10 55 | 56 | *(&ptr) - 0x7ffe49b6db94 57 | &(*ptr) - 0x7ffe49b6db94 58 | 59 | *(ptr) + 1 - 11 60 | *(ptr+1) - 1236720532 61 | 62 | Double Pointer: 63 | newptr: 0x7ffe49b6db98 64 | &ptr: 0x7ffe49b6db98 65 | */ -------------------------------------------------------------------------------- /10_pointers/04_pass_by_reference.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Pass by Reference Using Pointers 3 | 4 | Pass by Value : Passing the copy of variable 5 | Pass by Reference: Passing the address of variable 6 | 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | // call by value 13 | void increment_1(int num){ // variable 14 | num = num +1; 15 | cout << "[Call by Value] a: "<< num << endl; 16 | } 17 | 18 | // call by reference 19 | void increment_2(int *num){ // pointer 20 | *num = *num +1; 21 | cout << "[Call by reference] b:"<< *num << endl; 22 | } 23 | 24 | int main(){ 25 | int a = 10; 26 | int b = 10; 27 | 28 | cout << "a : "<< a << endl; 29 | increment_1(a); // Passing the copy of variable 30 | cout << "[Inside Main] a: "<< a << endl; 31 | 32 | cout << "\nb : "<< b << endl; 33 | increment_2(&b); // Passing the address of variable 34 | cout << "[Inside Main] b: "<< b << endl; 35 | 36 | 37 | return 0; 38 | } 39 | 40 | /* 41 | OUTPUT: 42 | a : 10 43 | [Call by Value] a: 11 44 | [Inside Main] a: 10 45 | 46 | b : 10 47 | [Call by reference] b:11 48 | [Inside Main] b: 11 49 | */ -------------------------------------------------------------------------------- /10_pointers/05_reference_variable.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - References in C++ 3 | 4 | Reference Variable 5 | - When a variable is declared as a reference, it becomes an alternative name for an existing variable. 6 | - A variable can be declared as a reference by putting ‘&’ in the declaration. 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | 13 | int main(){ 14 | int num = 10; 15 | 16 | int &ref = num; // ref is a reference to num 17 | cout << "ref : "<< ref << endl; 18 | 19 | ref = 20; // value of num(alias name ref) is now changed to 20. 20 | cout << "ref : "<< ref << endl; 21 | 22 | num = 30; // value of num is now changed to 20. 23 | cout << "ref : "<< ref << endl; 24 | 25 | return 0; 26 | } 27 | 28 | /* 29 | OUTPUT: 30 | ref : 10 31 | ref : 20 32 | ref : 30 33 | 34 | 35 | More About References Variable: 36 | 37 | - Reference Variable: 38 | > A reference variable is an alias, that is, another name for an already existing 39 | variable/memory instance. 40 | > Once a reference is initialized with a variable, either the variable name or the reference 41 | name may be used to refer to the variable. 42 | > The reference variable once defined to refer to a variable cannot be changed to 43 | point to other variable. 44 | 45 | - Defining Reference Variable: 46 | > Reference variables are defined by using '&' symbol in the definition. 47 | > Since they do not have any storage of their own and are just another name for the 48 | existing storage, they need to initialized before using them. 49 | > Eg: int x; 50 | int &y = x; 51 | The exisiting memory X will now also have another name Y. 52 | 53 | - Reference Variable VS Pointer Variable 54 | > You cannot have NULL references. You must always be able to assume that a reference 55 | is connected to a legitimate piece of storage. 56 | > Once a reference is initialized to an object, it cannot be changed to refer to another object. 57 | Pointers can be pointed to another object at any time. 58 | > A reference must be initialized when it is created. Pointers can be initialized at any time. 59 | */ -------------------------------------------------------------------------------- /11_dynamic_memory_allocation/03_allocating_2d_dynamic_arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Allocating 2D Dynamic Arrays 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int main(){ 9 | int rows, cols; 10 | cout << "Enter [Rows x Cols] : "; 11 | cin >> rows >> cols; 12 | 13 | // create an array of row heads 14 | int **arr = new int*[rows]; 15 | 16 | // create a 2D array 17 | for(int row=0; row<=rows-1; row++){ 18 | arr[row] = new int[cols]; 19 | } 20 | 21 | // Add value & print array elements 22 | cout << "Array Elements: \n"; 23 | int val = 1; 24 | for(int row=0; row<=rows-1; row++){ 25 | for(int col=0; col<=cols-1; col++){ 26 | arr[row][col] = val; 27 | val++; 28 | cout << arr[row][col] << " "; 29 | } 30 | cout << endl; 31 | } 32 | 33 | // Free each sub-array 34 | for(int row=0; row<=rows-1; row++){ 35 | delete[] arr[row]; 36 | } 37 | //Free the array pointers 38 | delete[] arr; 39 | 40 | return 0; 41 | } 42 | 43 | /* 44 | OUTPUT: 45 | Enter [Rows x Cols] : 3 3 46 | Array Elements: 47 | 1 2 3 48 | 4 5 6 49 | 7 8 9 50 | */ -------------------------------------------------------------------------------- /11_dynamic_memory_allocation/04_returning_local_vs_dynamic_arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Returning Local Arrays Vs Dynamic Arrays 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | int* fun1(){ 10 | int *a = new int[5]{1,2,3,4,5}; // Dynamic allocation 11 | 12 | cout << "a: " << a << endl; // Output: [Address of a] 13 | cout << "a[0]: " << a[0] << endl; // Output: 1 14 | 15 | return a; 16 | 17 | } 18 | 19 | int* fun2(){ 20 | int a[] = {1,2,3,4,5}; // Static allocation 21 | 22 | cout << "a: " << a << endl; // Output: [Address of a] 23 | cout << "a[0]: " << a[0] << endl; // Output: 1 24 | 25 | /* NOTE: we should never return a local variable because once's the function call 26 | is over, the array is destroyed */ 27 | return a; 28 | } 29 | 30 | 31 | int main(){ 32 | // Returning Dynamic Array 33 | cout << "Dynamic Allocation: \n"; 34 | int *b = fun1(); 35 | cout << "b: " << b << endl; // Output: [Address of a] 36 | cout << "b[0]: " << b[0] << "\n\n"; // Output: 1 37 | delete [] b; 38 | 39 | // Returning Static Array 40 | cout << "Static Allocation: \n"; 41 | b = fun2(); 42 | cout << "b: " << b << endl; // Output: [Address of a] 43 | cout << "b[0]: " << b[0] << endl; // Output: [Garbage or Segmentaion Fault] 44 | 45 | /* In above case, fun2() return a local variable (as a[] is a static allocation) 46 | So, once's the function call is over, the array is destroyed. 47 | Thus, we cannot guess the output for b[0] */ 48 | 49 | return 0; 50 | } 51 | 52 | /* 53 | OUTPUT: 54 | Dynamic Allocation: 55 | a: 0x55cf8b0902c0 56 | a[0]: 1 57 | b: 0x55cf8b0902c0 58 | b[0]: 1 59 | 60 | Static Allocation: 61 | a: 0x7ffd78bdd240 62 | a[0]: 1 63 | b: 0 64 | Segmentation fault (core dumped) 65 | */ -------------------------------------------------------------------------------- /12_algorithms_stl/01_find_finction.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Find Function 3 | 4 | return value : An iterator to the first element in the range that compares equal 5 | to val. If no elements match, the function returns last. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | void print_array(int arr[], int size){ 13 | for(int idx=0; idx<=size-1; ++idx){ 14 | cout << arr[idx] << " "; 15 | } 16 | cout << endl; 17 | } 18 | 19 | int main(){ 20 | int arr[] = {1,10,11,9,100}; 21 | int size = sizeof(arr)/sizeof(int); 22 | int key = 11; 23 | 24 | cout << "Array: "; 25 | print_array(arr, size); 26 | 27 | // Search using find() 28 | auto it = find(arr, arr+size, key); 29 | cout << "Address: " << it << endl; 30 | 31 | int index = it - arr; 32 | /* subtracting two pointers to get the number of elements between the two pointers. */ 33 | 34 | if(index == size){ 35 | cout << key << " not present"; 36 | }else{ 37 | cout << key << " present at index: " << index; 38 | } 39 | 40 | cout << endl; 41 | return 0; 42 | } 43 | 44 | /* 45 | OUTPUT: 46 | 47 | case 1:[when key=11] 48 | 49 | Array: 1 10 11 9 100 50 | Address: 0x7ffcc7a2c7d8 51 | 11 present at index: 2 52 | 53 | case2: [when key=110] 54 | 55 | Array: 1 10 11 9 100 56 | Address: 0x7ffd05db8d44 57 | 110 not present 58 | 59 | */ -------------------------------------------------------------------------------- /12_algorithms_stl/03_sort_function.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Sort Function 3 | 4 | - Sorting a array using sort() function of C++ STL is more effective than 5 | selection, bubble & insertion sort. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | //define a comparator function 13 | bool compare(int a, int b){ 14 | return a > b; 15 | } 16 | 17 | int main() 18 | { 19 | int range; 20 | int arr[1000]; 21 | 22 | cout << "Enter array size: "; 23 | cin >> range; 24 | 25 | // Taking array values from user 26 | cout << "Enter array elements: "; 27 | for (int index = 0; index < range; index++) 28 | { 29 | cin >> arr[index]; 30 | } 31 | 32 | // Inbuit - Sorting function 33 | sort(arr, arr+range, compare); 34 | 35 | // print the sorted array 36 | cout << "Sorted Array: "; 37 | for (int index = 0; index < range; index++) 38 | { 39 | cout << arr[index] << " "; 40 | } 41 | cout << endl; 42 | 43 | return 0; 44 | } 45 | 46 | /* 47 | OUTPUT: 48 | 49 | Enter array size : 5 50 | Enter array elements : 1 6 2 5 4 51 | Sorted Array : 6 5 4 2 1 52 | 53 | */ -------------------------------------------------------------------------------- /12_algorithms_stl/04_money_change_problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Money Change Problem 3 | 4 | You are given Indian currency(i.e 1,2,5,10,20,50,100,200,500,2000) & an amount Rs X. 5 | You have to find to the change for amount X using minimum currency. 6 | 7 | Input = Rs 168 8 | 9 | Output = 100 50 10 5 2 1 10 | 11 | Explanation: [100+50+10+5+2+1 = Rs168] 12 | 13 | */ 14 | 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | //comparator function (to overwrite lower bound) 20 | bool compare(int a, int b){ 21 | return a <= b; 22 | } 23 | 24 | // drive code 25 | int main() 26 | { 27 | int currency[] = {1,2,5,10,20,50,100,200,500,2000}; 28 | int size = sizeof(currency)/sizeof(int); 29 | int amount; 30 | 31 | cout << "Enter amount: "; 32 | cin >> amount; 33 | 34 | cout << "Currency: "; 35 | while(amount){ 36 | int idx = lower_bound(currency, currency+size, amount, compare) - currency -1; 37 | /* If search value is not present in array. Then lower bound will return 38 | address of value, greater than the search value. So, we are reducing one index. 39 | Now, this will also increase one index for the case when the search values 40 | is present in the array. So, we are using compare funtion to overwrite index. 41 | */ 42 | int money = currency[idx]; 43 | cout << money << " "; 44 | amount = amount - money; 45 | } 46 | 47 | cout << endl; 48 | return 0; 49 | } 50 | 51 | /* 52 | OUTPUT: 53 | 54 | Enter amount : 182 55 | Currency : 100 50 20 10 2 56 | */ -------------------------------------------------------------------------------- /12_algorithms_stl/06_some_more_methods_stl.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Some More Methods (STL) 3 | 4 | We will cover: 5 | - swap() 6 | - max() 7 | - min() 8 | - reverse() 9 | - max_element() 10 | - min_element() 11 | 12 | */ 13 | 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | void print_array(int arr[], int size){ 19 | for(int idx=0; idx<=size-1; ++idx){ 20 | cout << arr[idx] << " "; 21 | } 22 | cout << endl; 23 | } 24 | 25 | 26 | int main() 27 | { 28 | int a = 10; 29 | int b = 20; 30 | cout << "a: " << a << "| b: " << b << "\n\n"; 31 | 32 | // swap 33 | cout << "After swap: " << endl; 34 | swap(a,b); 35 | cout << "a: " << a << "| b: " << b << endl; 36 | 37 | 38 | // min & max 39 | cout << "mix: " << min(a,b) << endl; 40 | cout << "max: " << max(a,b) << "\n\n"; 41 | 42 | 43 | // reverve first 4 element of array 44 | int arr[] = {10,20,30,40,50}; 45 | int size = sizeof(arr)/sizeof(int); 46 | 47 | cout << "Array: "; 48 | print_array(arr,size); 49 | 50 | reverse(arr, arr+4); 51 | 52 | cout << "Reverved first 4 element: "; 53 | print_array(arr,size); 54 | 55 | 56 | // min_element 57 | auto min_ptr = min_element(arr, arr+size); 58 | /* It return a pointer to the smallest element in the range, and 59 | in case if there are more than one such element,then it points to the first one. 60 | It points to the last in case the range is empty.*/ 61 | cout << "Minimum Element: " << *min_ptr << endl;; 62 | 63 | 64 | // max_element: 65 | auto max_ptr = max_element(arr, arr+size); 66 | /* It returns a pointer to the largest element in the range, and 67 | in case if there are more than one such element, then it points to the first one. 68 | It points to the last in case the range is empty. */ 69 | cout << "Maximum Element: " << *max_ptr << endl;; 70 | 71 | // NOTE: both min_element() & max_element() accepts comparator function 72 | 73 | return 0; 74 | } 75 | 76 | /* 77 | OUTPUT: 78 | 79 | a: 10| b: 20 80 | 81 | After swap: 82 | a: 20| b: 10 83 | 84 | mix: 10 85 | max: 20 86 | 87 | Array: 10 20 30 40 50 88 | Reverved first 4 element: 40 30 20 10 50 89 | Minimum Element: 10 90 | Maximum Element: 50 91 | */ -------------------------------------------------------------------------------- /13_binary_search_divide_&_conquer/01_binary_search_on_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Binary Search on Array 3 | 4 | - Effective way to search in sorted array. 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int binary_search(int arr[], int range, int key) 11 | { 12 | int start = 0; 13 | int end = range; 14 | 15 | while (start <= end) 16 | { 17 | // calculating the middle value 18 | int mid = (start + end) / 2; 19 | 20 | if (arr[mid] == key){ 21 | return mid; 22 | } 23 | else if (arr[mid] > key){ 24 | end = mid - 1; 25 | } 26 | else{ 27 | start = mid + 1; 28 | } 29 | } 30 | return -1; 31 | } 32 | 33 | int main() 34 | { 35 | int range, key; 36 | int arr[1000]; 37 | 38 | cout << "Enter array size: "; 39 | cin >> range; 40 | 41 | cout << "Enter array elements [sorted order]: "; 42 | for (int index = 0; index < range; index++){ 43 | cin >> arr[index]; 44 | } 45 | //Asking for search value 46 | cout << "Enter search key: "; 47 | cin >> key; 48 | 49 | // searching the value 50 | int index = binary_search(arr, range, key); 51 | 52 | if (index == -1){ 53 | cout << key << " is not present" << endl; 54 | }else{ 55 | cout << key << " is present at index: " << index << endl; 56 | } 57 | return 0; 58 | } 59 | 60 | /* 61 | OUTPUT: 62 | 63 | Case 1: 64 | Enter array size: 6 65 | Enter array elements [sorted order]: 11 28 39 45 69 97 66 | Enter search key: 39 67 | 39 is present at index: 2 68 | 69 | Case 2: 70 | Enter array size: 6 71 | Enter array elements [sorted order]: 5 25 48 53 78 82 72 | Enter search key: 50 73 | 50 is not present 74 | */ -------------------------------------------------------------------------------- /13_binary_search_divide_&_conquer/02_binary_search_first_&_last_occerence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Binary Search - First & Last Occurence 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int first_occurence(int arr[], int size, int key){ 9 | int start = 0; 10 | int end = size-1; 11 | int first_idx = -1; 12 | while(start<=end){ 13 | int mid = (start+end)/2; 14 | if(key == arr[mid]){ 15 | first_idx = mid; 16 | end = mid-1; 17 | }else if(key < arr[mid]){ 18 | end = mid-1; 19 | }else{ 20 | start = mid+1; 21 | } 22 | } 23 | return first_idx; 24 | } 25 | 26 | int last_occurence(int arr[], int size, int key){ 27 | int start = 0; 28 | int end = size-1; 29 | int last_idx = -1; 30 | while(start<=end){ 31 | int mid = (start+end)/2; 32 | if(key == arr[mid]){ 33 | last_idx = mid; 34 | start = mid+1; 35 | }else if(key < arr[mid]){ 36 | end = mid-1; 37 | }else{ 38 | start = mid+1; 39 | } 40 | } 41 | return last_idx; 42 | } 43 | 44 | int main() 45 | { 46 | int range, key; 47 | int arr[1000]; 48 | 49 | cout << "Enter array size: "; 50 | cin >> range; 51 | 52 | cout << "Enter array elements [sorted order]: "; 53 | for (int index = 0; index < range; index++){ 54 | cin >> arr[index]; 55 | } 56 | //Asking for search value 57 | cout << "Enter search key: "; 58 | cin >> key; 59 | 60 | // first occurence 61 | int first_idx = first_occurence(arr, range, key); 62 | // last occurence 63 | int last_idx = last_occurence(arr, range, key); 64 | 65 | if (first_idx == -1){ 66 | cout << key << " is not present" << endl; 67 | }else{ 68 | cout << "key-" << key << ": first occurence at: " << first_idx << endl; 69 | cout << "key-" << key << ": last occurence at: " << last_idx << endl; 70 | } 71 | return 0; 72 | } 73 | 74 | /* 75 | OUTPUT: 76 | 77 | Case 1: 78 | Enter array size: 11 79 | Enter array elements [sorted order]: 1 2 2 2 3 4 6 7 9 9 9 80 | Enter search key: 9 81 | key-9: first occurence at: 8 82 | key-9: last occurence at: 10 83 | 84 | Case 2: 85 | Enter array size: 6 86 | Enter array elements [sorted order]: 1 2 3 3 3 6 87 | Enter search key: 4 88 | 4 is not present 89 | */ -------------------------------------------------------------------------------- /13_binary_search_divide_&_conquer/05_binary_search_in_monotonic_search_space.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Binary Search in Monotonic Search Space 3 | 4 | >> Square Root using Binary Search 5 | n = 10 6 | square_root(n) = 3 (int/floor) 7 | 8 | We actually has to think about search space. Also, no such search space is given in the above query. 9 | But, there exist a search space which is sorted & monotonic 10 | 11 | Eg: Suppose we are given a number N. 12 | So, the square root of number N lies in the search space 0 to N. 13 | Now, we can apply binary search on this range. 14 | */ 15 | 16 | #include 17 | using namespace std; 18 | 19 | float get_square_root(int num, int precision) 20 | { 21 | float ans = -1; 22 | // assuming a search space (0 to num) & appling binary search 23 | int start = 0; 24 | int end = num; 25 | while(start<=end){ 26 | int mid = (start+end)/2; 27 | if(mid*mid == num){ 28 | return mid; 29 | } 30 | if(mid*mid < num){ 31 | ans = mid; // getting most potential value for answer 32 | start = mid+1; 33 | } 34 | else{ 35 | end = mid-1; 36 | } 37 | } 38 | // finding the precision values using brute force 39 | float inc = 0.1; 40 | for(int times=1; times<=precision; times++) 41 | { 42 | while(ans*ans <= num){ 43 | ans = ans + inc; 44 | } 45 | // reducing the overshot value 46 | ans = ans - inc; 47 | // for next iteration 48 | inc = inc/10; 49 | } 50 | return ans; 51 | } 52 | 53 | // function to drive code 54 | int main(){ 55 | int num, precision; 56 | cout << "Enter number & precision: "; 57 | cin >> num >> precision; 58 | 59 | cout << "Square root: " << get_square_root(num, precision) << endl; 60 | 61 | return 0; 62 | } 63 | 64 | 65 | /* 66 | OUTPUT: 67 | 68 | Case1: 69 | Enter number & precision: 10 3 70 | Square root: 3.162 71 | 72 | Case2: 73 | Enter number & precision: 100 3 74 | Square root: 10 75 | 76 | Case3: 77 | Enter number & precision: 2 4 78 | Square root: 1.4142 79 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/02_unique_number_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Unique Number - 1 3 | 4 | - Given a list of numbers (2N+1) where every number occurs twice except one, find that unique number 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int total_num, num, ans=0; 13 | 14 | cout << "Enter total numbers: "; 15 | cin >> total_num; 16 | 17 | cout << "Enter numbers: "; 18 | for(int step=0; step> num; 21 | // Using bitwise XOR Operator to solve, It helped to not use any storage 22 | ans = ans^num; 23 | } 24 | 25 | cout<<"Unique No. is : "<< ans << endl; 26 | 27 | return 0; 28 | } 29 | 30 | /* 31 | OUTPUT: 32 | 33 | Enter total numbers: 7 34 | Enter numbers: 5 6 5 6 1 2 1 35 | Unique No. is : 2 36 | 37 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/06_replace_bits_in_n_by_m.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Replace Bits in N by M 3 | 4 | You are given two 32-bits numbers, N and M, and two bit positions. i and j. 5 | Write a method to set all bits between i and j in N equal to M 6 | (e.g., M becomes a substring of N located at i and starting at j) 7 | 8 | Eg: Input: N = 1024 (10000000000) 9 | M = 21 (10101) 10 | i = 2 11 | j = 6 12 | Output N = 1108 (10001010100) 13 | */ 14 | 15 | #include 16 | using namespace std; 17 | 18 | 19 | // function to update i-th bit of a given number 20 | int clearRangeItoJ(int n, int i, int j) 21 | { 22 | int ones = -1; 23 | int first_half = ones << (j+1); 24 | int second_half = (1<> n >> m; 46 | 47 | cout << "Enter bit positions [i & j]: "; 48 | cin >> i >> j; 49 | 50 | cout << "Number after replacing : "; 51 | cout << replaceBits(n, m, i, j); 52 | 53 | cout << endl; 54 | return 0; 55 | } 56 | 57 | /* 58 | OUTPUT: 59 | 60 | Case 1: 61 | Enter numbers [N & M] : 1024 21 62 | Enter bit positions [i & j] : 2 6 63 | Number after replacing : 1108 64 | 65 | Case 2: 66 | Enter numbers [N & M] : 15 2 67 | Enter bit positions [i & j] : 1 3 68 | Number after replacing : 5 69 | 70 | Approach: 71 | 72 | - clear bits of N from range i to j 73 | - create a mask from m 74 | (i.e left shift m by i bits) 75 | - return bitwise OR of cleared_N & mask 76 | 77 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/07_counting_set_bits_n_optimisations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Counting Set Bits & Optimisations 3 | 4 | - Given a Number N, find number of set bits in binary representation of it. 5 | 6 | Eg: Input : 13 (1101) 7 | Output: 3 8 | */ 9 | 10 | 11 | #include 12 | using namespace std; 13 | 14 | 15 | // function to count set bits 16 | int countBits(int n) 17 | { 18 | int count = 0; 19 | while(n) 20 | { 21 | count += (n&1); 22 | n = n>>1; 23 | } 24 | return count; 25 | } 26 | 27 | // approach 2 28 | int countBitsFast(int n) 29 | { 30 | int count = 0; 31 | while(n) 32 | { 33 | n = n & (n-1); // removing the last set bits 34 | count++; // count is the no. of times loop run 35 | } 36 | return count; 37 | 38 | /* 39 | Eg: when n = 5 0101 40 | n-1 = 4 & 0100 41 | ------- 42 | n & (n-1) = 4 0100 43 | 44 | when n = 4 0100 45 | n-1 = 3 & 0011 46 | ------- 47 | n & (n-1) = 0 0000 48 | 49 | Time Complexity: O(No. of Set Bits) 50 | */ 51 | } 52 | 53 | // function to drive code 54 | int main() 55 | { 56 | int n; 57 | 58 | cout << "Enter numbers: "; 59 | cin >> n; 60 | 61 | cout << "count: " << countBits(n) << endl; // Approach 1 62 | cout << "count: " << countBitsFast(n) << endl; // Approach 2 63 | cout << "count: " << __builtin_popcount(n) << endl; // Buildin Method 64 | 65 | return 0; 66 | } 67 | 68 | /* 69 | OUTPUT: 70 | 71 | Case 1: 72 | Enter numbers: 5 73 | count: 2 74 | 75 | Case 2: 76 | Enter numbers: 13 77 | count: 3 78 | 79 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/08_decimal_to_binary_using_bitwise.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Decimal to Binary using Bitwise 3 | 4 | - Given a Number N, convert number into its binary representation. 5 | 6 | Eg: Input : 13 7 | Output: 1101 8 | */ 9 | 10 | 11 | #include 12 | using namespace std; 13 | 14 | 15 | // function to convert decimal into binary 16 | int decimalToBinary(int n) 17 | { 18 | int binary_n = 0; 19 | int pow = 1; 20 | while(n) 21 | { 22 | int last_bit = n&1; 23 | binary_n += pow*last_bit; 24 | n = n>>1; 25 | pow *= 10; 26 | } 27 | return binary_n; 28 | } 29 | 30 | 31 | // function to drive code 32 | int main() 33 | { 34 | int n; 35 | 36 | cout << "Enter numbers: "; 37 | cin >> n; 38 | 39 | cout << n << " = " << decimalToBinary(n) << endl; 40 | 41 | return 0; 42 | } 43 | 44 | /* 45 | OUTPUT: 46 | 47 | Case 1: 48 | Enter numbers: 9 49 | 9 = 1001 50 | 51 | Case 2: 52 | Enter numbers: 13 53 | 13 = 1101 54 | 55 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/10_unique_number_III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Unique Numbers - III 3 | 4 | We are given an array containg n numbers. 5 | All the numbers are present thrice except for one number which is only present once. 6 | Find the unique number. Only use - bitwise operators, and no extra space. 7 | 8 | Input Format: First line contains the number n. Second line contains n space separated number. 9 | 10 | Constraints: N < 10^5 11 | 12 | Output Format: Output a single line containing the unique number 13 | 14 | Sample Input: 7 15 | 1 1 1 2 2 2 3 16 | 17 | Sample Output: 3 18 | 19 | Explanation: 3 is present only once 20 | */ 21 | 22 | 23 | #include 24 | using namespace std; 25 | 26 | int main() 27 | { 28 | int total_num, num; 29 | 30 | cout << "Enter total numbers: "; 31 | cin >> total_num; 32 | 33 | // Array of fixed size - O(1) space 34 | int bitCount[64] = {0}; // to maintain sum of bit-count at every bit position for input-numbers 35 | 36 | cout << "Enter numbers: "; 37 | for(int i=0; i> num; 40 | 41 | // update the bitCount array by extracting bits of each input number 42 | int idx = 0; 43 | while(num) 44 | { 45 | int lastBit = num&1; 46 | bitCount[idx] += lastBit; // maintaing sum of each-bit-count 47 | idx++; 48 | num = num>>1; 49 | } 50 | } 51 | 52 | /* 53 | As the numbers are repeated thrice. 54 | So, sum of bit-count will be of form 3N or 3N+1 at every bit position. 55 | Thus to find the unique number, take modulus with 3 for sum-of-bit-count at every bit position 56 | (i.e eliminating the contribution of bits which are occuring 3N times) & converting 0s and 1s 57 | into decimal number. 58 | */ 59 | int power = 1; 60 | int ans = 0; 61 | for(int idx=0; idx<64; idx++) 62 | { 63 | bitCount[idx] = bitCount[idx]%3; // reducing by a factor of 3 64 | ans += bitCount[idx]*power; 65 | power = power<<1; // power *= 2; 66 | } 67 | 68 | cout << "Unique Number: " << ans; 69 | cout << endl; 70 | 71 | return 0; 72 | } 73 | 74 | /* 75 | OUTPUT: 76 | 77 | Case 1: 78 | Enter total numbers: 7 79 | Enter numbers: 1 1 1 3 2 2 2 80 | Unique Number: 3 81 | 82 | Case 2: 83 | Enter total numbers: 7 84 | Enter numbers: 5 6 5 6 1 5 6 85 | Unique Number: 1 86 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/11_fast_exponentiation_using_bitmasking.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Fast Exponentiation using Bitmasking 3 | 4 | - Exponentiation/Power using Bitmasking 5 | 6 | Eg: Input : n=2 7 | p=6 8 | Output: 64 9 | 10 | */ 11 | 12 | 13 | #include 14 | using namespace std; 15 | 16 | // Exponentiation/Power using Bitmasking 17 | int power_optimised(int num, int power) 18 | { 19 | int ans = 1; 20 | while(power) 21 | { 22 | int last_bit = power&1; 23 | if(last_bit == 1) 24 | { 25 | ans = ans*num; 26 | } 27 | num = num*num; // Square up 28 | power = power>>1; // Discard the last bit 29 | } 30 | return ans; 31 | 32 | /* 33 | Approach: 34 | 35 | - Iterate over each binary value of 'power' & perform the below operations: 36 | 1. Multiply 'n' by its current value 37 | 2. if extracted_bit = 1 => multiply result-value by n (i.e current value of n) 38 | extracted_bit = 0 => skip 39 | 40 | 41 | Eg: when n = 3 42 | p = 5 (101) 43 | 44 | Current value of n (for each binary value of p) : n=81 n=9 n=3 45 | 1 0 1 46 | Output = 81 * (skip) * 3 47 | = 243 48 | */ 49 | } 50 | 51 | // function to drive code 52 | int main() 53 | { 54 | int num, power; 55 | 56 | cout << "Enter [Number & Power]: "; 57 | cin >> num >> power; 58 | 59 | 60 | cout << "Output: " << power_optimised(num, power); 61 | cout << endl; 62 | 63 | return 0; 64 | } 65 | 66 | /* 67 | OUTPUT: 68 | 69 | Case 1: 70 | Enter [Number & Power]: 5 2 71 | Output: 25 72 | 73 | Case 2: 74 | Enter [Number & Power]: 2 10 75 | Output: 1024 76 | 77 | Case 3: 78 | Enter [Number & Power]: 3 5 79 | Output: 243 80 | */ -------------------------------------------------------------------------------- /14_bit_manipulation/12_generate_subsets_using_bitmasking.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Generate Subsets using Bitmasking 3 | 4 | - Finding Subsequences/Subset of a Given String 5 | (Remember Subsequences are continious whereas Subset are not continious) 6 | 7 | Eg: Input : "abc" 8 | Output: " ",a,ab,abc,ac,b,bc,c 9 | 10 | */ 11 | 12 | 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | // function to extract out character which maps with set-bit of number n 18 | void filterChars(char c[], int n) 19 | { 20 | int idx=0; 21 | while(n) 22 | { 23 | int last_bit = n&1; 24 | if(last_bit == 1) 25 | { 26 | cout << c[idx]; 27 | } 28 | idx++; 29 | n = n>>1; // Discard the last bit 30 | } 31 | cout << endl; 32 | } 33 | 34 | 35 | void printSubsets(char c[]) 36 | { 37 | int len = strlen(c); 38 | // iterating over the list of numbers 39 | for(int i=0; i < (1<> c; 54 | 55 | cout << "Output: \n"; 56 | printSubsets(c); 57 | 58 | return 0; 59 | } 60 | 61 | /* 62 | 63 | OUTPUT: 64 | 65 | Enter character: abc 66 | 67 | Output: 68 | 69 | a 70 | b 71 | ab 72 | c 73 | ac 74 | bc 75 | abc 76 | 77 | 78 | Approach: 79 | 80 | - Extracting out character which maps with set-bit from number 0 to 7 81 | 82 | cba 83 | 0 : 000 | " " 84 | 1 : 001 | a 85 | 2 : 010 | b 86 | 3 : 011 | ab 87 | 4 : 100 | c 88 | 5 : 101 | ac 89 | 6 : 110 | bc 90 | 7 : 111 | abc 91 | */ -------------------------------------------------------------------------------- /16_recursion_I_basics/01_recursion_introduction.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Recursion Introduction 3 | 4 | What is recursion ? 5 | - Recursion in Computer Science is a method where solution to a problem 6 | depends on solution to smaller instances of same problem. 7 | - Using recursion we simplify the code for complex problems (eg: Tower of Hanoi) 8 | 9 | Parts of Recursive Algorithm 10 | 1. Base Case 11 | 2. Recursive Call (to work towards Base Case) 12 | 13 | 14 | Easiest Way to Approach to Recursive Problems 15 | "Magical" Recursive Rule = Principle of Mathematical Induction (PMI) 16 | 1. Figure out the Base Case 17 | 2. Assume Sub Problem can be solved by recursion (automatically) 18 | 3. Using the sub-problem write the answer for the current problem. 19 | 20 | Example: Compute N! [5! = 1*2*3*4*5 = 120] 21 | */ 22 | 23 | #include 24 | using namespace std; 25 | 26 | // function to compute factorial of a given number (using recursion) 27 | int fact(int n) 28 | { 29 | // base case 30 | if(n==0) 31 | { 32 | return 1; 33 | } 34 | // recursive case 35 | return n * fact(n-1); 36 | } 37 | 38 | // function to drive code 39 | int main() 40 | { 41 | int n; 42 | cout << "Enter Number: "; 43 | cin >> n; 44 | 45 | cout << "Factorial: "; 46 | cout << fact(n) << endl; 47 | 48 | return 0; 49 | } 50 | 51 | /* 52 | OUTPUT: 53 | 54 | Enter Number: 5 55 | Factorial: 120 56 | 57 | 58 | Time Complexity: O(N) (Because we have made N calls & in each call we are doing constant operations 59 | i.e in recursive case multiplying two numbers O(1) & base case O(1)) 60 | 61 | Space Complexity: O(N) (Because we are using implicit recursive stack & that is going to store 62 | 'N' numbers of variables i.e Having N numbers of stack frames & each 63 | stack frame contains constant number of variables) 64 | */ -------------------------------------------------------------------------------- /16_recursion_I_basics/02_fibonacci_recursion_n_call_stack_visualisation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Fibonacci Recursion | Call Stack Visualisation 3 | 4 | Problem: Nth Fibonacci using Recursion 5 | (0,1,1,2,5,8,13 ...... f(n).......) 6 | 7 | 8 | Easiest Way to Approach to Recursive Problems 9 | "Magical" Recursive Rule = Principle of Mathematical Induction (PMI) 10 | 1. Figure out the Base Case 11 | 2. Assume Sub Problem can be solved by recursion (automatically) 12 | 3. Using the sub-problem write the answer for the current problem. 13 | 14 | */ 15 | 16 | #include 17 | using namespace std; 18 | 19 | // function to compute Nth Fibonacci (using recursion) 20 | int f(int n) 21 | { 22 | // base case 23 | if(n==0 or n==1) 24 | { 25 | return n; 26 | } 27 | // recursive case 28 | int f1 = f(n-1); 29 | int f2 = f(n-2); 30 | return f1 + f2; 31 | } 32 | 33 | // function to drive code 34 | int main() 35 | { 36 | int n; 37 | cout << "Enter Number: "; 38 | cin >> n; 39 | 40 | cout << "Fibonacci: "; 41 | cout << f(n) << endl; 42 | 43 | return 0; 44 | } 45 | 46 | /* 47 | OUTPUT: 48 | 49 | Case 1: 50 | Enter Number: 7 51 | Fibonacci: 13 52 | 53 | Case 2: 54 | Enter Number: 4 55 | Fibonacci: 3 56 | 57 | 58 | 59 | Call Stack Visualisation 60 | 61 | int f(int n) 62 | { Call Stack Recursion Tree 63 | // base case 64 | if(n==0 or n==1) 4 65 | { |________| / \ 66 | return n; |________| 3 2 67 | } |__n=1___| / \ / \ 68 | // recursive case |__n=2___| f1=1 f2=0 2 1 1 0 69 | int f1 = f(n-1); |__n=3___| f1=1 f2=1 / \ 70 | int f2 = f(n-2); |__n=4___| f1=2 f2=1 1 0 71 | return f1 + f2; |__main__| f=3 72 | } 73 | */ -------------------------------------------------------------------------------- /16_recursion_I_basics/03_increasing_decreasing_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Increasing Decreasing Recursion 3 | 4 | Write 2 Functions to Print first N numbers in 5 | - Increasing 6 | - Descreasing 7 | 8 | 9 | Easiest Way to Approach to Recursive Problems 10 | "Magical" Recursive Rule = Principle of Mathematical Induction (PMI) 11 | 1. Figure out the Base Case 12 | 2. Assume Sub Problem can be solved by recursion (automatically) 13 | 3. Using the sub-problem write the answer for the current problem. 14 | 15 | */ 16 | 17 | #include 18 | using namespace std; 19 | 20 | 21 | void dec(int n) 22 | { 23 | // base case 24 | if(n==0) 25 | { 26 | return; 27 | } 28 | // recursive case 29 | cout << n << " "; // Before function call, goes from Top to Base Case 30 | dec(n-1); 31 | } 32 | 33 | 34 | void inc(int n) 35 | { 36 | // base case 37 | if(n==0) 38 | { 39 | return; 40 | } 41 | // recursive case 42 | inc(n-1); 43 | cout << n << " "; // After function call, goes in Bottom up direction (i.e from Base case towards Top) 44 | } 45 | 46 | // function to drive code 47 | int main() 48 | { 49 | int n; 50 | cout << "Enter Number: "; 51 | cin >> n; 52 | 53 | cout << "Decreasing: "; 54 | dec(n); 55 | cout << "\nIncreasing: "; 56 | inc(n); 57 | 58 | cout << endl; 59 | return 0; 60 | } 61 | 62 | /* 63 | OUTPUT: 64 | Enter Number: 5 65 | Decreasing: 5 4 3 2 1 66 | Increasing: 1 2 3 4 5 67 | */ -------------------------------------------------------------------------------- /16_recursion_I_basics/04_recursion_array_is_sorted.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Recursion Array is Sorted 3 | 4 | Write a recursive Functions to check if array is sorted 5 | {1, 2, 3, 4, 5, 10, 20} 6 | 7 | 8 | Easiest Way to Approach to Recursive Problems 9 | "Magical" Recursive Rule = Principle of Mathematical Induction (PMI) 10 | 1. Figure out the Base Case 11 | 2. Assume Sub Problem can be solved by recursion (automatically) 12 | 3. Using the sub-problem write the answer for the current problem. 13 | 14 | */ 15 | 16 | #include 17 | using namespace std; 18 | 19 | // function to check if array is sorted 20 | bool isSorted(int *a, int size) 21 | { 22 | // base case 23 | if(size==0 or size==1) 24 | { 25 | return true; 26 | } 27 | // recursive case 28 | if(a[0]> size; 42 | 43 | int arr[size]; 44 | cout << "Enter Elements: "; 45 | for(int i=0; i> arr[i]; 48 | } 49 | 50 | cout << "Output: " << isSorted(arr, size); 51 | 52 | cout << endl; 53 | return 0; 54 | } 55 | 56 | /* 57 | OUTPUT: 58 | 59 | Case 1: 60 | Enter array size: 5 61 | Enter Elements: 1 2 3 14 5 62 | Output: 0 63 | 64 | Case 2: 65 | Enter array size: 7 66 | Enter Elements: 1 2 3 7 8 9 12 67 | Output: 1 68 | */ -------------------------------------------------------------------------------- /16_recursion_I_basics/05_recursion_binary_search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Time to Try Recursion! 3 | 4 | Write a Recursive Functions to perform binary search. 5 | Eg: arr = {1, 2, 3, 4, 5, 10, 20} 6 | key = 10 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | 13 | int binarySearch(int *a, int start, int end, int key) 14 | { 15 | int mid = start + (end-start)/2; 16 | // base case 17 | if(start>end) 18 | { 19 | return -1; 20 | } 21 | // recursive case 22 | if(a[mid]==key) 23 | { 24 | return mid; 25 | } 26 | else if (key < a[mid]) 27 | { 28 | return binarySearch(a, start, mid-1,key); 29 | } 30 | else 31 | { 32 | return binarySearch(a, mid+1, end,key); 33 | } 34 | } 35 | 36 | 37 | // function to drive code 38 | int main() 39 | { 40 | int size; 41 | cout << "Enter array size: "; 42 | cin >> size; 43 | 44 | int arr[size]; 45 | cout << "Enter Elements: "; 46 | for(int i=0; i> arr[i]; 49 | } 50 | 51 | int key; 52 | cout << "Enter Search Key: "; 53 | cin >> key; 54 | 55 | // search for value 56 | int idx = binarySearch(arr,0 ,size-1, key); 57 | 58 | // display output 59 | if(idx >= 0){ 60 | cout << "Value found at index: " << idx; 61 | } 62 | else{ 63 | cout << "Value not found: "; 64 | } 65 | 66 | cout << endl; 67 | return 0; 68 | } 69 | 70 | /* 71 | OUTPUT: 72 | 73 | Case 1: 74 | Enter array size: 5 75 | Enter Elements: 1 3 4 5 15 76 | Enter Search Key: 5 77 | Value found at index: 3 78 | 79 | Case 2: 80 | Enter array size: 5 81 | Enter Elements: 1 3 4 5 15 82 | Enter Search Key: 2 83 | Value not found 84 | 85 | Case 3: 86 | Enter array size: 5 87 | Enter Elements: 1 3 4 5 15 88 | Enter Search Key: -10 89 | Value not found 90 | */ -------------------------------------------------------------------------------- /16_recursion_I_basics/06_recursion_power_n_multiply.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Time to Try Recursion! 3 | 4 | - Write a Recursive Functions to perform power(a,n) 5 | - Write a Recursive Functions to Multiply two numbers (a,b) without using * operator. 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | // functions to perform power(base,pow) 12 | int power(int n, int p) 13 | { 14 | // base case 15 | if(p == 0) 16 | { 17 | return 1; 18 | } 19 | // recursive case 20 | return n * power(n,p-1); 21 | } 22 | 23 | 24 | // functions to multiply two numbers (a,b) without using * operator 25 | int multiply(int a, int b) 26 | { 27 | // base case 28 | if(b==0) 29 | { 30 | return 0; 31 | } 32 | // recursive case 33 | return a + multiply(a, b-1); 34 | } 35 | 36 | 37 | // function to drive code 38 | int main() 39 | { 40 | int a,b; 41 | cout << "Enter Numbers [a & b]: "; 42 | cin >> a >> b; 43 | 44 | // compute power(base, pow) 45 | cout << "power(a,b): " << power(a,b) << endl; 46 | 47 | // muliply two number without using "*" 48 | cout << "multiply(a,b): " << multiply(a,b) << endl; 49 | 50 | return 0; 51 | } 52 | 53 | /* 54 | OUTPUT: 55 | 56 | Case 1: 57 | Enter Numbers [a & b]: 10 3 58 | power(a,b): 1000 59 | multiply(a,b): 30 60 | 61 | Case 2: 62 | Enter Numbers [a & b]: 5 3 63 | power(a,b): 125 64 | multiply(a,b): 15 65 | 66 | Case 3: 67 | Enter Numbers [a & b]: 2 4 68 | power(a,b): 16 69 | multiply(a,b): 8 70 | */ -------------------------------------------------------------------------------- /17_recursion_II_implementation/04_fast_power_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Fast Power Recursion 3 | 4 | compute a^n 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | 11 | // compute base^power (Time complexity: O(N)) 12 | int power(int b, int p) 13 | { 14 | // base case 15 | if(p == 0) 16 | { 17 | return 1; 18 | } 19 | // rec case 20 | return b * power(b, p-1); 21 | } 22 | 23 | 24 | // compute base^power (Time complexity: O(LogN) 25 | int fast_power(int b, int p) 26 | { 27 | // base case 28 | if(p == 0) 29 | { 30 | return 1; 31 | } 32 | // rec case 33 | int smaller_ans = fast_power(b, p/2); 34 | 35 | // whem power is odd 36 | if(p&1) 37 | { 38 | return b*smaller_ans*smaller_ans; 39 | } 40 | // whem power is even 41 | return smaller_ans*smaller_ans; 42 | 43 | /* 44 | APPROACH: 45 | 46 | When power is ODD: 47 | b^p = b(b^p/2)^2 48 | When power is EVEN: 49 | b^p = (b^p/2)^2 50 | 51 | Eg: base = a 52 | power = 9 53 | a^9 = a*(a^8) 54 | | 55 | (a^8) => (a^4)^2compute base^power 56 | | 57 | (a^4) => (a^2)^2 58 | | 59 | (a^2) => (a^1)^2 60 | | 61 | (a^1) => a(a^0) 62 | | 63 | (a^0) => (1) 64 | So, Number of steps needed to convert p to 1 is LogN 65 | */ 66 | } 67 | 68 | 69 | // function to drive code 70 | int main() 71 | { 72 | int a, b; 73 | cout << "Enter Numbers [a & b]: "; 74 | cin >> a >> b; 75 | 76 | cout << "a^b [Approach 1]: " << power(a,b) << endl; 77 | cout << "a^b [Approach 2]: " << fast_power(a,b) << endl; 78 | 79 | return 0; 80 | } 81 | 82 | /* 83 | OUTPUT: 84 | Enter Numbers [a & b]: 10 4 85 | a^b [Approach 1]: 10000 86 | a^b [Approach 2]: 10000 87 | */ 88 | -------------------------------------------------------------------------------- /18_recursion_III_quick_thinking/01_2048_problem_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - 2048 Problem Recursion 3 | 4 | Number to Spelling 5 | Input : 2048 6 | Output : two zero four eight 7 | 8 | APPRAOCH: 9 | - first make a recursive call (n/10) (i.e n/10 reducing number) 10 | - then print spelling of last digit (n%10) (i.e n%10 last digit) 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | // 2D character array of words as per index 17 | char words[][10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; 18 | 19 | 20 | void printSpellings(int num) 21 | { 22 | // base case 23 | if(num == 0) 24 | { 25 | return; 26 | } 27 | // rec case 28 | printSpellings(num/10); 29 | // after the function call print spellings 30 | int last_digit = num%10; 31 | cout << words[last_digit] << " "; 32 | return; 33 | } 34 | 35 | // function to drive code 36 | int main() 37 | { 38 | int num; 39 | cout << "Enter number: "; 40 | cin >> num; 41 | 42 | cout << "Output: "; 43 | printSpellings(num); 44 | 45 | cout << endl; 46 | return 0; 47 | } 48 | 49 | /* 50 | OUTPUT: 51 | 52 | Case 1: 53 | Enter number: 2048 54 | Output: two zero four eight 55 | 56 | Case 2: 57 | Enter number: 189642 58 | Output: one eight nine six four two 59 | */ -------------------------------------------------------------------------------- /18_recursion_III_quick_thinking/02_string_to_integer_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - String To Integer Recursion 3 | 4 | Given a string convert it into interger 5 | Eg: Input : "1234" 6 | Output : 1234 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | 13 | // function to convert string to integer recursively 14 | int strToInt(string s, int len) 15 | { 16 | // base case 17 | if(len < 0) 18 | { 19 | return 0; 20 | } 21 | // rec case 22 | int digit = s[len] - '0'; // Eg: '3' - '0' = 3 23 | int small_ans = strToInt(s, len-1); 24 | 25 | return (small_ans * 10) + (digit); // Eg: 12*10 + 3 = 123 26 | } 27 | 28 | 29 | // function to drive code 30 | int main() 31 | { 32 | string s; 33 | cout << "Enter String: "; 34 | cin >> s; 35 | 36 | int result = strToInt(s, s.length()-1); 37 | 38 | cout << "String to Int: " << result; 39 | cout << endl; 40 | return 0; 41 | } 42 | 43 | /* 44 | OUTPUT: 45 | 46 | Case 1: 47 | Enter String: 1234 48 | String to Int: 1234 49 | 50 | Case 2: 51 | Enter String: 15698 52 | String to Int: 15698 53 | */ -------------------------------------------------------------------------------- /18_recursion_III_quick_thinking/03_replace_pi_recursion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Replace Pi Recursion 3 | 4 | In a given a string, replace "pi" with "3.14" (inplace i.e without taking any extra space) 5 | Eg: Input : xpighpilmpipi 6 | Output : x3.14gh3.14lm3.143.14 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | 13 | // function to replace pi with 3.14 14 | void replacePi(char c[], int idx) 15 | { 16 | // base case 17 | if( c[idx] == '\0' or c[idx] == '\0') 18 | { 19 | return; 20 | } 21 | 22 | // rec case: Look for pi in current position 23 | if(c[idx] == 'p' and c[idx+1] == 'i') 24 | { 25 | // shifting + replacement with 3.14 26 | 27 | int j = idx+2; // pi = 2 charcater but 3.14 = 4 characters 28 | 29 | // take j to the end of the array (i.e until it points to NULL) 30 | while(c[j] != '\0') 31 | { 32 | j++; 33 | } 34 | // shifting (right to left) 35 | while(j >= idx+2) 36 | { 37 | c[j+2] = c[j]; 38 | j--; 39 | } 40 | // replacement with 3.14 41 | c[idx] = '3'; 42 | c[idx+1] = '.'; 43 | c[idx+2] = '1'; 44 | c[idx+3] = '4'; 45 | // recursive call on the remaining part 46 | replacePi(c, idx+4); 47 | } 48 | else{ 49 | // go to next position 50 | replacePi(c, idx+1); 51 | } 52 | 53 | return; 54 | } 55 | 56 | 57 | // function to drive code 58 | int main() 59 | { 60 | char c[1000]; 61 | cout << "Enter characters: "; 62 | cin >> c; 63 | 64 | replacePi(c, 0); 65 | 66 | cout << "After replacement: "; 67 | cout << c; 68 | 69 | cout << endl; 70 | return 0; 71 | } 72 | 73 | /* 74 | OUTPUT: 75 | 76 | Case 1: 77 | Enter characters: abcpixyz 78 | After replacement: abc3.14xyz 79 | 80 | Case 2: 81 | Enter characters: pistartpimidpiendpi 82 | After replacement: 3.14start3.14mid3.14end3.14 83 | 84 | */ -------------------------------------------------------------------------------- /20_recursion_V_backtracking/02_permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Permutations 3 | 4 | Given a string s, task is to find all permutation of the string s. 5 | 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | 12 | // function find all permutations 13 | void permute(char *inp, int idx) 14 | { 15 | // Base Case 16 | if(inp[idx] == '\0') 17 | { 18 | cout << inp << ", "; 19 | return; 20 | } 21 | // Recursive Case 22 | for(int j=idx; inp[j] != '\0'; j++) 23 | { 24 | swap(inp[idx], inp[j]); 25 | permute(inp, idx+1); 26 | // backtracing: to restore the original array 27 | swap(inp[idx], inp[j]); 28 | } 29 | } 30 | 31 | 32 | // function to drive code 33 | int main() 34 | { 35 | char ch[10]; 36 | cout << "Enter your string: "; 37 | cin >> ch; 38 | 39 | cout << "Permutations: "; 40 | permute(ch, 0); 41 | 42 | cout << endl; 43 | return 0; 44 | } 45 | 46 | /* 47 | OUTPUT: 48 | 49 | Case 1: 50 | Enter your string : abc 51 | Permutations : abc, acb, bac, bca, cba, cab, 52 | 53 | Case 2: 54 | Enter your string : aba 55 | Permutations : aba, aab, baa, baa, aba, aab, 56 | 57 | Case 3: 58 | Enter your string : 123 59 | Permutations : 123, 132, 213, 231, 321, 312, 60 | */ -------------------------------------------------------------------------------- /20_recursion_V_backtracking/03_unique_permutations_using_set.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Unique Permutations (using set STL) 3 | 4 | Given a string s, task is to find all unique permutation of the string s. 5 | 6 | Input : aba 7 | Output : aab, aba, baa 8 | 9 | Explaination: all permutaions: aab, aba, baa, baa, aba, aab, 10 | unique : aab, aba, baa, 11 | */ 12 | 13 | #include 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | 19 | // function find all permutations 20 | void uniquePermute(char *inp, int idx, set &s) 21 | { 22 | // Base Case 23 | if(inp[idx] == '\0') 24 | { 25 | // cout << inp << ", "; 26 | string str = inp; 27 | s.insert(str); 28 | return; 29 | } 30 | // Recursive Case 31 | for(int j=idx; inp[j] != '\0'; j++) 32 | { 33 | swap(inp[idx], inp[j]); 34 | uniquePermute(inp, idx+1, s); 35 | // backtracing: to restore the original array 36 | swap(inp[idx], inp[j]); 37 | } 38 | } 39 | 40 | 41 | // function to drive code 42 | int main() 43 | { 44 | char ch[100]; 45 | cout << "Enter your string: "; 46 | cin >> ch; 47 | 48 | set s; 49 | 50 | uniquePermute(ch, 0, s); 51 | 52 | // loop over the set s 53 | cout << "Unique Permutations: "; 54 | for(auto str:s) 55 | { 56 | cout << str << ", "; 57 | } 58 | 59 | cout << endl; 60 | return 0; 61 | } 62 | 63 | /* 64 | OUTPUT: 65 | 66 | Case 1: 67 | Enter your string : aba 68 | Unique Permutations : aab, aba, baa, 69 | 70 | Case 2: 71 | Enter your string : 121 72 | Unique Permutations : 112, 121, 211, 73 | */ -------------------------------------------------------------------------------- /20_recursion_V_backtracking/07_n_queen_advance_backtracking.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Agenda - Clear some of the backtracking concepts 3 | 4 | Questions 5 | --------- 6 | N-Queens Problem: 7 | - print/count 1 config 8 | - print/count all config 9 | 10 | Approaches 11 | --------- 12 | 1. Naive Backtracking Approach 13 | 2. Backtracing + Bitset (efficient) 14 | 3. Backtracking + Bitmasks (more efficient) [Advance Backtracking] 15 | (i.e how to use bitmask during backtracking) 16 | 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | 22 | int n; 23 | int count = 0, DONE; 24 | // rowmask denote which positions(columns) in all row are filled 25 | // ld, rd denotes unsafe positions along diagnols for the current row 26 | // DONE is vector of all 11111 (n times 1) 27 | // safe denotes the cols which are safe in current rowss 28 | 29 | 30 | // More optimisized n queen code ! 31 | void solveNQueens(int rowMask, int ld, int rd) 32 | { 33 | // Base Case 34 | if(rowMask == DONE) 35 | { 36 | count++; 37 | return; 38 | } 39 | 40 | // Recursive Case 41 | int safe = DONE & (~(rowMask | ld | rd)); 42 | while(safe) 43 | { 44 | int p = safe & (-safe); 45 | safe = safe -p; 46 | solveNQueens(rowMask | p, (ld | p) << 1, (rd | p) >> 1); 47 | } 48 | } 49 | 50 | 51 | // function to drive code 52 | int main() 53 | { 54 | int n; 55 | cout << "Enter Number of Queens: "; 56 | cin >> n; 57 | 58 | DONE = ((1 << n) - 1); 59 | 60 | solveNQueens(0, 0, 0); // using Bitmask Approach 61 | cout << "Total number of ways to place N-Queens: " << count; 62 | 63 | cout << endl; 64 | return 0; 65 | } 66 | 67 | /* 68 | OUTPUT: 69 | 70 | Case 1: 71 | Enter Number of Queens: 8 72 | Total number of ways to place N-Queens: 92 73 | 74 | Case 2: 75 | Enter Number of Queens: 3 76 | Total number of ways to place N-Queens: 0 77 | 78 | Case 3: 79 | Enter Number of Queens: 1 80 | Total number of ways to place N-Queens: 1 81 | */ -------------------------------------------------------------------------------- /21_more_Sorting_techniques_n_problems/04_counting_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Counting Sort 3 | 4 | Counting sort is a sorting algorithm that sorts the elements of an array by counting the number of 5 | occurrences of each unique element in the array. 6 | The count is stored in an auxiliary array and the sorting is done by mapping the count as an 7 | index of the auxiliary array. 8 | 9 | 10 | Eg: Sample Input: 6 11 | 2 2 1 6 6 3 12 | 13 | Sample Output: 1 2 2 3 6 6 14 | */ 15 | 16 | #include 17 | using namespace std; 18 | 19 | void counting_sort(int arr[], int size) 20 | { 21 | // find largest number in the array 22 | int largest_num = -1; 23 | for (int i = 0; i < size; i++) 24 | { 25 | largest_num = max(largest_num, arr[i]); 26 | } 27 | 28 | // create & update frequency array tillthe largest number 29 | int *freq = new int[largest_num+1]{0}; 30 | 31 | for(int i=0; i 0) 41 | { 42 | arr[j] = i; 43 | j++; 44 | freq[i]--; 45 | } 46 | } 47 | } 48 | 49 | 50 | int main() 51 | { 52 | int size; 53 | cout << "Enter array size: "; 54 | cin >> size; 55 | 56 | int arr[size]; 57 | cout << "Enter array elements: "; 58 | for (int i = 0; i < size; i++) 59 | { 60 | cin >> arr[i]; 61 | } 62 | 63 | counting_sort(arr, size); 64 | 65 | cout << "Sorted Array: "; 66 | for (int i = 0; i < size; i++) 67 | { 68 | cout << arr[i] << " "; 69 | } 70 | 71 | cout << endl; 72 | return 0; 73 | } 74 | 75 | 76 | /* 77 | OUTPUT: 78 | 79 | Case 1: 80 | Enter array size: 6 81 | Enter array elements: 2 2 1 6 6 3 82 | Sorted Array: 1 2 2 3 6 6 83 | 84 | Case 2: 85 | Enter array size: 9 86 | Enter array elements: 1 3 2 8 7 8 6 1 5 87 | Sorted Array: 1 1 2 3 5 6 7 8 8 88 | 89 | */ -------------------------------------------------------------------------------- /21_more_Sorting_techniques_n_problems/05_bucket_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Bucket Sort 3 | 4 | Bucket Sort is a sorting algorithm that divides the unsorted array elements into several groups 5 | called buckets. Each bucket is then sorted by using any of the suitable sorting algorithms or 6 | recursively applying the same bucket algorithm. 7 | Finally, the sorted buckets are combined to form a final sorted array. 8 | 9 | */ 10 | 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | class Student 16 | { 17 | public: 18 | int marks; 19 | string name; 20 | }; 21 | 22 | 23 | // bucket sort to sort an array of students 24 | void bucket_sort(Student s[], int n) 25 | { 26 | // assuming marks are in the range [0 to 100] 27 | vector v[101]; 28 | 29 | // O(N) time - Just iterationg over array & inserting students in the vector as per marks 30 | for(int i=0; i=0; i--) 38 | { 39 | for(vector::iterator it = v[i].begin(); it != v[i].end(); it++) 40 | { 41 | cout << (*it).marks << " " << (*it).name << endl; 42 | } 43 | } 44 | 45 | } 46 | 47 | 48 | // function to drive code 49 | int main() 50 | { 51 | int n; 52 | cout << "Enter total Students: "; 53 | cin >> n; 54 | 55 | Student s[n]; 56 | 57 | cout << "Enter Students [Marks & Name]: "; 58 | for(int i=0; i> s[i].marks >> s[i].name; 61 | } 62 | 63 | cout << "Sorted [As per Marks]: \n"; 64 | bucket_sort(s,n); 65 | 66 | return 0; 67 | } 68 | 69 | 70 | /* 71 | OUTPUT: 72 | 73 | Enter total Students: 6 74 | 75 | Enter Students [Marks & Name]: 76 | 39 Ario 77 | 65 Brad 78 | 54 Creo 79 | 98 Raman 80 | 25 Joy 81 | 65 Deep 82 | 83 | Sorted [As per Marks]: 84 | 98 Raman 85 | 65 Brad 86 | 65 Deep 87 | 54 Creo 88 | 39 Ario 89 | 25 Joy 90 | 91 | */ -------------------------------------------------------------------------------- /21_more_Sorting_techniques_n_problems/06_dnf_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - DNF Sort [Sort an array of 0s, 1s and 2s] 3 | 4 | Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. 5 | The functions should put all 0s first, then all 1s and all 2s in last. 6 | 7 | Examples: Input: {0, 1, 2, 0, 1, 2} 8 | Output: {0, 0, 1, 1, 2, 2} 9 | 10 | Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} 11 | Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2} 12 | 13 | Note: we can sort the above array using sorting algorithms like counting sort & more. 14 | But, by using DNF sort, we can sort the array in a single iteration, as well as inplace. 15 | */ 16 | 17 | #include 18 | using namespace std; 19 | 20 | // sort an array of 0s, 1s and 2s [inplace & using single iteration] 21 | void dnf_sort(int arr[], int size) 22 | { 23 | int lo = 0; // low pointer 24 | int hi = size-1; // high pointer 25 | int curr = 0; // current pointer 26 | 27 | while(curr <= hi) 28 | { 29 | if(arr[curr] == 0) 30 | { 31 | swap(arr[curr], arr[lo]); 32 | lo++; 33 | curr++; 34 | } 35 | else if(arr[curr] == 1) 36 | { 37 | curr++; 38 | } 39 | else 40 | swap(arr[curr], arr[hi]); 41 | hi--; 42 | /* Note: we will not increment curr pointer (i.e curr++) because we are not sure that arr[hi] is 43 | always having a value 2. It can also have value 0 or 1, So we have to again check arr[curr] 44 | in the next iteration. 45 | */ 46 | 47 | { 48 | 49 | } 50 | } 51 | } 52 | 53 | 54 | // function to drive code 55 | int main() 56 | { 57 | int arr[] = {2,1,1,1,1,0,1,1,1,0,0,2,0}; 58 | int size = sizeof(arr)/sizeof(int); 59 | 60 | cout << "Array: "; 61 | for(int i=0; i key) 21 | { 22 | end = mid - 1; 23 | } 24 | else 25 | { 26 | start = mid + 1; 27 | } 28 | } 29 | return -1; 30 | } 31 | 32 | Assume, array size = n 33 | __ Steps___ | ____Array Size______ 34 | 0 | n i.e = n/(2^0) 35 | 1 | n/2 i.e = n/(2^1) 36 | 2 | n/4 i.e = n/(2^2) 37 | 3 | n/8 i.e = n/(2^3) 38 | 3 | n/16 i.e = n/(2^4) 39 | ... | ... 40 | ... | ... 41 | (Suppose at k steps array size reached at 1) 42 | k steps | 1 i.e = n/(2^k) 43 | 44 | Now, at k-steps, 45 | 1 = n/(2^k) 46 | 2^k = n 47 | Taking (log base2) both sides 48 | log(2^k) = logn 49 | k = logn 50 | 51 | Time Complexity = O(logn) 52 | 53 | */ -------------------------------------------------------------------------------- /22_space_time_complexity_analysis/11_time_complexity_exercise.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC - Time Complexity Exercise 3 | 4 | ------------------------------------------------------------------------------------- 5 | // Exercise-I 6 | 7 | for(i=0; i<=n-1; i++) 8 | { 9 | for(j=i+1; j<=k; j++) 10 | { 11 | constant number of operations. 12 | } 13 | } 14 | 15 | j=0 j=k 16 | |-------------|---------------| 17 | 1 k n-1 18 | 19 | = k+(k-1)+....+1+0+0+0+.......... 20 | = (k^2 + (n-1-k) 21 | = O(n + k^2) 22 | = O(n^2) if k~N 23 | 24 | Time Complexity = O(n^2) 25 | 26 | 27 | ------------------------------------------------------------------------------------- 28 | // Exercise-II 29 | 30 | for(i=0; i<=n-1; i++) 31 | { 32 | for(j=i+1; j<=n; j++) 33 | { 34 | constant number of operations. 35 | } 36 | } 37 | 38 | ___i__|___j___ 39 | 1 | n 40 | 2 | n-1 41 | 3 | n-2 42 | ... | . 43 | ... | . 44 | ... | . 45 | n-2 | 3 46 | n-1 | 2 47 | n | 1 48 | 49 | Now, when the loop ends then, 50 | = (1+2+3+5+...+n) 51 | = __n_*_(n+1)__ 52 | 2 53 | = __(n^2)_+_1__ 54 | 2 55 | = (n^2) 56 | 57 | Time Complexity = O(n) 58 | 59 | 60 | ------------------------------------------------------------------------------------- 61 | // Exercise-III 62 | 63 | for(i=0; i<=n-1; ) 64 | { 65 | for(j=0; j If a function is defined as a friend function in C++, then the protected and private data of a class 5 | can be accessed using the function. 6 | > By using the keyword friend compiler knows the given function is a friend function. 7 | > For accessing the data, the declaration of a friend function should be done inside the body of a class 8 | starting with the keyword friend. 9 | 10 | Reference: https://www.javatpoint.com/cpp-friend-function 11 | 12 | 13 | Friend Class: 14 | - A friend class can access private and protected members of other class in which it is declared as friend. 15 | - It is sometimes useful to allow a particular class to access private members of other class. 16 | - For example: A LinkedList class may be allowed to access private members of Node. 17 | class Node 18 | { 19 | private: 20 | int key; 21 | Node *next; 22 | 23 | // Other members of Node Class 24 | friend class LinkedList; // Now class LinkedList can access private members of Node 25 | }; 26 | 27 | Friend Function: 28 | - Like friend class, a friend function can be given special grant to access private and protected members. 29 | - A friend function can be: 30 | a) A method of another class 31 | b) A global function 32 | - For example: 33 | class Node 34 | { 35 | private: 36 | int key; 37 | Node *next; 38 | 39 | // Other members of Node Class 40 | friend int LinkedList::search(); // Only search() of linked List can access internal members 41 | }; 42 | */ 43 | -------------------------------------------------------------------------------- /23_object_oriented_programming_concepts/11_this_pointer_in_cpp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: C++ this Pointer 3 | 4 | > In C++ programming, "this" is a keyword that refers to the current instance of the class. 5 | > There can be 3 main usage of this keyword in C++. 6 | - It can be used to pass current object as a parameter to another method. 7 | - It can be used to refer current class instance variable. 8 | - It can be used to declare indexers. 9 | 10 | */ 11 | 12 | 13 | // Example: this keyword in C++ that refers to the fields of current class. 14 | 15 | #include 16 | using namespace std; 17 | 18 | class Employee 19 | { 20 | public: 21 | int id; // data member (also instance variable) 22 | string name; // data member (also instance variable) 23 | float salary; 24 | 25 | Employee(int id, string name, float salary) 26 | { 27 | this->id = id; 28 | this->name = name; 29 | this->salary = salary; 30 | } 31 | 32 | void display() 33 | { 34 | cout << id << " " << name << " " << salary << endl; 35 | } 36 | }; 37 | 38 | 39 | int main() 40 | { 41 | Employee e1 = Employee(601, "Amit", 190000); // creating an object of Employee 42 | Employee e2 = Employee(602, "Deep", 79000); // creating an object of Employee 43 | 44 | e1.display(); 45 | e2.display(); 46 | 47 | return 0; 48 | } 49 | 50 | 51 | /* 52 | OUTPUT: 53 | 601 Amit 190000 54 | 602 Deep 79000 55 | */ -------------------------------------------------------------------------------- /24_generic_programming_in_cpp/01_generic_programming_with_templates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC: Generic Programming with Templates 3 | 4 | Basics: 5 | - The major advantage of C++ Standard Template Library(STL) is "all the containers" & "all the algorithms" 6 | provided by STL is generic. 7 | 8 | - Generic means they can work with different data types. 9 | Eg: if you want to sort array of intergers, you can use the sort function. 10 | if you want to sort array of books (objects), then also you can use the sort function. 11 | So, underline datatype doesn't matter. 12 | 13 | - The only thing that it will need is, How do you compare 2 book object ? 14 | For this, you have to define a comparison using a Comparator function (that will make the sort function 15 | work for a array of books) 16 | 17 | Generic Programming can be done a 2 levels:- 18 | 1. Algorithm 19 | 2. Container (data structures Eg: vector) 20 | 21 | Let's make a Generic Function! (at Algorithm Level) 22 | - the way to do is using Templates. 23 | 24 | Eg: template Or 25 | template 26 | */ 27 | 28 | 29 | #include 30 | using namespace std; 31 | 32 | // Linear Search 33 | template 34 | int search(T arr[], int n, T key) 35 | { 36 | for(int i=0; i // using <> for standard header files 13 | #include "vector.h" // using "" for user defined files 14 | // #include "../25_vectors/vector2.h" 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | Vector v; 20 | 21 | v.push_back(11); 22 | v.push_back(12); 23 | v.push_back(13); 24 | v.push_back(14); 25 | v.pop_back(); 26 | v.push_back(15); 27 | 28 | cout << "v.capacity: " << v.capacity() << endl; 29 | v.push_back(20); 30 | cout << "v.capacity: " << v.capacity() << endl; 31 | 32 | cout << "Vector v: "; 33 | for(int i=0; i< v.size(); i++) 34 | { 35 | cout << v[i] << " "; 36 | } 37 | cout << endl; 38 | 39 | cout << "v.size: " << v.size() << endl; 40 | 41 | return 0; 42 | } 43 | 44 | /* 45 | OUTPUT: 46 | 47 | v.capacity: 4 48 | v.capacity: 8 49 | 50 | Vector v: 11 12 13 15 20 51 | 52 | v.size: 5 53 | */ -------------------------------------------------------------------------------- /25_vectors/06_templates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC: Templates 3 | 4 | Converting a class into a Templated class 5 | 6 | Note: first view "vector2.h" file 7 | 8 | */ 9 | 10 | 11 | // Using user defined vector class 12 | 13 | #include // using <> for standard header files 14 | #include "vector2.h" // using "" for user defined files 15 | // #include "../25_vectors/vector2.h" 16 | using namespace std; 17 | 18 | int main() 19 | { 20 | // Vector2 v; // vector of int 21 | Vector2 v; // vector of char 22 | 23 | v.push_back(71); 24 | v.push_back(72); 25 | v.push_back(73); 26 | v.push_back(74); 27 | v.pop_back(); 28 | v.push_back(75); 29 | 30 | cout << "v.capacity: " << v.capacity() << endl; 31 | v.push_back(20); 32 | cout << "v.capacity: " << v.capacity() << endl; 33 | 34 | cout << "Vector v: "; 35 | for(int i=0; i< v.size(); i++) 36 | { 37 | cout << v[i] << " "; 38 | } 39 | cout << endl; 40 | 41 | cout << "v.size: " << v.size() << endl; 42 | 43 | return 0; 44 | } 45 | 46 | /* 47 | OUTPUT: [when, using vector of int] 48 | 49 | v.capacity: 4 50 | v.capacity: 8 51 | 52 | Vector v: 11 12 13 15 20 53 | v.size: 5 54 | 55 | 56 | OUTPUT: [when, using vector of char] 57 | 58 | v.capacity: 4 59 | v.capacity: 8 60 | 61 | Vector v: G H I K 62 | v.size: 5 63 | */ -------------------------------------------------------------------------------- /25_vectors/vector.h: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC: 05 - Container Design 3 | 4 | We will be designing our own vector class. 5 | To understand, How STL containers are implemented ? 6 | 7 | NOTE: filename: vector.h 8 | 9 | */ 10 | 11 | class Vector 12 | { 13 | int cs; // cs: current size 14 | int ms; // cs: max size 15 | int *arr; // pointer 16 | 17 | public: 18 | Vector() // constructor 19 | { 20 | cs = 0; 21 | ms = 1; 22 | arr = new int[ms]; 23 | } 24 | 25 | void push_back(const int d) // d: data 26 | { 27 | if(cs == ms) 28 | { 29 | int *oldArr = arr; 30 | arr = new int[2*ms]; 31 | ms = 2*ms; 32 | for(int i=0; i 11 | class Vector2 12 | 13 | { 14 | int cs; // cs: current size 15 | int ms; // cs: max size 16 | T *arr; // pointer 17 | 18 | public: 19 | Vector2() // constructor 20 | { 21 | cs = 0; 22 | ms = 1; 23 | arr = new T[ms]; 24 | } 25 | 26 | void push_back(const T d) // d: data 27 | { 28 | if(cs == ms) 29 | { 30 | T *oldArr = arr; 31 | arr = new T[2*ms]; 32 | ms = 2*ms; 33 | for(int i=0; i|1|300|------- _300_ _200_ 11 | node* int Address '------>|3|200|------>|2|400|---- _400__ 12 | |------| '------->|4|NULL| 13 | node |------| 14 | node 15 | 16 | - So, Linked list are collection of nodes allocated in the memory that stores data. 17 | 18 | - Some time we also need to store the address of the last node, if we want to perform operation 19 | at the end of linked list. 20 | 21 | |100| ---- _100_ 22 | head '------>|1|300|------- _300_ _200_ 23 | node* int Address '------>|3|200|------>|2|400|---- _400__ 24 | |------| '------->|4|NULL|--->|400| 25 | node |------| tail 26 | node node* 27 | */ 28 | 29 | -------------------------------------------------------------------------------- /26_linked_lists/07_input.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 5 3 | 9 4 | 10 5 | 3 6 | 19 7 | 7 8 | -1 -------------------------------------------------------------------------------- /26_linked_lists/19_forward_list_stl.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC: Forward List STL 3 | 4 | Forward lists are implemented as singly-linked lists. 5 | 6 | Compared to other base standard sequence containers (array, vector and deque), forward_list perform 7 | generally better in inserting, extracting and moving elements in any position within the container, 8 | and therefore also in algorithms that make intensive use of these, like sorting algorithms. 9 | 10 | The main drawback of forward_lists and lists compared to these other sequence containers is that they 11 | lack direct access to the elements by their position. 12 | For example, to access the sixth element in a forward_list one has to iterate from the beginning to 13 | that position, which takes linear time in the distance between these. 14 | 15 | Ref: https://www.cplusplus.com/reference/forward_list/forward_list/ 16 | 17 | */ 18 | -------------------------------------------------------------------------------- /26_linked_lists/20_list_stl_I.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC: List STL - I 3 | 4 | List => Doubly Linked List 5 | Useful in insert & delete from front, middle & tail. 6 | (as it takes O(1) time in front & tail insertion) 7 | 8 | Unlike in vector, If we want to insert some element in the front & middle, we first have to shift 9 | all the elements. 10 | 11 | Some useful Methods in List stl:- 12 | - push_back : insert at tail 13 | - push_front : insert at head 14 | - pop_back : remove at tail 15 | - pop_front : remove from front 16 | - insert : insert in the middle 17 | - erase(idx) : erase some of the elements 18 | - remove(val) : remove all occurance of some value 19 | */ 20 | 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | int main() 26 | { 27 | list l; 28 | 29 | // Init 30 | list l1{1,2,3,10,8,5}; 31 | list l2{"apple","guava","mango","banana"}; 32 | l2.push_back("pineapple"); 33 | 34 | // Iterate over list and print the data 35 | for(auto s:l2) 36 | // for(string s:l2) 37 | { 38 | cout << s << "-->"; 39 | } 40 | cout << endl; 41 | 42 | // sort 43 | l2.sort(); // lexographic sorting of strings 44 | 45 | // reverse 46 | l2.reverse(); 47 | 48 | // pop_front 49 | cout << l2.front() << endl; // display front element 50 | l2.pop_front(); 51 | 52 | // print the data 53 | for(auto s:l2) 54 | { 55 | cout << s << "-->"; 56 | } 57 | cout << endl; 58 | 59 | // add to the front of the list 60 | l2.push_front("kiwi"); 61 | 62 | cout << l2.back() << endl; // display last element 63 | l2.pop_back(); 64 | 65 | // print the data 66 | for(auto s:l2) 67 | { 68 | cout << s << "-->"; 69 | } 70 | cout << endl; 71 | 72 | // Iterate over list using iterators 73 | for(auto it = l2.begin(); it != l2.end(); it++) 74 | { 75 | cout << (*it) << "-->"; 76 | } 77 | cout << endl; 78 | 79 | return 0; 80 | } 81 | 82 | /* 83 | OUTPUT: 84 | 85 | apple-->guava-->mango-->banana-->pineapple 86 | 87 | pineapple 88 | mango-->guava-->banana-->apple 89 | 90 | apple 91 | kiwi-->mango-->guava-->banana 92 | 93 | kiwi-->mango-->guava-->banana 94 | */ -------------------------------------------------------------------------------- /26_linked_lists/23_cpp_notes_on_linked_list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Stanford CS Notes on Linked Lists 4 | 5 | The following notes will helpful. Students are advised to give a read and practice the given Linked List Problems. 6 | Many of the problems have been discussed in above program as well. 7 | 8 | - Pointers and Memory 9 | [Download PDF] URL: http://cslibrary.stanford.edu/102/PointersAndMemory.pdf 10 | 11 | - Linked List Problems 12 | [Download PDF] URL: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf 13 | 14 | */ -------------------------------------------------------------------------------- /27_stacks/01_stack_introduction.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TOPIC: Stack - Introduction 3 | 4 | Stack is data structure which maintains information in the LIFO order. 5 | LIFO -> Last In First Out 6 | 7 | Stack can be inplemented using Array, 8 | using Linked List, 9 | using Vector 10 | 11 | Important operation in stack: 12 | - Push (Insertion of data) 13 | - Pop (Removal of data) 14 | - Top (viewing the topmost element) 15 | 16 | - isEmpty() (check if stack is empty) 17 | - isFull() (check if stack is full) 18 | */ -------------------------------------------------------------------------------- /exercise_01_fundamentals/01_von_neuman_loves_binary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem - Given a binary number ,help Von Neuman to find out its decimal representation. 3 | For eg 000111 in binary is 7 in decimal. 4 | 5 | Input Format - The first line contains N , the number of binary numbers. Next N lines contain N integers each representing binary represenation of number. 6 | 7 | Constraints - N<=1000 Digits in binary representation is <=16. 8 | 9 | Output Format - N lines,each containing a decimal equivalent of the binary number. 10 | 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | int main() { 17 | int total_inputs, bin_val; 18 | cin>>total_inputs; 19 | 20 | while(total_inputs>0){ 21 | cin>>bin_val; 22 | int temp = bin_val; 23 | int base = 1; 24 | int dec_val = 0; 25 | while(temp>0){ 26 | int last_digit = temp%10; // Extract rightmost digit 27 | dec_val = dec_val + (last_digit * base); // add the digit to answer 28 | base = base * 2; // update the power of 2 29 | temp = temp / 10; // update the number 30 | } 31 | cout< 13 | using namespace std; 14 | #define ll long long int 15 | 16 | int main() { 17 | ll num; 18 | cout<<"Enter the number: "; 19 | 20 | while(cin>>num){ 21 | if(num<3){ //No Pythagoras Triplet exists 22 | cout<<"-1"< 23 | using namespace std; 24 | int main() { 25 | int num, cumulative_sum=0; 26 | cout<<"Enter values for cumulative sum: "; 27 | 28 | while (cumulative_sum>=0){ 29 | cin>>num; 30 | cumulative_sum = cumulative_sum+num; 31 | if(cumulative_sum>=0){ 32 | cout< 29 | using namespace std; 30 | 31 | int main() { 32 | int num1, num2, ans, count=1; 33 | cout<<"Enter num1 & num2: "; 34 | cin>>num1>>num2; 35 | 36 | for(int step=1; count<=num1; step++){ 37 | ans = (3*step)+2; 38 | if(ans%num2 != 0){ 39 | cout< 24 | using namespace std; 25 | 26 | int main() { 27 | int number, digit, count=0; 28 | cout<<"Enter number & digit: "; 29 | cin>>number>>digit; 30 | 31 | while (number>0){ 32 | int rem = number%10; 33 | if(digit == rem) count++; 34 | number = number/10; 35 | } 36 | cout<<"Total counts: "< 36 | using namespace std; 37 | 38 | int main() { 39 | char ch; 40 | cin>>ch; 41 | 42 | int num1, num2; 43 | while(ch!='x' and ch!='X'){ 44 | if(ch=='+'){ 45 | cin>>num1>>num2; 46 | cout<>num1>>num2; 49 | cout<>num1>>num2; 52 | cout<>num1>>num2; 55 | cout<>num1>>num2; 58 | cout<>ch; 63 | } 64 | return 0; 65 | } 66 | 67 | /* 68 | Simply Put a loop and take input operator and then take input of two digits and then perform the operation till the user inputs 'x' or 'X'. 69 | */ -------------------------------------------------------------------------------- /exercise_01_fundamentals/11_decimal_tooctal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Take N (number in decimal format). Write a function that converts it to octal format. Print the value returned. 3 | 4 | Constraints: 0 < N <= 1000000000 5 | 6 | Sample Input: 63 7 | 8 | Sample Output: 77 9 | 10 | Explanation: Both input and output are integers 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | 16 | int main() { 17 | int decimal_num; 18 | cin>>decimal_num; 19 | 20 | int octal_num=0, pow=1; 21 | 22 | while(decimal_num > 0){ 23 | int rem = decimal_num%8; 24 | octal_num = octal_num + (pow*rem); 25 | pow = pow * 10; 26 | decimal_num = decimal_num/8; 27 | } 28 | cout< 26 | using namespace std; 27 | 28 | int pow(int num,int power){ 29 | if (num == 0) 30 | return 0; 31 | else if (power == 0) 32 | return 1; 33 | int res=1; 34 | while(power--){ 35 | res *= num; 36 | } 37 | return res; 38 | } 39 | 40 | int check_armstrong(int num, int power){ 41 | int sum = 0; 42 | int val = num; 43 | while(val){ 44 | int rem = val%10; 45 | sum = sum + pow(rem,power); 46 | val /= 10; 47 | } 48 | return sum == num; 49 | } 50 | 51 | int main() { 52 | int num; 53 | cin >> num; 54 | 55 | int val = num; 56 | int no_of_digits = 0; 57 | while(val){ 58 | no_of_digits++; 59 | val /= 10; 60 | } 61 | 62 | bool is_armstrong = check_armstrong(num, no_of_digits); 63 | if(is_armstrong) 64 | cout << "true"; 65 | else 66 | cout << "false"; 67 | return 0; 68 | } 69 | 70 | /* 71 | Algorithm 72 | 73 | - Take input of number. 74 | - Calculate the number of digits of the number in a variable say , cnt. 75 | - Extract digit one by one from the number(using % 10). 76 | - Raise it to the power of number of digits and add it to sum. 77 | - After the loop check if the sum is equal to the original number. 78 | If yes, print true 79 | otherwise, print false. 80 | */ -------------------------------------------------------------------------------- /exercise_01_fundamentals/14_check_prime.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Take as input a number N, print "Prime" if it is prime if not Print "Not Prime". 3 | 4 | Constraints: 2 < N <= 1000000000 5 | 6 | Sample Input: 3 7 | 8 | Sample Output: Prime 9 | 10 | Explanation: The output is case specific 11 | */ 12 | 13 | #include 14 | using namespace std; 15 | int main() { 16 | int num; 17 | cin >> num; 18 | 19 | bool is_prime = true; 20 | int divisor = 2; 21 | while (divisor < num){ 22 | if(num%divisor == 0){ 23 | is_prime = false; 24 | break; 25 | } 26 | divisor++; 27 | } 28 | if(is_prime) 29 | cout << "Prime"; 30 | else 31 | cout << "Not Prime"; 32 | return 0; 33 | } 34 | 35 | /* 36 | Any number which has only two divisors, one divisor is the number itself and other divisor is 1, is called as Prime number. 37 | 38 | Algorithmn: 39 | Take input of the number. 40 | put a loop from 2 to that number. 41 | If the number gets divided by any number in the loop, that means the number is not Prime. 42 | Othewise, Prime. 43 | */ -------------------------------------------------------------------------------- /exercise_01_fundamentals/15_binary_to_decimal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Take N (number in binary format). Write a function that converts it to decimal format and Print the value returned. 3 | Constraints: 0 < N <= 1000000000 4 | 5 | Sample Input: 101010 6 | Sample Output: 42 7 | 8 | Explanation: For binary number fedcba , Decimal number = f * 25 + e * 24 + d * 23 + …..+ a * 20. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | int main() { 14 | int b_num; 15 | cin >> b_num; 16 | int pow = 1; 17 | int d_num = 0; 18 | while(b_num){ 19 | int rem = b_num%10; 20 | d_num += (rem * pow); 21 | pow *= 2; 22 | b_num /= 10; 23 | } 24 | cout << d_num; 25 | return 0; 26 | } 27 | 28 | /* 29 | For binary number fedcba , Decimal number = f.2^5 + e.2^4 + d.2^3 + …..+ a.2^0. 30 | 31 | The idea is to extract the digits of given binary number starting from right most digit and keep a variable decvalue. 32 | At the time of extracting digits from the binary number, multiply the digit with the proper base (Power of 2) 33 | and add it to the variable dec_value. 34 | At the end, the variable decvalue will store the required decimal number. 35 | */ -------------------------------------------------------------------------------- /exercise_01_fundamentals/16_print_reverse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Take N as input, Calculate it's reverse also Print the reverse. 3 | Constraints: 0 <= N <= 1000000000 4 | 5 | Sample Input: 123456789 6 | Sample Output: 987654321 7 | 8 | Explanation: You've to calculate the reverse in a number, not just print the reverse. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | // function to calculate power 15 | int fast_pow(int num, int power){ 16 | if(num == 0) 17 | return 0; 18 | else if(power == 0) 19 | return 1; 20 | int res = 1; 21 | while(power--){ 22 | res *= num; 23 | } 24 | return res; 25 | } 26 | 27 | int main() { 28 | int num; 29 | cin >> num; 30 | //Calculating the digit count 31 | int temp = num; 32 | int digit_count = 0; 33 | while (temp){ 34 | digit_count++; 35 | temp /= 10; 36 | } 37 | //Calculating reverse 38 | int reverse = 0; 39 | temp = num; 40 | while(temp){ 41 | int rem = temp%10; 42 | digit_count--; 43 | reverse += (rem * fast_pow(10,(digit_count))); 44 | temp /= 10; 45 | } 46 | cout << reverse; 47 | return 0; 48 | } 49 | 50 | /* 51 | For the Given input: 123456789 52 | The corresponding ans is 987654321,To achieve this answer we must know how to access the last digit of a number viz, if we perform modulus 10 with any number we got the last digit of that number. 53 | 54 | for e.g, 123 % 10 = 3, and now to modify the number we need to remove the 3 from the digit as it is accounted so we have perfrom divide by 10 action to reduce the length by 1. 55 | for e.g., 123 / 10 = 12. we must perform both the operations till we got Zero as the number, and most importantly to build the ans we can construct it by multipying it by 10 and then add to the answer. 56 | for e.g., ans = 12, if u want to add 3 so u need to multiply 12 by 10 and then add the num, so it become 12*10 + 3 = 123. 57 | 58 | Code: public static int reverse(int n){ 59 | int ans = 0; 60 | while(n != 0){ 61 | int digit = n % 10; 62 | ans = ans *10 + digit; 63 | n /= 10; 64 | } 65 | return ans; 66 | } 67 | */ -------------------------------------------------------------------------------- /exercise_02_patterns/08_pattern _inverted_HourGlass.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pattern Inverted HourGlass 3 | 4 | Take N as input. For a value of N=5, we wish to draw the following pattern : 5 | 6 | 5 5 7 | 5 4 4 5 8 | 5 4 3 3 4 5 9 | 5 4 3 2 2 3 4 5 10 | 5 4 3 2 1 1 2 3 4 5 11 | 5 4 3 2 1 0 1 2 3 4 5 12 | 5 4 3 2 1 1 2 3 4 5 13 | 5 4 3 2 2 3 4 5 14 | 5 4 3 3 4 5 15 | 5 4 4 5 16 | 5 5 17 | 18 | Input Format: Take N as input. 19 | 20 | Output Format: Pattern should be printed with a space between every two values. 21 | 22 | Sample Input: 5 23 | 24 | Sample Output: 5 5 25 | 5 4 4 5 26 | 5 4 3 3 4 5 27 | 5 4 3 2 2 3 4 5 28 | 5 4 3 2 1 1 2 3 4 5 29 | 5 4 3 2 1 0 1 2 3 4 5 30 | 5 4 3 2 1 1 2 3 4 5 31 | 5 4 3 2 2 3 4 5 32 | 5 4 3 3 4 5 33 | 5 4 4 5 34 | 5 5 35 | */ 36 | 37 | #include 38 | using namespace std; 39 | 40 | int main() { 41 | int total_rows; 42 | cin >> total_rows; 43 | 44 | int nop = 1; 45 | int nos = (total_rows*2)-1; 46 | 47 | for(int row=1; row<=(total_rows*2)+1; row++){ 48 | int val = total_rows; 49 | // for pattern 50 | for(int cop=1; cop<=nop; cop++){ 51 | cout << val <<" "; 52 | val--; 53 | } 54 | // for space 55 | for(int cos=1; cos<=nos; cos++){ 56 | cout << " "; 57 | } 58 | // for pattern 59 | for(int cop=1; cop<=nop; cop++){ 60 | if(nop == total_rows+1 && cop == 1){ 61 | cop++; 62 | val++; 63 | } 64 | val++; 65 | cout << val << " "; 66 | } 67 | 68 | // for next iteration 69 | if(row < total_rows+1){ 70 | nop++; 71 | nos = nos-2; 72 | }else{ 73 | nop--; 74 | nos = nos+2; 75 | } 76 | cout << endl; 77 | } 78 | return 0; 79 | } -------------------------------------------------------------------------------- /exercise_02_patterns/10_hollow_diamond_pattern.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Hollow Diamond Pattern 3 | 4 | Take N (number of rows), print the following pattern (for N = 5). 5 | * * * * * 6 | * * * * 7 | * * 8 | * * * * 9 | * * * * * 10 | 11 | Constraints: 0 < N < 10 (where N is an odd number) 12 | 13 | Sample Input: 5 14 | 15 | Sample Output: * * * * * 16 | * * * * 17 | * * 18 | * * * * 19 | * * * * * 20 | 21 | Explanation: Each '*' is separated from other by a tab. 22 | */ 23 | 24 | #include 25 | using namespace std; 26 | 27 | int main() { 28 | int total_rows; 29 | cin >> total_rows; 30 | 31 | int mid = (total_rows/2)+1; // middle row 32 | int nop = (total_rows/2)+1; // number of pattern in first row 33 | int nos = -1; // number of space in first row 34 | 35 | for(int row=1; row<=total_rows; row++){ 36 | int cop; // counter of pattern 37 | int cos; // counter of spaces 38 | //printing pattern 39 | for(cop=1; cop<=nop; cop++){ 40 | cout << "*" << "\t"; 41 | } 42 | // printing spaces 43 | for(cos=1; cos<=nos; cos++){ 44 | cout << " " << "\t"; 45 | } 46 | // printing pattern 47 | for(cop=1; cop<=nop; cop++){ 48 | if((cop==1 && row == 1) || (cop==1 && row == total_rows)) 49 | continue; // to handle extra star 50 | cout << "*" << "\t"; 51 | } 52 | 53 | // for next iterations 54 | if(row < mid){ 55 | nop--; 56 | nos += 2; 57 | }else{ 58 | nop++; 59 | nos -= 2; 60 | } 61 | cout << endl; 62 | } 63 | return 0; 64 | } -------------------------------------------------------------------------------- /exercise_02_patterns/13_pattern_and_star_1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pattern Numbers & Stars - 1 3 | 4 | Take as input N, a number. Print the pattern as given in output section for corresponding input. 5 | 6 | Input Format: Enter value of N 7 | 8 | Output Format: All numbers and stars are Space separated 9 | 10 | Sample Input: 5 11 | 12 | Sample Output: 1 2 3 4 5 13 | 1 2 3 4 * 14 | 1 2 3 * * * 15 | 1 2 * * * * * 16 | 1 * * * * * * * 17 | 18 | Explanation: Catch the pattern for the corresponding input and print them accordingly. 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | 24 | int main() { 25 | int total_rows; 26 | cin >> total_rows; 27 | 28 | int nop = total_rows; // number of pattern in first row 29 | int nos = -1; // number of star in first row 30 | 31 | for(int row=1; row<=total_rows; row++){ 32 | int cop; // counter of pattern 33 | int cos; // counter of star 34 | // print number pattern 35 | for(cop=1; cop<=nop; cop++){ 36 | cout << cop << " "; 37 | } 38 | // print stars 39 | for(cos=1; cos<=nos; cos++){ 40 | cout << "*" << " "; 41 | } 42 | // for next iterations 43 | nop--; 44 | nos += 2; 45 | cout << endl; 46 | } 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /exercise_02_patterns/14_pattern_and_star_2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pattern Numbers & Stars - 2 3 | 4 | Take as input N, a number. Print the pattern as given in the input and output section. 5 | 6 | Input Format: Enter value of N 7 | 8 | Constraints: 1 <= N < 10 9 | 10 | Output Format: Print the pattern. 11 | 12 | Sample Input: 7 13 | 14 | Sample Output: 1****** 15 | 12***** 16 | 123**** 17 | 1234*** 18 | 12345** 19 | 123456* 20 | 1234567 21 | 22 | Explanation: There is no space between any two numbers. Catch the pattern for corresponding input and print them accordingly. 23 | */ 24 | 25 | #include 26 | using namespace std; 27 | 28 | int main() { 29 | int total_rows; 30 | cin >> total_rows; 31 | 32 | int nop = 1; // number of pattern in first row 33 | int nos = total_rows-1; // number of star in first row 34 | 35 | for(int row=1; row<=total_rows; row++){ 36 | int cop; // counter of pattern 37 | int cos; // counter of star 38 | // print number pattern 39 | for(cop=1; cop<=nop; cop++){ 40 | cout << cop; 41 | } 42 | // print stars 43 | for(cos=1; cos<=nos; cos++){ 44 | cout << "*"; 45 | } 46 | 47 | // for next iterations 48 | nop++; 49 | nos--; 50 | cout << endl; 51 | } 52 | return 0; 53 | } -------------------------------------------------------------------------------- /exercise_03_arrays/01_max_value_in_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Max Value in Array 3 | 4 | Take as input N, the size of array. Take N more inputs and store that in an array. 5 | Write a function which returns the maximum value in the array. Print the value returned. 6 | 1.It reads a number N. 7 | 2.Take Another N numbers as input and store them in an Array. 8 | 3.calculate the max value in the array and return that value. 9 | 10 | Input Format: First line contains integer n as size of array. 11 | Next n lines contains a single integer as element of array. 12 | 13 | Constraints: N cannot be Negative. Range of Numbers can be between -1000000000 to 1000000000 14 | 15 | Output Format: Print the required output. 16 | 17 | Sample Input: 4 18 | 2 19 | 8 20 | 6 21 | 4 22 | 23 | Sample Output: 8 24 | 25 | Explanation: Arrays= {2, 8, 6, 4} => Max value = 8 . 26 | 27 | */ 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | int main() { 34 | int range; 35 | cout << "Enter array range: "; 36 | cin >> range; 37 | 38 | int arr[range]; 39 | int maxVal = INT_MIN; 40 | 41 | cout << "Enter array elements: "; 42 | for(int idx=0; idx<=range-1; idx++){ 43 | cin >> arr[idx]; 44 | if(arr[idx]>maxVal){ 45 | maxVal = arr[idx]; 46 | } 47 | } 48 | cout << "Max array value: "; 49 | cout << maxVal < 23 | using namespace std; 24 | 25 | int main() { 26 | int rows, cols; 27 | cout << "Enter array [Rows & Cols]: "; 28 | cin >> rows >> cols; 29 | 30 | int arr[rows][cols]; 31 | cout << "Enter array elements: \n"; 32 | for(int row=0; row<=rows-1; row++){ 33 | for(int col=0; col<=cols-1; col++){ 34 | cin >> arr[row][col]; 35 | 36 | } 37 | } 38 | 39 | //wave pattern 40 | cout << "Wave Pattern: "; 41 | for(int col=0; col<=cols-1; col++){ 42 | if(col%2 == 0){ 43 | for(int row=0; row<=rows-1; row++){ 44 | cout << arr[row][col] << ", "; 45 | } 46 | }else{ 47 | for(int row=rows-1; row>=0; row--){ 48 | cout << arr[row][col] << ", "; 49 | } 50 | } 51 | } 52 | cout << "END" << endl; 53 | return 0; 54 | } -------------------------------------------------------------------------------- /exercise_03_arrays/03_target_sum_pairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Array - Target Sum Pairs 3 | 4 | Take as input N, the size of array. 5 | Take N more inputs and store that in an array. 6 | Take as input “target”, a number. 7 | Write a function which prints all pairs of numbers which sum to target. 8 | 9 | Input Format: The first line contains input N. 10 | Next N lines contains the elements of array and (N+1)th line contains target number. 11 | 12 | Constraints: Length of the arrays should be between 1 and 1000. 13 | 14 | Output Format: Print all the pairs of numbers which sum to target. Print each pair in increasing order. 15 | 16 | Sample Input: 5 17 | 1 18 | 3 19 | 4 20 | 2 21 | 5 22 | 5 23 | 24 | Sample Output: 1 and 4 25 | 2 and 3 26 | 27 | Explanation: Find any pair of elements in the array which has sum equal to target element and print them. 28 | 29 | */ 30 | 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | void targetSum(int arr[], int range, int target){ 36 | // sorting array 37 | sort(arr, arr+range); 38 | 39 | int start = 0; 40 | int end = range-1; 41 | while(start> range; 59 | 60 | int arr[range]; 61 | cout << "Enter array elements: "; 62 | for(int idx=0; idx<=range-1; idx++){ 63 | cin >> arr[idx]; 64 | } 65 | 66 | int target; 67 | cout << "Enter Target value: "; 68 | cin >> target; 69 | 70 | cout << "All pairs of numbers which sum to target : \n"; 71 | targetSum(arr, range, target); 72 | 73 | return 0; 74 | } -------------------------------------------------------------------------------- /exercise_03_arrays/10_rotate_image_90_degree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Name: Rotate Image(N x N Array) 3 | 4 | Given a 2D array of size N x N. Rotate the array 90 degrees anti-clockwise. 5 | 6 | Input Format: First line contains a single integer N. Next N lines contain N space separated integers. 7 | 8 | Constraints: N < 1000 9 | 10 | Output Format: Print N lines with N space separated integers of the rotated array. 11 | 12 | Sample Input: 4 13 | 1 2 3 4 14 | 5 6 7 8 15 | 9 10 11 12 16 | 13 14 15 16 17 | 18 | 19 | Sample Output: 4 8 12 16 20 | 3 7 11 15 21 | 2 6 10 14 22 | 1 5 9 13 23 | 24 | Explanation: Rotate the array 90 degrees anticlockwise. 25 | */ 26 | 27 | #include 28 | using namespace std; 29 | 30 | int main() { 31 | int rows, cols; 32 | cout << "Enter Matrix [Rows & Cols]: "; 33 | cin >> rows >> cols; 34 | 35 | int arr[rows][cols]; 36 | cout << "Enter matrix values: \n"; 37 | for (int row=0; row<=rows-1; row++){ 38 | for(int col=0; col<=cols-1; col++){ 39 | cin >> arr[row][col]; 40 | } 41 | } 42 | 43 | // Step:1 Reverse the column 44 | for(int idx=0; idx<=rows-1; idx++){ 45 | int start = 0; 46 | int end = cols-1; 47 | while(start col){ 58 | swap(arr[row][col], arr[col][row]); 59 | } 60 | } 61 | } 62 | 63 | // Print array after 90 degree rotation 64 | cout << "Array in spiral form anticlock wise: \n"; 65 | for (int row=0; row<=rows-1; row++){ 66 | for(int col=0; col<=cols-1; col++){ 67 | cout << arr[row][col] << " "; 68 | } 69 | cout << endl; 70 | } 71 | 72 | return 0; 73 | } 74 | 75 | -------------------------------------------------------------------------------- /exercise_04_strings/01_difference_in_ascii_codes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Name: String - Difference in Ascii Codes 3 | 4 | Take as input S, a string. Write a program that inserts between each pair of 5 | characters the difference between their ascii codes and print the ans. 6 | 7 | Input Format: String 8 | 9 | Constraints: Length of String should be between 2 to 1000. 10 | 11 | Output Format: String 12 | 13 | Sample Input: acb 14 | 15 | Sample Output: a2c-1b 16 | 17 | Explanation: For the sample case, the Ascii code of a=97 and c=99, 18 | the difference between c and a is 2. Similarly, 19 | the Ascii code of b=98 and c=99 and their difference is -1. 20 | So the ans is a2c-1b. 21 | */ 22 | 23 | #include 24 | using namespace std; 25 | 26 | int main() { 27 | string s; 28 | cout << "Enter your string: "; 29 | getline(cin, s); 30 | 31 | cout << "Output: "; 32 | int end = s.length()*2; 33 | int idx = 0; 34 | for(int step=0; step<=end-2; step++){ 35 | if(step%2 == 0){ 36 | cout << s[idx]; 37 | idx++; 38 | }else{ 39 | cout << s[idx]-s[idx-1]; 40 | } 41 | } 42 | cout << endl; 43 | return 0; 44 | } 45 | 46 | /* 47 | 48 | Approach: 49 | 50 | All we need to do is just traverse the whole string and 51 | for every two adjacent characters just calculate the ascii among them. 52 | We will print the characters and the difference between with characters 53 | 54 | Required Code is given below : 55 | 56 | #include 57 | #include 58 | using namespace std; 59 | 60 | int main() { 61 | char str[1000]; 62 | int nstr[2000]; 63 | cin>>str; 64 | int i=1; 65 | cout< 23 | #include 24 | using namespace std; 25 | 26 | // function to print character type 27 | void getCharacterType(char ch) 28 | { 29 | if(ch >= 'A' && ch <= 'Z'){ 30 | cout << "U"; 31 | }else if(ch >= 'a' && ch <= 'z'){ 32 | cout << "L"; 33 | }else{ 34 | cout << "I"; 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | char ch; 41 | cout << "Enter you character: "; 42 | cin >> ch; 43 | 44 | getCharacterType(ch); 45 | cout << endl; 46 | 47 | return 0; 48 | } 49 | 50 | /* 51 | Approach: 52 | 53 | Problem statement is quite easy you just need to tell whether the character entered is Lower case or Uppercase otherwise print I. 54 | We can also compare characters directly without remembering the ascii codes. 55 | 56 | Code: 57 | 58 | public static char tell(char ch) { 59 | 60 | if(ch >= 'a' && ch <= 'z') 61 | return 'L'; 62 | else if(ch >= 'A' && ch <= 'Z') 63 | return 'U'; 64 | else 65 | return 'I'; 66 | 67 | } 68 | */ -------------------------------------------------------------------------------- /exercise_04_strings/09_lower_upper.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Name: Lower Upper 3 | 4 | Print "lowercase" if user enters a character between 'a-z' , 5 | Print "UPPERCASE" is character lies between 'A-Z' and 6 | print "Invalid" for all other characters like $,.^# etc. 7 | 8 | Input Format: Single Character 9 | 10 | Constraints: No constraints 11 | 12 | Output Format: lowercase UPPERCASE Invalid 13 | 14 | Sample Input: $ 15 | 16 | Sample Output: Invalid 17 | 18 | Explanation: NA 19 | */ 20 | 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | // function to print character type 26 | void getCharacterType(char ch) 27 | { 28 | if(ch >= 'A' && ch <= 'Z'){ 29 | cout << "UPPERCASE"; 30 | }else if(ch >= 'a' && ch <= 'z'){ 31 | cout << "lowercase"; 32 | }else{ 33 | cout << "Invalid"; 34 | } 35 | } 36 | 37 | int main() 38 | { 39 | char ch; 40 | cout << "Enter you character: "; 41 | cin >> ch; 42 | 43 | getCharacterType(ch); 44 | cout << endl; 45 | 46 | return 0; 47 | } 48 | 49 | /* 50 | Algo 51 | 1.Take Input of the character from the User. 52 | 2.Chech if the character is in UpperCase ( if is between A - Z). 53 | Then, print UPPERCASE 54 | 3.If the character is in LowerCase ( If character is in between a - z) . 55 | Print lowercase 56 | 4.Otherwise, Print Invalid. 57 | */ -------------------------------------------------------------------------------- /exercise_06_sorting_n_searching/05_bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic - Bubble Sort 3 | 4 | Take as input N, the size of array. Take N more inputs and store that in an array. 5 | Write a function that bubble sorts the array. Print the elements of sorted array. 6 | 7 | 1.It reads a number N. 8 | 2.Take Another N numbers as input and store them in an Array. 9 | 3.Bubble sort the array and print the Array. 10 | 11 | Constraints: N cannot be Negative. 12 | Range of Numbers can be between -1000000000 to 100000000. 13 | 14 | Sample Input: 4 15 | 2 16 | -18 17 | 45 18 | 30 19 | 20 | Sample Output: -18 21 | 2 22 | 30 23 | 45 24 | 25 | Explanation: For each test case write bubble sorting program to sort the elements of the array. 26 | */ 27 | 28 | #include 29 | #define ll long long int 30 | 31 | using namespace std; 32 | 33 | 34 | void bubble_sort(ll *arr, ll size) 35 | { 36 | // counting steps 37 | for(ll step=1; step<=size-1; step++) 38 | { 39 | // iterating unsorted array 40 | for(ll idx=0; idx<=(size-1)-step; idx++) 41 | { 42 | // pairwise swapping 43 | if(arr[idx] > arr[idx+1]){ 44 | swap(arr[idx], arr[idx+1]); 45 | } 46 | } 47 | } 48 | } 49 | 50 | // function to drive code 51 | int main() 52 | { 53 | ll size; 54 | cout << "Enter array size: "; 55 | cin >> size; 56 | 57 | ll arr[size]; 58 | cout << "Enter array elements: "; 59 | for(ll idx=0; idx<=size-1; idx++){ 60 | cin >> arr[idx] ; 61 | } 62 | 63 | // sorting array 64 | bubble_sort(arr, size); 65 | 66 | // print sorted array 67 | cout << "Sorted Array: "; 68 | for(ll idx=0; idx<=size-1; idx++){ 69 | cout << arr[idx] << " " ; 70 | } 71 | cout << endl; 72 | 73 | return 0; 74 | } 75 | 76 | 77 | /* 78 | OUTPUT: 79 | 80 | Case 1: 81 | Enter array size: 5 82 | Enter array elements: 5 1 2 3 4 83 | Sorted Array: 1 2 3 4 5 84 | 85 | Case2: 86 | Enter array size: 4 87 | Enter array elements: 2 -18 45 30 88 | Sorted Array: -18 2 30 45 89 | 90 | 91 | APPROACH: 92 | 93 | Bubble sort is comparison-based algorithm in which each pair of adjacent elements is compared 94 | and the elements are swapped if they are not in order. 95 | 96 | */ -------------------------------------------------------------------------------- /exercise_07_bitmasking/01_playing_with_bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Name - Playing With Bits 3 | 4 | Raman likes to play with bits. One day Raman decides to assign a task to his student Sanya. 5 | You have to help Sanya to complete this task. 6 | Task is as follows - Raman gives Q queries each query containing two integers a and b. 7 | Your task is to count the no of set-bits in for all numbers between a and b (both inclusive) 8 | 9 | Input Format: Read Q - No of Queries, Followed by Q lines containing 2 integers a and b. 10 | 11 | Constraints: Q,a,b are integers. 12 | 13 | Output Format: Q lines, each containing an output for your query. 14 | 15 | Sample Input: 2 16 | 1 1 17 | 10 15 18 | 19 | Sample Output: 1 20 | 17 21 | 22 | */ 23 | 24 | 25 | #include 26 | using namespace std; 27 | 28 | // function to count set bits 29 | int countBits(int n) 30 | { 31 | int count=0; 32 | while(n) 33 | { 34 | n = n & (n-1); 35 | count++; 36 | } 37 | return count; 38 | } 39 | 40 | // function to count set bits between range I to J 41 | int countSetBitIToJ(int start, int end) 42 | { 43 | int count = 0; 44 | for(int i=start; i <= end; i++) 45 | { 46 | count += countBits(i); 47 | } 48 | return count; 49 | } 50 | 51 | 52 | // function to drive code 53 | int main() 54 | { 55 | int testcase; 56 | cout << "Enter total testcases: "; 57 | cin >> testcase; 58 | 59 | while(testcase--) 60 | { 61 | int i, j; 62 | cout << "Enter Range [i & j]: "; 63 | cin >> i >> j; 64 | 65 | cout << "Total Set Bits: "; 66 | cout << countSetBitIToJ(i,j) << endl; 67 | } 68 | 69 | return 0; 70 | } 71 | 72 | /* 73 | 74 | OUTPUT: 75 | Enter total testcases: 2 76 | 77 | Enter Range [i & j]: 1 1 78 | Total Set Bits: 1 79 | 80 | Enter Range [i & j]: 10 15 81 | Total Set Bits: 17 82 | 83 | 84 | APPROACH: 85 | 86 | This is a quite simple problem to tackle. Just loop through all the numbers between a and b and 87 | calculate the no of set bits using either brian kernighan algo or the inbuilt function for 88 | counting set bits 89 | */ -------------------------------------------------------------------------------- /exercise_07_bitmasking/02_unique_number_I.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Name - Unique Number - I 3 | 4 | We are given an array containg n numbers. All the numbers are present twice except for one number 5 | which is only present once. Find the unique number without taking any extra spaces and in linear time. 6 | (Hint - Use Bitwise) 7 | 8 | Input Format: First line contains the number n. 9 | Second line contains n space separated number. 10 | 11 | Constraints: n < 10^5 12 | 13 | Output Format: Output a single line containing the unique number 14 | 15 | Sample Input: 7 16 | 1 1 2 2 3 3 4 17 | 18 | Sample Output: 4 19 | 20 | Explanation: 4 is present only once 21 | */ 22 | 23 | 24 | #include 25 | using namespace std; 26 | 27 | int main() 28 | { 29 | int total_num, num, ans=0; 30 | 31 | cout << "Enter total numbers: "; 32 | cin >> total_num; 33 | 34 | cout << "Enter numbers: "; 35 | for(int i=0; i> num; 38 | // Using bitwise XOR Operator to solve, It helped to not use any storage 39 | ans = ans^num; 40 | } 41 | 42 | cout<<"Unique No. is : "<< ans << endl; 43 | 44 | return 0; 45 | } 46 | 47 | /* 48 | 49 | OUTPUT: 50 | 51 | Enter total numbers: 7 52 | Enter numbers: 1 1 2 2 3 3 4 53 | Unique No. is : 4 54 | 55 | 56 | APPROACH: 57 | 58 | Use property of xor function to solve this problem. 59 | 60 | Concept : 61 | If we take XOR of zero and some bit, it will return that bit: a^0 = a 62 | If we take XOR of two same bits, it will return 0: a^a=0 63 | a^b^a = (a^a)^b = 0^b = b 64 | So we can XOR all bits together to find the unique number. 65 | */ -------------------------------------------------------------------------------- /exercise_07_bitmasking/06_unique_number_III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Name: Unique Numbers - III 3 | 4 | We are given an array containg n numbers. 5 | All the numbers are present thrice except for one number which is only present once. 6 | Find the unique number. Only use - bitwise operators, and no extra space. 7 | 8 | Input Format: First line contains the number n. Second line contains n space separated number. 9 | 10 | Constraints: N < 10^5 11 | 12 | Output Format: Output a single line containing the unique number 13 | 14 | Sample Input: 7 15 | 1 1 1 2 2 2 3 16 | 17 | Sample Output: 3 18 | 19 | Explanation: 3 is present only once 20 | */ 21 | 22 | 23 | #include 24 | using namespace std; 25 | 26 | int main() 27 | { 28 | int total_num, num; 29 | 30 | cout << "Enter total numbers: "; 31 | cin >> total_num; 32 | 33 | // Array of fixed size - O(1) space 34 | int bitCount[64] = {0}; // to maintain sum of bit-count at every bit position for input-numbers 35 | 36 | cout << "Enter numbers: "; 37 | for(int i=0; i> num; 40 | 41 | // update the bitCount array by extracting bits of each input number 42 | int idx = 0; 43 | while(num) 44 | { 45 | int lastBit = num&1; 46 | bitCount[idx] += lastBit; // maintaing sum of each-bit-count 47 | idx++; 48 | num = num>>1; 49 | } 50 | } 51 | 52 | /* 53 | As the numbers are repeated thrice. 54 | So, sum of bit-count will be of form 3N or 3N+1 at every bit position. 55 | Thus to find the unique number, take modulus with 3 for sum-of-bit-count at every bit position 56 | (i.e eliminating the contribution of bits which are occuring 3N times) & converting 0s and 1s 57 | into decimal number. 58 | */ 59 | int power = 1; 60 | int ans = 0; 61 | for(int idx=0; idx<64; idx++) 62 | { 63 | bitCount[idx] = bitCount[idx]%3; // reducing by a factor of 3 64 | ans += bitCount[idx]*power; 65 | power = power<<1; // power *= 2; 66 | } 67 | 68 | cout << "Unique Number: " << ans; 69 | cout << endl; 70 | 71 | return 0; 72 | } 73 | 74 | /* 75 | OUTPUT: 76 | 77 | Case 1: 78 | Enter total numbers: 7 79 | Enter numbers: 1 1 1 3 2 2 2 80 | Unique Number: 3 81 | 82 | Case 2: 83 | Enter total numbers: 7 84 | Enter numbers: 5 6 5 6 1 5 6 85 | Unique Number: 1 86 | */ -------------------------------------------------------------------------------- /exercise_08_number_theory/02_raman_and_primes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: Raman and Primes 3 | 4 | Raman is learning Sieve of Eratosthenes, He is stuck somewhere. Help him printing prime numbers. 5 | 6 | Input Format: Single line containing integral value n. 7 | 8 | Constraints: 1<=n<=500000 9 | 10 | Output Format: Integral value denoting nth prime number. 11 | 12 | Sample Input: 1 13 | 14 | Sample Output: 2 15 | 16 | */ 17 | 18 | 19 | #include 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | #define ll long long 25 | 26 | int const SIZE = 10000005; 27 | bitset p; 28 | vector primes; 29 | 30 | void sieve() 31 | { 32 | // set all bits 33 | p.set(); 34 | 35 | // 0 & 1 are not prime 36 | p[0] = p[1] = 0; 37 | 38 | 39 | for(ll i=2; i<=SIZE; i++) 40 | { 41 | if(p[i]==1) 42 | { 43 | primes.push_back(i); 44 | // lets make all the multiples of i as Not Prime 45 | for(ll j=i*i; j<=SIZE; j=j+i) 46 | { 47 | p[j] = 0; 48 | } 49 | } 50 | } 51 | } 52 | 53 | int main() 54 | { 55 | // get all prime values 56 | sieve(); 57 | 58 | int pos; 59 | cout << "Enter position: "; 60 | cin >> pos; 61 | 62 | cout << "Prime No: "; 63 | cout << primes[pos-1] << endl; 64 | 65 | return 0; 66 | } 67 | 68 | 69 | /* 70 | OUTPUT: 71 | 72 | Case 1: 73 | Enter position: 1 74 | Prime No: 2 75 | 76 | Case 2: 77 | Enter position: 9865 78 | Prime No: 103123 79 | 80 | Case 3: 81 | Enter position: 456 82 | Prime No: 3221 83 | */ -------------------------------------------------------------------------------- /exercise_10_space_time_complexity/01_exercise_time_space_complexity.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codescoop/Play-with-Data-Structures/8fedcac81ed7003132c7d5584bd2fa6fd1539979/exercise_10_space_time_complexity/01_exercise_time_space_complexity.pdf -------------------------------------------------------------------------------- /misc/array_rotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to print array elements 5 | void display(int arr[],int size) 6 | { 7 | for (int i = 0; i < size; i++) 8 | cout << arr[i] << " "; 9 | } 10 | 11 | //Function to left rotate array 12 | void leftrotate(int arr[], int size) 13 | { 14 | int i = 0; 15 | int temp = arr[i]; 16 | 17 | for (i=0; i> size; 28 | 29 | int arr[size] = {0}; 30 | cout << "Enter array values : "; 31 | for (int i = 0; i < size; i++) 32 | cin >> arr[i]; 33 | 34 | cout << "Array Elements : "; 35 | display(arr,size); 36 | 37 | cout << "\nEnter number of rotation : "; 38 | cin>>rotation; 39 | 40 | for (i=0; i 2 | using namespace std; 3 | 4 | int binary_search(int a[], int size, int key) 5 | { 6 | int low = 0; 7 | int high = size; 8 | int mid; 9 | while (low <= high) 10 | { 11 | mid = (low+high)/2; 12 | if (key == a[mid]) 13 | return mid; 14 | else if (key < a[mid]) 15 | high = mid-1; 16 | else 17 | low = mid+1; 18 | } 19 | return -1; 20 | } 21 | 22 | int main() 23 | { 24 | int size, index; 25 | cout<<"Enter the Array size : "; 26 | cin>>size; 27 | 28 | int a[size]; 29 | cout<<"Enter values for sorted array : "; 30 | for (int i = 0; i < size; i++) cin>> a[i]; 31 | 32 | cout<<"Array : "; 33 | for (int i = 0; i < size; i++) cout<>search_value; 38 | 39 | index = binary_search(a, size, search_value); 40 | if (index == -1) 41 | cout<<"Search is not in array"; 42 | else 43 | cout<<"Search value at Index : "< 2 | 3 | struct Array 4 | { 5 | int A[20]; 6 | int size; 7 | int length; 8 | }; 9 | 10 | int linear_search(struct Array arg, int value) 11 | { 12 | int index = -1; 13 | for (int i = 0 ; i < arg.length; i++) 14 | { 15 | if (arg.A[i] == value) 16 | { 17 | index = i; 18 | return index; 19 | } 20 | } 21 | return index; 22 | } 23 | 24 | // Function to display array 25 | void display(struct Array arg) 26 | { 27 | printf("Array : "); 28 | for (int i = 0; i < arg.length; i++) 29 | printf("%d ", arg.A[i]); 30 | } 31 | 32 | // Main Function 33 | int main() 34 | { 35 | int search_value, index; 36 | struct Array arr = {{5, 8, 7, 11, 18, 21, 9, 45, 38, 30}, 20, 10}; 37 | display(arr); 38 | 39 | printf("\nEnter Search value : "); 40 | scanf("%d",&search_value); //Taking input for search value 41 | 42 | index = linear_search(arr, search_value); 43 | if (index == -1) 44 | printf("Search value is not in array"); 45 | else 46 | printf("Search Value %d at index : %d",search_value,index); 47 | 48 | return 0; 49 | } 50 | 51 | /* 52 | Input: 53 | Array : 5 8 7 11 18 21 9 45 38 30 54 | Enter Search value : 18 55 | 56 | Output: 57 | Search Value 18 at index : 4 58 | */ -------------------------------------------------------------------------------- /misc/reverse_elements_of_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Array 5 | { 6 | int *A; 7 | int size; 8 | int length; 9 | }; 10 | 11 | // Function to print array elements 12 | void display(struct Array arr) 13 | { 14 | for (int i = 0; i < arr.length; i++) 15 | cout << arr.A[i] << " "; 16 | } 17 | 18 | /* Function to reverse array element using auxiliary array */ 19 | void reverse_1(struct Array *arr) 20 | { 21 | int i, j; 22 | int b[arr->length]; 23 | 24 | for (i = 0, j = arr->length - 1; j >= 0; i++, j--) 25 | b[i] = arr->A[j]; 26 | 27 | for (i = 0; i < arr->length; i++) 28 | arr->A[i] = b[i]; 29 | } 30 | 31 | /* Function to reverse array element using swap */ 32 | void reverse_2(struct Array *arr) 33 | { 34 | int i, j, temp; 35 | 36 | for (i = 0, j = arr->length - 1; i < j; i++, j--) 37 | { 38 | temp = arr->A[i]; 39 | arr->A[i] = arr->A[j]; 40 | arr->A[j] = temp; 41 | } 42 | } 43 | 44 | int main() 45 | { 46 | struct Array arr; 47 | 48 | cout << "Enter the array size : "; 49 | cin >> arr.size; 50 | arr.A = new int[arr.size]{0}; 51 | 52 | cout << "How many values do you want to enter : "; 53 | cin >> arr.length; 54 | 55 | cout << "Enter array values : "; 56 | for (int i = 0; i < arr.length; i++) 57 | cin >> arr.A[i]; 58 | 59 | cout << "Array Elements : "; 60 | display(arr); 61 | 62 | reverse_1(&arr); //Method 1: Reverse using auxiliary array 63 | cout << "\n\nMethod 1: Reverse using auxiliary array \nReversed Array Element: "; 64 | display(arr); 65 | 66 | reverse_2(&arr); //Method 2: Reverse using swaping elements 67 | cout << "\n\nMethod 2: Reverse using swaping elements \nReversed Array Element: "; 68 | display(arr); 69 | 70 | return 0; 71 | } 72 | 73 | /* 74 | Input : Enter the Array Size : 10 75 | How many values do you want to enter : 6 76 | Enter array values :10 77 | 20 78 | 30 79 | 40 80 | 50 81 | 60 82 | Array Elements : 10 20 30 40 50 60 83 | 84 | Output: Method 1: Reverse using auxiliary array 85 | Reversed Array Element: 60 50 40 30 20 10 86 | 87 | Method 2: Reverse using swaping elements 88 | Reversed Array Element: 10 20 30 40 50 60 89 | */ -------------------------------------------------------------------------------- /misc/tower_of_hanoi.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * C++ Implement of Tower of Hanoi (n-disk) puzzle. 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | //Tower of Hanoi function 9 | int TOH(int n, int a, int b, int c) 10 | { 11 | // a,b,c are names of Towers 12 | if (n==0) 13 | return 1; 14 | TOH(n-1,a,c,b); 15 | cout<<"Move disk "<>n; 26 | 27 | // 1,2,3 are name of Towers 28 | TOH(n,1,2,3); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /misc_js/approach.md: -------------------------------------------------------------------------------- 1 | ## General Approach 2 | 3 |
4 | Two Pointer's 5 | Description for 2 Pointer approach 6 |
7 | 8 |
9 | Hash Map 10 | Description for hash map approach 11 |
12 | -------------------------------------------------------------------------------- /misc_js/links.txt: -------------------------------------------------------------------------------- 1 | TUF: https://takeuforward.org/strivers-a2z-dsa-course/strivers-a2z-dsa-course-sheet-2 2 | Karan DSA: https://github.com/karandeepsingh7070/DSA-Concepts-Questions --------------------------------------------------------------------------------