Showing preview only (2,615K chars total). Download the full file or copy to clipboard to get everything.
Repository: akgmage/data-structures-and-algorithms
Branch: main
Commit: a9d5f0c556b7
Files: 894
Total size: 2.3 MB
Directory structure:
gitextract_p9w8rb_6/
├── .github/
│ └── ISSUE_TEMPLATE/
│ └── feature_request.md
├── .gitignore
├── 2D Arrays (Matrix)/
│ ├── 2D_sorted.go
│ ├── 2D_sorted_array.java
│ ├── binary_search.cpp
│ ├── count_negatives_in_sorted_matrix.cpp
│ ├── matrix_diagonal_sum.cpp
│ ├── matrix_wave_print.cpp
│ ├── rotate_matrix.cpp
│ ├── rotate_matrix.go
│ ├── rotate_matrix.java
│ ├── rotate_matrix.js
│ ├── rotate_matrix.py
│ ├── search_element.cpp
│ ├── searching_in_sorted_array.cpp
│ ├── searching_in_sorted_array.java
│ ├── searching_in_sorted_array.js
│ ├── searching_in_sorted_array.py
│ ├── set_matrix_0.cpp
│ ├── set_matrix_0.go
│ ├── set_matrix_0.java
│ ├── spiral_traverse.cpp
│ ├── spiral_traverse.go
│ ├── spiral_traverse.java
│ ├── spiral_traverse.py
│ ├── zigzag_traversal.cpp
│ ├── zigzag_traversal.go
│ ├── zigzag_traversal.java
│ ├── zigzag_traversal.js
│ └── zigzag_traversal.py
├── Arrays/
│ ├── Jobassign.cpp
│ ├── Maximum_freq.py
│ ├── Rotatedarr.cpp
│ ├── array_of_products.cpp
│ ├── array_of_products.go
│ ├── array_of_products.java
│ ├── array_of_products.js
│ ├── array_of_products.py
│ ├── ceaser_cipher.cpp
│ ├── ceaser_cipher.go
│ ├── ceaser_cipher.java
│ ├── ceaser_cipher.js
│ ├── ceaser_cipher.py
│ ├── dutch_national_flag.cpp
│ ├── dutch_national_flag.go
│ ├── dutch_national_flag.java
│ ├── dutch_national_flag.js
│ ├── dutch_national_flag.py
│ ├── find_three_largest_integers.js
│ ├── find_three_largest_number.cpp
│ ├── find_three_largest_numbers.go
│ ├── find_three_largest_numbers.java
│ ├── find_three_largest_numbers.py
│ ├── first_duplicate_value.cpp
│ ├── first_duplicate_value.go
│ ├── first_duplicate_value.java
│ ├── first_duplicate_value.js
│ ├── first_duplicate_value.py
│ ├── four_sum.py
│ ├── insert_interval.cpp
│ ├── insert_interval.go
│ ├── insert_interval.java
│ ├── insert_interval.js
│ ├── insert_interval.py
│ ├── insert_intervals.cpp
│ ├── insert_intervals.go
│ ├── is_monotonic.cpp
│ ├── is_monotonic.go
│ ├── is_monotonic.java
│ ├── is_monotonic.js
│ ├── is_monotonic.py
│ ├── longest_peak.cpp
│ ├── longest_peak.go
│ ├── longest_peak.java
│ ├── longest_peak.js
│ ├── longest_peak.py
│ ├── majority_element.go
│ ├── majority_element.java
│ ├── maximum_subarray_sum.cpp
│ ├── maximum_subarray_sum.go
│ ├── maximum_subarray_sum.py
│ ├── merge_intervals.cpp
│ ├── merge_intervals.go
│ ├── merge_intervals.java
│ ├── merge_intervals.js
│ ├── merge_intervals.py
│ ├── merge_sorted_array.cpp
│ ├── merge_sorted_array.java
│ ├── merge_sorted_arrays.py
│ ├── minimum_size_subarray_sum.java
│ ├── move_element_to_end.cpp
│ ├── move_element_to_end.go
│ ├── move_element_to_end.java
│ ├── move_element_to_end.js
│ ├── move_element_to_end.py
│ ├── non-overlapping intervals.cpp
│ ├── pallindromic_permutations.cpp
│ ├── sign_of_the_product_of_an_array.cpp
│ ├── smallest_difference.cpp
│ ├── smallest_difference.go
│ ├── smallest_difference.java
│ ├── smallest_difference.js
│ ├── smallest_difference.py
│ ├── sorted_square_array,js
│ ├── sorted_square_array.cpp
│ ├── sorted_square_array.go
│ ├── sorted_square_array.java
│ ├── sorted_square_array.py
│ ├── string_halves.cpp
│ ├── three_largest_no.py
│ ├── total_hamming_distance.cpp
│ ├── tournament_winner.go
│ ├── triplet_sum.cpp
│ ├── triplet_sum.go
│ ├── triplet_sum.java
│ ├── triplet_sum.js
│ ├── triplet_sum.py
│ └── urlify.go
├── Backtracking/
│ ├── Generate_Parentheses.py
│ ├── geenrate_parentheses.go
│ ├── n_queen.cpp
│ ├── n_queens.java
│ └── sudoko_solver.java
├── Binary Search/
│ ├── BinarySearchRecursive.java
│ ├── binary_search.cpp
│ ├── binary_search.js
│ ├── binary_search.py
│ ├── binary_search_iterative.go
│ ├── binary_search_recursive.go
│ ├── binary_serach_first_and_last_occurence.py
│ ├── first_and_last_pos.js
│ ├── first_and_last_pos_of_element.cpp
│ ├── first_and_last_position.java
│ ├── first_last_pos.java
│ ├── first_occurance.go
│ ├── first_occurence.java
│ ├── first_true.cpp
│ ├── first_true.go
│ ├── first_true.java
│ ├── first_true.js
│ ├── first_true.py
│ ├── floor_of_target.java
│ ├── index_position.java
│ ├── infinity_array.java
│ ├── last_occurance.go
│ ├── median_of_two_sorted_arrays.cpp
│ ├── median_of_two_sorted_arrays.js
│ ├── minimum_in_rotated_sorted_array.cpp
│ ├── perfect_square.java
│ ├── search_in_rotated_sorted_array.cpp
│ ├── search_in_sorted_rotated_array.cpp
│ ├── search_in_sorted_rotated_array.go
│ ├── search_in_sorted_rotated_array.java
│ ├── search_in_sorted_rotated_array.py
│ ├── search_insert_position.js
│ └── square_root.java
├── Bit Manipulation/
│ ├── bloom_filter.cpp
│ ├── bloom_filter.py
│ ├── count_bits.go
│ ├── interesting_array.java
│ ├── mod_array.java
│ ├── number_of_1_bits.java
│ ├── parity_of_a_word.go
│ ├── power_of_2.cpp
│ ├── reduce_to_zero.cpp
│ ├── setbits.cpp
│ ├── single_number.java
│ └── subarrays_with_bitwise_OR_1.java
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dynamic Programming/
│ ├── best_time_to_buy_and_sell_stock.cpp
│ ├── best_time_to_buy_and_sell_stock.go
│ ├── best_time_to_buy_and_sell_stock.java
│ ├── best_time_to_buy_and_sell_stock.js
│ ├── best_time_to_buy_and_sell_stock.py
│ ├── climb_stairs.cpp
│ ├── climb_stairs.go
│ ├── climb_stairs.java
│ ├── climb_stairs.js
│ ├── climb_stairs.py
│ ├── coin_change.cpp
│ ├── coin_change.go
│ ├── coin_change.java
│ ├── coin_change.js
│ ├── coin_change.py
│ ├── dice_throws.go
│ ├── disk_stacking.go
│ ├── disk_stacking.py
│ ├── distance_of_nearest_0.cpp
│ ├── distance_of_nearest_0.py
│ ├── distane_of_nearest_0.go
│ ├── distane_of_nearest_0.java
│ ├── distane_of_nearest_0.js
│ ├── edit_distance_dp.cpp
│ ├── edit_distance_dp.go
│ ├── edit_distance_dp.java
│ ├── edit_distance_dp.js
│ ├── edit_distance_dp.py
│ ├── edit_distance_memoized.cpp
│ ├── edit_distance_recursive.cpp
│ ├── house_robber.cpp
│ ├── juice_bottling.cpp
│ ├── juice_bottling.go
│ ├── juice_bottling.java
│ ├── juice_bottling.js
│ ├── juice_bottling.py
│ ├── knapsack.cpp
│ ├── knapsack.go
│ ├── knapsack.java
│ ├── knapsack.js
│ ├── knapsack.py
│ ├── knight_probability_chessboard.cpp
│ ├── knight_probability_chessboard.go
│ ├── knight_probability_chessboard.java
│ ├── knight_probability_chessboard.js
│ ├── knight_probability_chessboard.py
│ ├── kth_closest_point_to origin.java
│ ├── largest_rectangle.java
│ ├── largest_rectangle.js
│ ├── largest_rectangle.py
│ ├── longest_common_subsequence_dp.cpp
│ ├── longest_common_subsequence_memoization.cpp
│ ├── longest_common_subsequence_recursive.cpp
│ ├── longest_increasing_subsequence.cpp
│ ├── longest_pallindromic_substring.cpp
│ ├── longest_pallindromic_substring.go
│ ├── longest_pallindromic_substring.java
│ ├── longest_pallindromic_substring.js
│ ├── longest_pallindromic_substring.py
│ ├── max_path_sum.go
│ ├── max_sum_increasing_subsequence.cpp
│ ├── max_sum_increasing_subsequence.go
│ ├── max_sum_increasing_subsequence.java
│ ├── max_sum_increasing_subsequence.js
│ ├── max_sum_increasing_subsequence.py
│ ├── maximal_sqaure.cpp
│ ├── maximal_sqaure.go
│ ├── maximal_sqaure.js
│ ├── maximal_sqaure.py
│ ├── maximal_square.java
│ ├── min_cost_travel_in_a_grid.cpp
│ ├── min_insertion_steps_for_string_palindrome.java
│ ├── min_number_of_jumps.cpp
│ ├── min_number_of_jumps.go
│ ├── min_number_of_jumps.java
│ ├── min_number_of_jumps.js
│ ├── min_number_of_jumps.py
│ ├── min_steps_to_make_string_palindrome.go
│ ├── min_steps_to_make_string_palindrome.java
│ ├── min_steps_to_make_string_palindrome.py
│ ├── min_steps_to_make_string_pallindrome.cpp
│ ├── min_steps_to_make_string_pallindrome.js
│ ├── min_steps_to_reduce_a_number_to_one.cpp
│ ├── num_ways_to_make_change.cpp
│ ├── num_ways_to_make_change.go
│ ├── num_ways_to_make_change.java
│ ├── num_ways_to_make_change.js
│ ├── num_ways_to_make_change.py
│ ├── num_ways_to_traverse_graph.cpp
│ ├── num_ways_to_traverse_graph.go
│ ├── num_ways_to_traverse_graph.js
│ ├── num_ways_to_traverse_graph.py
│ ├── numbers_in_pi.go
│ ├── reconstruct_bst_in_python.py
│ ├── rod_cutting_problem_dp.cpp
│ ├── rod_cutting_problem_memoized.cpp
│ ├── rod_cutting_problem_recursive.cpp
│ ├── trapping_rain_water.cpp
│ ├── unique_paths_with_obstacles.cpp
│ ├── wine_selling_problem_dp.cpp
│ ├── wine_selling_problem_memoized.cpp
│ └── wine_selling_problem_recursive.cpp
├── Famous Algorithms/
│ ├── N_queen.js
│ ├── euclidean_algorithm.java
│ ├── euclidean_algorithm.js
│ ├── euclidean_algorithm.py
│ ├── kadanes_algorithm.c++
│ ├── kadanes_algorithm.go
│ ├── kadanes_algorithm.java
│ ├── kadanes_algorithm.py
│ ├── kadenes_algorithm.js
│ ├── kmp.java
│ ├── kmp.js
│ └── kmp.py
├── Fast and Slow Pointers/
│ ├── happy_number.go
│ ├── linked_list_compute_midpoint.cpp
│ ├── linked_list_compute_midpoint.java
│ ├── linked_list_find_middle.py
│ ├── linked_list_floyds_cycle_detection.cpp
│ └── linked_list_floyds_cycle_detection.py
├── Graphs/
│ ├── Diljstra.go
│ ├── GraphBFS.java
│ ├── Graph_Dijstra.java
│ ├── Graphs_Dijkstras.py
│ ├── Graphs_Ford_Fulkerson.cpp
│ ├── Graphs_bfs.cpp
│ ├── Graphs_bfs.js
│ ├── Graphs_bfs.py
│ ├── Graphs_bfs_sssp.cpp
│ ├── Graphs_cycle_detection_bfs.cpp
│ ├── Graphs_cycle_detection_dfs.cpp
│ ├── Graphs_dfs.cpp
│ ├── Graphs_dfs.java
│ ├── Graphs_dfs.js
│ ├── Graphs_dfs.py
│ ├── Graphs_dfs_connected_components.cpp
│ ├── Graphs_dijkstras.js
│ ├── Graphs_flood_fill.cpp
│ ├── Graphs_kill_process.cpp
│ ├── Graphs_kruskals_algo.cpp
│ ├── Graphs_kruskals_algorithm.js
│ ├── Graphs_topological_sort_bfs.cpp
│ ├── Graphs_topological_sort_dfs.cpp
│ ├── a_star_algorithm.py
│ ├── adjacency_list.java
│ ├── adjacency_matrix.go
│ ├── adjacency_matrix.java
│ ├── dijkstras.cpp
│ ├── dijkstras.go
│ ├── dijkstras.java
│ ├── dijkstras.py
│ ├── dijkstras_heap_based.go
│ ├── ford_fulkerson.cpp
│ ├── graphs_adjacency_list.cpp
│ ├── graphs_adjacency_list_generic.cpp
│ ├── graphs_bfs.go
│ ├── graphs_dfs.go
│ ├── kruskals_algorithm.java
│ ├── kruskals_algorithm.py
│ ├── remove_island.go
│ ├── river_sizes.cpp
│ ├── river_sizes.go
│ ├── river_sizes.java
│ ├── river_sizes.js
│ ├── river_sizes.py
│ ├── single_cycle_check.cpp
│ ├── single_cycle_check.go
│ ├── single_cycle_check.java
│ ├── single_cycle_check.js
│ ├── single_cycle_check.py
│ ├── snack_ladders.cpp
│ ├── snack_ladders.js
│ ├── snack_ladders.py
│ ├── snakes_ladders.java
│ ├── topological_sort.cpp
│ ├── topological_sort.go
│ ├── topological_sort.java
│ ├── topological_sort.js
│ ├── topological_sort.py
│ ├── two_colorable.cpp
│ ├── two_colorable.go
│ ├── two_colorable.java
│ ├── two_colorable.js
│ ├── two_colorable.py
│ ├── union_find.cpp
│ ├── union_find.go
│ ├── union_find.java
│ ├── union_find.js
│ ├── union_find.py
│ ├── validate_bst.cpp
│ ├── validate_bst.go
│ ├── validate_bst.java
│ ├── validate_bst.js
│ ├── validate_bst.py
│ ├── youngest_common_ancestor.cpp
│ ├── youngest_common_ancestor.go
│ ├── youngest_common_ancestor.java
│ ├── youngest_common_ancestor.js
│ └── youngest_common_ancestor.py
├── Greedy/
│ ├── coin_change.go
│ ├── coin_change.java
│ ├── coin_change.js
│ ├── coin_change.py
│ ├── task_assignment.cpp
│ ├── task_assignment.go
│ ├── task_assignment.java
│ ├── task_assignment.js
│ └── task_assignment.py
├── Hash Table/
│ ├── Bloomfilter.cpp
│ ├── Convert an array to reduced form using hashing.cpp
│ ├── Count_Pairs_of_Points_With_Distance_k.py
│ ├── HashTable.java
│ ├── Longest_substring_without_repeating_characters.py
│ ├── Partition.java
│ ├── Partition_string.py
│ ├── add_first_missing_positive.cpp
│ ├── add_first_missing_positive.java
│ ├── find_optimal_partition_of_string.cpp
│ ├── find_optimal_partition_of_string.go
│ ├── first_duplicate_value.go
│ ├── first_missing_positve.go
│ ├── first_missing_positve.js
│ ├── first_missing_positve.py
│ ├── first_non_repeated_character.go
│ ├── first_repeated_character.go
│ ├── four_number_sum.java
│ ├── frequency_of_elements.java
│ ├── group_anagrams.cpp
│ ├── group_anagrams.go
│ ├── group_anagrams.java
│ ├── group_anagrams.js
│ ├── group_anagrams.py
│ ├── integer_to_roman.cpp
│ ├── integer_to_roman.go
│ ├── integer_to_roman.java
│ ├── integer_to_roman.js
│ ├── integer_to_roman.py
│ ├── remove_duplicates.go
│ ├── roman_to_integer.cpp
│ ├── roman_to_integer.go
│ ├── roman_to_integer.java
│ ├── roman_to_integer.js
│ ├── roman_to_integer.py
│ ├── sum_of_unique_elements.java
│ ├── three_number_sum.java
│ ├── two_sum.cpp
│ ├── two_sum.go
│ ├── two_sum.java
│ ├── two_sum.js
│ ├── two_sum.py
│ ├── zero_sum_subarray.cpp
│ ├── zero_sum_subarray.go
│ ├── zero_sum_subarray.java
│ ├── zero_sum_subarray.js
│ └── zero_sum_subarray.py
├── Heaps/
│ ├── heap.cpp
│ ├── heap.go
│ ├── heap.java
│ ├── heap.js
│ ├── heap.py
│ └── k_closest.py
├── LICENSE
├── Linked List/
│ ├── Add_two_numbers.py
│ ├── Intersection_LL.cpp
│ ├── LFU_Cache.cpp
│ ├── Linked_List_Component.java
│ ├── MiddleOfLinkedList.java
│ ├── MiddleofLL.py
│ ├── RemoveKthNodeFromEnd.java
│ ├── Remove_nth_node_from_end.java
│ ├── add_two_numbers.cpp
│ ├── add_two_numbers.js
│ ├── delete_kth_node.js
│ ├── double_linked_list.go
│ ├── doubly_linked_list.cpp
│ ├── doubly_linked_list.java
│ ├── doubly_linked_list.js
│ ├── floyds_cycle_detection.cpp
│ ├── floyds_cycle_detection.go
│ ├── floyds_cycle_detection.java
│ ├── intersection_of_two_linked_lists.cpp
│ ├── liniked_list_sort_list.cpp
│ ├── linked_list.go
│ ├── linked_list.js
│ ├── linked_list.py
│ ├── linked_list_add_two_numbers.py
│ ├── linked_list_compute_middle.cpp
│ ├── linked_list_compute_middle.java
│ ├── linked_list_delete_at_any_pos.cpp
│ ├── linked_list_delete_at_head.cpp
│ ├── linked_list_delete_at_tail.cpp
│ ├── linked_list_delete_node.go
│ ├── linked_list_even_or_odd.go
│ ├── linked_list_find_length.cpp
│ ├── linked_list_insert_at_any_pos.cpp
│ ├── linked_list_insert_at_head.cpp
│ ├── linked_list_insert_at_tail.cpp
│ ├── linked_list_kth_from_end.go
│ ├── linked_list_kth_node_from_end.cpp
│ ├── linked_list_linear_search.cpp
│ ├── linked_list_merge_k_sorted_lists.cpp
│ ├── linked_list_merge_two_sorted_linked_list.cpp
│ ├── linked_list_mergesort_an_unsorted_list.cpp
│ ├── linked_list_middle.go
│ ├── linked_list_middle.js
│ ├── linked_list_odd_even.cpp
│ ├── linked_list_pallindrome.cpp
│ ├── linked_list_recursive_search.cpp
│ ├── linked_list_remove_dups.cpp
│ ├── linked_list_remove_kth_node_from_end.py
│ ├── linked_list_remove_nth_node_from_end.cpp
│ ├── linked_list_remove_nth_node_from_end.py
│ ├── linked_list_reverse.cpp
│ ├── linked_list_reverse.js
│ ├── linked_list_reverse_recursive.cpp
│ ├── linked_list_sum_lists.cpp
│ ├── linked_list_swap_nodes_in_pair.cpp
│ ├── linked_list_swap_nodes_in_pair_iterative.cpp
│ ├── linked_list_take_input.cpp
│ ├── linked_list_take_input_as_array_operator_overloading.cpp
│ ├── linked_list_take_input_operator_overloading.cpp
│ ├── recursive and iterative in singly linkedlist.py
│ ├── reverse_linked_list.go
│ ├── reverse_linked_list.java
│ ├── singly_linked_list.cpp
│ ├── singly_linked_list.go
│ ├── singly_linked_list.java
│ ├── singly_linked_list.py
│ ├── sll.go
│ └── sort_linked_list.cpp
├── Math/
│ ├── Basic_operations.py
│ ├── Count.go
│ ├── Factorial.cpp
│ ├── Factorial.go
│ ├── Factorial.java
│ ├── Factorial.py
│ ├── Hamming_distance.py
│ ├── Hammingdistance.cpp
│ ├── K_closest.cpp
│ ├── K_closest_points_to_origin.java
│ ├── K_closest_points_to_origin.py
│ ├── Number_of_Substrings_With_Only_1s.cpp
│ ├── PowXn.go
│ ├── PowXn.java
│ ├── PowXn.py
│ ├── Reverse_Integer.cpp
│ ├── Sum_four.cpp
│ ├── circle.cpp
│ ├── count_numbers_with_unique_digits.java
│ ├── count_primes.cpp
│ ├── count_primes.java
│ ├── count_unique_digits.cpp
│ ├── count_unique_digits.go
│ ├── factorial.py
│ ├── factorial_iterative.js
│ ├── find_longest_increasing_subsequence.cpp
│ ├── hamming_distance.cpp
│ ├── is_power_of_two.js
│ ├── is_prime.js
│ ├── k_closest_points_to_origin.cpp
│ ├── missing_number.py
│ ├── modular_expo_itera.cpp
│ ├── modular_expo_recursive.cpp
│ ├── num_points_inside_a_circle.cpp
│ ├── num_points_inside_a_circle.js
│ ├── num_points_inside_a_circle.py
│ ├── num_steps_reduce_to_zero.Go
│ ├── num_steps_reduce_to_zero.cpp
│ ├── num_steps_reduce_to_zero.java
│ ├── num_steps_reduce_to_zero.js
│ ├── num_steps_reduce_to_zero.py
│ ├── number_of_substrings_with_only_1s.js
│ ├── op.js
│ ├── palindrome_number.java
│ ├── pallindrome_number.cpp
│ ├── pallindrome_number.py
│ ├── powXn.cpp
│ ├── powXn.js
│ ├── prime_factorization.cpp
│ ├── shuffle_an_array.cpp
│ ├── shuffle_an_array.py
│ ├── sieve_of_eratosthenes.cpp
│ ├── substrings_with_1s.py
│ ├── unique_digits.cpp
│ ├── unique_digits.java
│ ├── unique_digits.py
│ └── unique_integers_that_sum_up_to_0.cpp
├── Misc/
│ └── tictactoe.java
├── Patterns/
│ ├── CompleteSquare.java
│ ├── HollowPattern.cpp
│ ├── HollowPattern.go
│ ├── HollowPattern.java
│ ├── HollowPattern.py
│ ├── Ladder_Pattern.java
│ ├── ReverseRightTrianglePattern.java
│ ├── RightPascalTriangle.java
│ ├── StarDiamond.java
│ ├── diamond_pattern.cpp
│ ├── diamond_pattern.go
│ ├── diamond_pattern.java
│ ├── diamond_pattern.py
│ ├── numerical_pattern.java
│ ├── triangular_pattern.java
│ └── triangular_pattern.py
├── Priority Queues/
│ ├── In_Place_HeapSort.cpp
│ ├── buy_the_ticket.cpp
│ ├── check_max_heap.cpp
│ ├── kth_largest_element.cpp
│ ├── kth_smallest_element.cpp
│ ├── merge_k_sorted_arrays.cpp
│ └── running_median.cpp
├── Queue/
│ ├── queue.cpp
│ ├── queue.go
│ ├── queue.java
│ ├── queue.js
│ ├── queue.py
│ ├── queue_using_stack.js
│ ├── queue_using_stacks.go
│ ├── queues_using_stacks.py
│ └── stack_using_queue.cpp
├── README.md
├── Recursion/
│ ├── calculatextopowern.cpp
│ ├── count_digits.cpp
│ ├── count_digits.go
│ ├── count_zeros.cpp
│ ├── count_zeros.go
│ ├── factorial.cpp
│ ├── factorial.go
│ ├── factorial.js
│ ├── fibonacci.cpp
│ ├── fibonacci.go
│ ├── fibonacci_memoization.cpp
│ ├── fibonacci_memoization.go
│ ├── geometric_sum.cpp
│ ├── is_array_sorted.cpp
│ ├── is_array_sorted.go
│ ├── is_element_present.cpp
│ ├── modular_exponentiation.cpp
│ ├── multiplication.cpp
│ ├── powerset.cpp
│ ├── powerset.go
│ ├── powerset.java
│ ├── powerset.js
│ ├── powerset.py
│ ├── print_numbers.cpp
│ ├── recursive_bubble_sort.cpp
│ ├── reverse_print.go
│ ├── tower_of_hannoi.cpp
│ ├── tower_of_hannoi.java
│ ├── tower_of_hannoi.js
│ ├── tower_of_hannoi.py
│ ├── tower_of_hanoi.go
│ └── valid_palindrome_2.py
├── SECURITY.md
├── Scheduling/
│ ├── fcfs.c
│ ├── sjf.c
│ └── srtf.c
├── Scheduling Algortihms/
│ ├── fcfs.c
│ ├── sjf.c
│ └── srtf.c
├── Searching/
│ ├── first_duplicate_value.js
│ ├── linear_search_string.cpp
│ ├── semordnilap.go
│ ├── separate_0s_and_1s.go
│ └── separate_even_odd.go
├── Sliding Window/
│ ├── find_max.go
│ ├── fruits_into_basket.cpp
│ ├── fruits_into_basket.go
│ ├── fruits_into_basket.java
│ ├── fruits_into_basket.js
│ ├── fruits_into_basket.py
│ ├── longest_repeated_character_replacement.cpp
│ ├── longest_repeated_character_replacement.go
│ ├── longest_repeated_character_replacement.java
│ ├── longest_repeated_character_replacement.js
│ ├── longest_repeated_character_replacement.py
│ ├── longest_substring_with_k_distinct_chars.go
│ ├── longest_substring_with_k_distinct_chars.java
│ ├── longest_substring_with_k_distinct_chars.js
│ ├── longest_substring_with_k_distinct_chars.py
│ ├── longest_substring_without_repeating_characters.go
│ ├── max_eraser_value.go
│ ├── max_eraser_value.java
│ ├── sliding_window_max.java
│ ├── sliding_window_max.js
│ ├── sliding_window_max.py
│ ├── subaray_sum_equals_k.cpp
│ ├── subaray_sum_equals_k.go
│ ├── subaray_sum_equals_k.java
│ ├── subaray_sum_equals_k.js
│ ├── subaray_sum_equals_k.py
│ ├── subarray_product_less_than_k,js
│ ├── subarray_product_less_than_k.cpp
│ ├── subarray_product_less_than_k.go
│ ├── subarray_product_less_than_k.java
│ └── subarray_product_less_than_k.py
├── Stacks/
│ ├── Stack_with_max_API.cpp
│ ├── Stacks_using_queues.py
│ ├── balanced_parenthesis.go
│ ├── is_palindrome.go
│ ├── next_greater_element.c++
│ ├── next_greater_element.go
│ ├── next_greater_element.java
│ ├── next_greater_element.js
│ ├── next_greater_element.py
│ ├── queue using stack.go
│ ├── queue using stack.java
│ ├── queue using stack.js
│ ├── queue using stack.py
│ ├── queue_using_stacks.cpp
│ ├── reverse_polish_notation.cpp
│ ├── stack.cpp
│ ├── stack.go
│ ├── stack.java
│ ├── stack.js
│ ├── stack.py
│ ├── stack_array_based.go
│ ├── stack_dynamic_array.go
│ ├── stack_linked_list.go
│ ├── stack_using_queue.cpp
│ ├── stack_using_queue.go
│ ├── stack_using_queue.java
│ ├── stack_using_queue.js
│ ├── stack_using_queue.py
│ ├── stacks_API.cpp
│ ├── stacks_using_queues.java
│ ├── stacks_with_queues.cpp
│ ├── stacks_with_queues.py
│ └── valid_parentheses.cpp
├── Strings/
│ ├── Dp_plaindrome.py
│ ├── KMP.go
│ ├── Longest_palindromic_substring.py
│ ├── MaxConcatenatedstr.java
│ ├── Min_palindrome.js
│ ├── Valid_palindrome.py
│ ├── case_specific_sorting_of_strings.cpp
│ ├── check panagram.java
│ ├── check_anagrams.java
│ ├── check_palindrome.cpp
│ ├── check_permutations.cpp
│ ├── count_occurances.java
│ ├── group_anagrams.cpp
│ ├── group_anagrams.go
│ ├── group_anagrams.java
│ ├── group_anagrams.js
│ ├── group_anagrams.py
│ ├── is_pallindrome.cpp
│ ├── is_pallindrome.go
│ ├── is_pallindrome.java
│ ├── is_pallindrome.js
│ ├── is_pallindrome.py
│ ├── is_unique.cpp
│ ├── is_unique.go
│ ├── is_unique.java
│ ├── is_unique.js
│ ├── is_unique.py
│ ├── length_of_longest_substring.java
│ ├── longest palindromic substring.java
│ ├── longest_common_prefix.cpp
│ ├── longest_string.cpp
│ ├── one_edit.cpp
│ ├── one_edit.go
│ ├── one_edit.java
│ ├── one_edit.js
│ ├── one_edit.py
│ ├── plaindrome_str.cpp
│ ├── reverse_string.go
│ ├── reverse_words_in_a_string.cpp
│ ├── reverse_words_in_a_string.go
│ ├── reverse_words_in_a_string.js
│ ├── reverse_words_in_string.java
│ ├── valid_palindrome.js
│ ├── valid_pallindrome2.cpp
│ ├── valid_pallindrome2.go
│ ├── valid_pallindrome2.java
│ ├── valid_pallindrome2.js
│ ├── valid_pallindrome2.py
│ ├── well_formed_parentheses.cpp
│ ├── well_formed_parentheses.java
│ └── zigzag_conversion.cpp
├── Trees/
│ ├── AVL/
│ │ └── avl.go
│ ├── Binary Search Trees/
│ │ ├── Kth_Largest_Value_In_BST.py
│ │ ├── Kth_largest_BST.cpp
│ │ ├── Kth_largest_BST.java
│ │ ├── Kth_largest_BST.js
│ │ ├── Validate_BST.cpp
│ │ ├── Validate_BST.java
│ │ ├── Validate_BST.js
│ │ ├── Validate_BST.py
│ │ ├── bst.go
│ │ ├── find_closest_value.cpp
│ │ ├── find_closest_value.go
│ │ ├── find_closest_value.js
│ │ ├── find_closest_value.py
│ │ ├── insert_into_bst.cpp
│ │ ├── kth_largest.go
│ │ ├── min_height_BST.cpp
│ │ ├── min_height_BST.go
│ │ ├── min_height_BST.java
│ │ ├── min_height_BST.js
│ │ ├── min_height_BST.py
│ │ ├── reconstruct_bst.cpp
│ │ ├── reconstruct_bst.go
│ │ ├── reconstruct_bst.java
│ │ ├── reconstruct_bst.js
│ │ ├── reconstruct_bst.py
│ │ ├── search.cpp
│ │ └── validate_bst.go
│ ├── Binary Trees/
│ │ ├── Trie.js
│ │ ├── bfs.cpp
│ │ ├── bfs.go
│ │ ├── binary_tree.go
│ │ ├── branch_sum.go
│ │ ├── build_tree_preorder.cpp
│ │ ├── calculate_size.go
│ │ ├── count_nodes.cpp
│ │ ├── delete.go
│ │ ├── dfs.cpp
│ │ ├── dfs.go
│ │ ├── dfs.java
│ │ ├── dfs.js
│ │ ├── dfs.py
│ │ ├── diameter.cpp
│ │ ├── diameter.go
│ │ ├── diameter.java
│ │ ├── diameter.js
│ │ ├── diameter.py
│ │ ├── find_branch_sum.go
│ │ ├── find_max.go
│ │ ├── height.cpp
│ │ ├── height.go
│ │ ├── height_balanced_binary_tree.cpp
│ │ ├── height_balanced_binary_tree.go
│ │ ├── height_balanced_binary_tree.java
│ │ ├── height_balanced_binary_tree.js
│ │ ├── height_balanced_binary_tree.py
│ │ ├── inorder_traversal.cpp
│ │ ├── inorder_traversal.go
│ │ ├── inorder_traversal.java
│ │ ├── inorder_traversal.js
│ │ ├── inorder_traversal.py
│ │ ├── invert.cpp
│ │ ├── invert.go
│ │ ├── invert.java
│ │ ├── invert.js
│ │ ├── invert.py
│ │ ├── is_symmetric.cpp
│ │ ├── is_symmetric.go
│ │ ├── is_symmetric.java
│ │ ├── is_symmetric.js
│ │ ├── is_symmetric.py
│ │ ├── level_by_level.cpp
│ │ ├── level_order_traversal.cpp
│ │ ├── level_order_traversal.go
│ │ ├── node_depth.go
│ │ ├── postorder_traversal.cpp
│ │ ├── preorder_traversal.cpp
│ │ ├── remove_leaf_nodes.go
│ │ ├── search_an_element.go
│ │ └── sum_of_all_nodes.cpp
│ ├── Implement_Trie.cpp
│ ├── Implement_Trie.py
│ ├── MaxpathBinaryTree.cpp
│ ├── tree.go
│ ├── trie.cpp
│ ├── trie.go
│ └── trie.java
├── Tries/
│ ├── pattern_matching.cpp
│ ├── search_in_tries.cpp
│ └── trie_node_class.cpp
└── sorting/
├── Cyclic_Sort.java
├── bubble_sort.cpp
├── bubble_sort.go
├── bubble_sort.java
├── bubble_sort.js
├── bubble_sort.py
├── bucket-sort.js
├── bucket_sort.cpp
├── bucket_sort.go
├── bucket_sort.java
├── bucket_sort.js
├── count_sort.cpp
├── count_sort.java
├── count_sort.js
├── count_sort.py
├── dnf.cpp
├── dnf.go
├── dnf.java
├── dnf.js
├── dnf.py
├── heap_sort.cpp
├── heap_sort.java
├── heap_sort.js
├── heap_sort.py
├── insertion_sort.cpp
├── insertion_sort.go
├── insertion_sort.java
├── insertion_sort.js
├── insertion_sort.py
├── merge_sort.cpp
├── merge_sort.go
├── merge_sort.java
├── merge_sort.js
├── merge_sort.py
├── quick_sort.cpp
├── quick_sort.go
├── quick_sort.java
├── quick_sort.js
├── quick_sort.py
├── radix_sort.cpp
├── radix_sort.go
├── radix_sort.java
├── radix_sort.js
├── radix_sort.py
├── selection_sort.cpp
├── selection_sort.go
├── selection_sort.java
├── selection_sort.js
├── selection_sort.py
├── tim_sort.cpp
├── tim_sort.go
├── tim_sort.java
├── tim_sort.py
└── wave_sort.cpp
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .gitignore
================================================
.vscode
.idea
*.exe
================================================
FILE: 2D Arrays (Matrix)/2D_sorted.go
================================================
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 || len(matrix[0]) == 0 {
return false
}
rows, cols := len(matrix), len(matrix[0])
left, right := 0, rows*cols-1
for left <= right {
mid := left + (right-left)/2
// Convert the 1D index back to 2D coordinates
row, col := mid/cols, mid%cols
midValue := matrix[row][col]
if midValue == target {
return true
} else if midValue < target {
left = mid + 1
} else {
right = mid - 1
}
}
return false
}
================================================
FILE: 2D Arrays (Matrix)/2D_sorted_array.java
================================================
/*
The algorithm starts by initializing two pointers, left and right, which represent the start and end indices of the search range. The range spans from the first element (matrix[0][0]) to the last element (matrix[m - 1][n - 1]) in the matrix, where m is the number of rows and n is the number of columns.
The function then enters a while loop that continues as long as left is less than or equal to right. In each iteration, it calculates the middle index mid using the formula mid = left + (right - left) / 2. This ensures that mid is always rounded down to the lower integer if the range is odd.
The middle index mid is then mapped to its corresponding row and column indices in the matrix using the formulas row = mid / n and col = mid % n.
The number num at the middle position (matrix[row][col]) is retrieved and compared with the target. If num is equal to the target, the function returns true as the target is found in the matrix. If num is less than the target, the left pointer is updated to mid + 1 to search in the upper half of the range. If num is greater than the target, the right pointer is updated to mid - 1 to search in the lower half of the range.
If the while loop terminates without finding the target, the function returns false.
The algorithm achieves a time complexity of O(log(m * n)), where m is the number of rows and n is the number of columns in the matrix, as it uses binary search to efficiently search within the given range.
*/
#include <vector>
class Solution {
public:
/**
* Searches for a target integer in a matrix with specific properties.
*
* @param matrix The input matrix.
* @param target The target integer to search for.
* @return True if the target is found in the matrix, false otherwise.
*/
bool searchMatrix(std::vector<std::vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
int left = 0; // Start index of the search range
int right = m * n - 1; // End index of the search range
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate middle index
int row = mid / n; // Calculate row index
int col = mid % n; // Calculate column index
int num = matrix[row][col]; // Get the number at the middle position
if (num == target) {
return true; // Target found in the matrix
} else if (num < target) {
left = mid + 1; // Search in the upper half of the range
} else {
right = mid - 1; // Search in the lower half of the range
}
}
return false; // Target not found in the matrix
}
};
================================================
FILE: 2D Arrays (Matrix)/binary_search.cpp
================================================
/*
You are given an m x n integer matrix matrix with the following two properties:
Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
*/
class Solution {
bool costumBinarySearch(const vector<vector<int>>& matrix, int target, int low, int high){
int size = matrix[0].size();
while(high - low > 1){
int mid = (high + low) / 2;
if(matrix[mid / size][mid % size] < target) {
low = mid + 1;
} else {
high = mid;
}
}
if(matrix[low / size][low % size] == target || matrix[high / size][high % size] == target){
return true;
}
return false;
}
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
return costumBinarySearch(matrix, target, 0, matrix.size() * matrix[0].size() - 1);
}
};
================================================
FILE: 2D Arrays (Matrix)/count_negatives_in_sorted_matrix.cpp
================================================
/*
Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.
Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.
Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
Follow up: Could you find an O(n + m) solution?
*/
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int len = grid.size(), m = grid[0].size();
int ans = 0;
int j = 0, i = len - 1;
while(j < m && i >= 0){
if(grid[i][j] < 0){
ans += (m - j);
i--;
}
else{
j++;
}
}
return ans;
}
};
================================================
FILE: 2D Arrays (Matrix)/matrix_diagonal_sum.cpp
================================================
/*
Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
*/
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int len = mat.size(), sum = 0;
for(int i = 0; i < len; i++){
sum += mat[i][i] + mat[i][len - 1 - i];
}
// if length is odd then subtract mid element, because its added twice
if(len & 1){
sum -= mat[len / 2][len / 2];
}
return sum;
}
};
================================================
FILE: 2D Arrays (Matrix)/matrix_wave_print.cpp
================================================
// Prints a matrix in wave form
#include<bits/stdc++.h>
using namespace std;
void wave_print(int Mat[][10], int R, int C){
for(int j = 0; j < C; j++){
if(j & 1){
for(int i = R - 1; i >= 0; i--){
cout << Mat[i][j] << " ";
}
}
else{
for(int i = 0; i < R; i++){
cout << Mat[i][j] << " ";
}
}
}
}
int main(){
int Mat[10][10], R, C;
cin >> R >> C;
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
cin >> Mat[i][j];
}
}
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
cout << Mat[i][j] << " ";
}
cout << endl;
}
wave_print(Mat, R, C);
}
================================================
FILE: 2D Arrays (Matrix)/rotate_matrix.cpp
================================================
// Rotate clockwise and anti-clockwise
/*
This implementation first defines two functions, rotateClockwise and rotateCounterclockwise,
to rotate the image by 90 degrees clockwise and counterclockwise, respectively.
Each function takes a 2D vector image as input and modifies it in place.
The printImage function is used to print the image for demonstration purposes.
Finally, the main function initializes an example image, prints it, rotates
it by 90 degrees clockwise, prints it again, rotates it by 90 degrees counterclockwise,
and prints it one last time to verify that the rotations worked as expected.
*/
#include <iostream>
#include <vector>
using namespace std;
// Function to rotate the image by 90 degrees clockwise
void rotateClockwise(vector<vector<int>>& image) {
int n = image.size();
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = image[i][j];
image[i][j] = image[n - j - 1][i];
image[n - j - 1][i] = image[n - i - 1][n - j - 1];
image[n - i - 1][n - j - 1] = image[j][n - i - 1];
image[j][n - i - 1] = temp;
}
}
}
// Function to rotate the image by 90 degrees counterclockwise
void rotateCounterclockwise(vector<vector<int>>& image) {
int n = image.size();
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = image[i][j];
image[i][j] = image[j][n - i - 1];
image[j][n - i - 1] = image[n - i - 1][n - j - 1];
image[n - i - 1][n - j - 1] = image[n - j - 1][i];
image[n - j - 1][i] = temp;
}
}
}
// Function to print the image
void printImage(vector<vector<int>>& image) {
for (auto row : image) {
for (auto pixel : row) {
cout << pixel << " ";
}
cout << endl;
}
}
// Driver code
int main() {
vector<vector<int>> image = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
cout << "Original Image:" << endl;
printImage(image);
rotateClockwise(image);
cout << "Image rotated by 90 degrees clockwise:" << endl;
printImage(image);
rotateCounterclockwise(image);
cout << "Image rotated by 90 degrees counterclockwise:" << endl;
printImage(image);
return 0;
}
================================================
FILE: 2D Arrays (Matrix)/rotate_matrix.go
================================================
// Rotate clockwise and anti-clockwise
/*
The rotateClockwise function takes an image array as input and returns the image rotated by 90 degrees clockwise.
It creates a new rotated array with the same dimensions as the original image, and then iterates over
each element of the image, assigning it to a new position in the rotated array.
The rotateCounterClockwise function works similarly, but it rotates the image counterclockwise instead.
The n-j-1 and n-i-1 indices are used to swap the rows and columns, respectively.
In the main function, we create an example image, and then call the rotateClockwise and
rotateCounterClockwise functions to rotate the image by 90 degrees in each direction.
Finally, we print the rotated images.
*/
package main
import "fmt"
func rotateClockwise(image [][]int) [][]int {
n := len(image)
rotated := make([][]int, n)
for i := 0; i < n; i++ {
rotated[i] = make([]int, n)
for j := 0; j < n; j++ {
rotated[i][j] = image[n-j-1][i]
}
}
return rotated
}
func rotateCounterClockwise(image [][]int) [][]int {
n := len(image)
rotated := make([][]int, n)
for i := 0; i < n; i++ {
rotated[i] = make([]int, n)
for j := 0; j < n; j++ {
rotated[i][j] = image[j][n-i-1]
}
}
return rotated
}
func main() {
// example image
image := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
// rotate clockwise
rotatedClockwise := rotateClockwise(image)
fmt.Println("Rotated Clockwise:")
for _, row := range rotatedClockwise {
fmt.Println(row)
}
// rotate counterclockwise
rotatedCounterClockwise := rotateCounterClockwise(image)
fmt.Println("Rotated Counterclockwise:")
for _, row := range rotatedCounterClockwise {
fmt.Println(row)
}
}
================================================
FILE: 2D Arrays (Matrix)/rotate_matrix.java
================================================
// Rotate clockwise and anti-clockwise
/*
This program takes a 2D array (matrix) and performs two types of 90-degree rotations: clockwise and
anti-clockwise. The rotateClockwise method takes a matrix and returns a new matrix with its
elements rotated 90 degrees clockwise. The rotateAntiClockwise method takes a matrix and
returns a new matrix with its elements rotated 90 degrees anti-clockwise.
The printMatrix method is used to print the matrix elements in a readable format.
Finally, the main method initializes a test matrix and performs the two rotations on it.
*/
public class RotateMatrix {
// Rotate matrix by 90 degrees clockwise
public static int[][] rotateClockwise(int[][] matrix) {
int n = matrix.length;
int[][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix[n - j - 1][i];
}
}
return result;
}
// Rotate matrix by 90 degrees anti-clockwise
public static int[][] rotateAntiClockwise(int[][] matrix) {
int n = matrix.length;
int[][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix[j][n - i - 1];
}
}
return result;
}
// Print matrix
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
// Test program
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Original Matrix:");
printMatrix(matrix);
int[][] rotatedClockwise = rotateClockwise(matrix);
System.out.println("Matrix after 90 degree clockwise rotation:");
printMatrix(rotatedClockwise);
int[][] rotatedAntiClockwise = rotateAntiClockwise(matrix);
System.out.println("Matrix after 90 degree anti-clockwise rotation:");
printMatrix(rotatedAntiClockwise);
}
}
================================================
FILE: 2D Arrays (Matrix)/rotate_matrix.js
================================================
// Rotate clockwise and anti-clockwise
/*
Here, we first get the number of rows and columns in the matrix. Then, for rotating the matrix clockwise,
we iterate over the columns in reverse order and create a new row in the rotated matrix by iterating
over each row in the original matrix and adding the corresponding element to the new row.
Finally, we add the new row to the rotated matrix.
For rotating the matrix anti-clockwise, we again iterate over the columns but this time in the
forward order and create a new row in the rotated matrix by iterating over each row in the original
matrix in reverse order and adding the corresponding element to the new row. Finally, we add the
new row to the rotated matrix.
*/
function rotateClockwise(matrix) {
// Get the number of rows and columns in the matrix
const rows = matrix.length;
const cols = matrix[0].length;
// Create a new matrix to store the rotated matrix
const rotated = [];
// Iterate over the columns in reverse order and create a new row in the rotated matrix
for (let j = cols - 1; j >= 0; j--) {
const newRow = [];
// Iterate over each row in the matrix and add the corresponding element to the new row
for (let i = 0; i < rows; i++) {
newRow.push(matrix[i][j]);
}
// Add the new row to the rotated matrix
rotated.push(newRow);
}
// Return the rotated matrix
return rotated;
}
function rotateAntiClockwise(matrix) {
// Get the number of rows and columns in the matrix
const rows = matrix.length;
const cols = matrix[0].length;
// Create a new matrix to store the rotated matrix
const rotated = [];
// Iterate over the columns in reverse order and create a new row in the rotated matrix
for (let j = 0; j < cols; j++) {
const newRow = [];
// Iterate over each row in the matrix in reverse order and add the corresponding element to the new row
for (let i = rows - 1; i >= 0; i--) {
newRow.push(matrix[i][j]);
}
// Add the new row to the rotated matrix
rotated.push(newRow);
}
// Return the rotated matrix
return rotated;
}
================================================
FILE: 2D Arrays (Matrix)/rotate_matrix.py
================================================
# Rotate clockwise and anti-clockwise
'''
The rotate_clockwise() function takes a matrix as input and returns the matrix rotated by 90 degrees
clockwise. It does this by first transposing the matrix (swapping the elements across the diagonal),
and then reversing each row of the transposed matrix.
The rotate_counterclockwise() function takes a matrix as input and returns the matrix rotated by 90
degrees counterclockwise. It also transposes the matrix first, and then reverses each column of
the transposed matrix.
Both functions use two nested loops to iterate through the matrix and perform the required operations.
The n variable represents the size of the matrix, and is used to control the range of the loops.
'''
def rotate_clockwise(matrix):
"""
Function to rotate the given matrix by 90 degrees clockwise
"""
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row to get the final rotated matrix
for i in range(n):
matrix[i] = matrix[i][::-1]
return matrix
def rotate_counterclockwise(matrix):
"""
Function to rotate the given matrix by 90 degrees counterclockwise
"""
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each column to get the final rotated matrix
for i in range(n//2):
for j in range(n):
matrix[j][i], matrix[j][n-i-1] = matrix[j][n-i-1], matrix[j][i]
return matrix
================================================
FILE: 2D Arrays (Matrix)/search_element.cpp
================================================
/*
You are given an m x n integer matrix matrix with the following two properties:
Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
*/
class Solution {
public:
bool searchMatrix(vector<vector<int>> &matrix,int target) {
int i = 0;
int j = matrix[0].size() - 1;
while(i < matrix.size() && j >= 0)
{
if(target == matrix[i][j])
return true;
else if(target < matrix[i][j])
j--;
else
i++;
}
return false;
}
};
================================================
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.cpp
================================================
/* Name : Rajeev Kumar
Github username : Tonystart121
Repository name : data-structures-and-algorithms
Problem : Searching in 2D sorted array in C++
Issue Number : #273
Problem statement : Given a sorted matrix mat[n][m] and an element ‘x’. Find the position of x in the matrix if it is present, else print -1.
Sample testcases:
Testcase 1 -->
Input: number of rows(n) and column(m).Let n=3,m=3 and value to search x = 20 .
arr[n][m] = { {1, 5, 9},
{14, 20, 21},
{30, 34, 43} }
Output: found at (1,2);
Testcase 2 -->
Input: number of rows(n) and column(m).Let n=3,m=4 and value to search x = 43
arr[n][m] = { {1, 5, 9, 11},
{14, 20, 21, 26},
{30, 34, 43, 50} }
Output: Found at (2,3);
Time Complexity = O(n+m)
Space Complexity = O(n+m)
Explanation:
This code asks the user to enter the number of rows and column in the array and element to find in the array, and then prompts them to enter each element of the array one at a time. Once the array is complete, the code applies the linear search/mapping algorithm to find the element within the array, and then prints the position of that element to the console.
Start at the top left corner of the matrix.
Compare the target element to the element at the current position.
If the target element is equal to the element at the current position, then return the current position.
If the target element is less than the element at the current position, then move down one row.
If the target element is greater than the element at the current position, then move right one column.
Repeat steps 2-5 until the target element is found or the entire matrix has been searched.
*/
// ----------------------------------------------------------------------------- code begins now!
#include<bits/stdc++.h>
using namespace std;
int main(){
// enter array rows and column
int n,m;
cin>>n>>m;
// taking input array.
int arr[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>arr[i][j];
}
}
// taking input value to search.
int key;
cin>>key;
// initializing rightmost element as current element.
int cr_row = 0, cr_col=m-1;
bool ans = false;
while(cr_row<n and cr_col>=0){
// if key==curr output its position
if(arr[cr_row][cr_col]==key){
cout<<cr_row<<" "<<cr_col;
ans=true;
break;
}
// if key greater than array elements, row increasing.
else if(key>arr[cr_row][cr_col]){
cr_row++;
}
// if key less than array elements, col decreasing.
else if(key<arr[cr_row][cr_col]){
cr_col--;
}
}
// if not found outputting -1.
if(ans==false) cout<<"-1"<<endl;
return 0;
}
================================================
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.java
================================================
/* Issue 271
Author:maneesha
Date:10/06/2023
##Assignee:Mani1881
//About:Search in 2D sorted array in Java
//Input:
You are given an m x n integer matrix matrix with the following two properties:
Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
//Time Complexity:O(log(m * n))
//Space Complexity:O(1)
//Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
//Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
//Explanation:
>>In this code, we have the Solution class with the searchMatrix method that takes a 2D matrix and a target value as parameters.
>>It iterates through each element in the matrix and checks if the current element is equal to the target value.
>>If a match is found, it returns true. If no match is found after checking all elements, it returns false.
>>In the main function, we create an instance of the Solution class and define a sample matrix and target value.
>>We then call the searchMatrix method with the provided matrix and target, and store the result in the found variable.
>>Finally, we print whether the target was found or not.
>>In this example, the output will be "Target found: true" since the target value 5 exists in the matrix.
*/
class Solution
{
public boolean searchMatrix(int[][] matrix, int target)
{
int m = matrix.length;
int i = 0;
for (i = 0; i < m; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
if (matrix[i][j] == target)
return true;
}
}
return false;
}
public static void main(String[] args)
{
Solution solution = new Solution();
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 5;
boolean found = solution.searchMatrix(matrix, target);
System.out.println("Target found: " + found);
}
}
================================================
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.js
================================================
/*Name : Abhinav kumar
Github username : Abhinavcode13
Repository name : data-structures-and-algorithms
Problem : Search in 2D sorted array in Javascript
Issue Number : #272
Problem statement :
Explanation of the below Javascript code :
The function searchMatrix takes in a matrix (matrix) and a target integer (target) as parameters. It returns true if the target is found in the matrix and false otherwise.
The function first checks for edge cases where the matrix is empty or the rows are empty, and immediately returns false in such cases.
It then initializes variables for the number of rows (rows) and columns (cols) in the matrix, and sets the left and right indices for the binary search.
The binary search is performed using a while loop, with the left and right indices as the condition. Inside the loop, the middle index (mid) is calculated using Math.floor((left + right) / 2), and the corresponding row and column indices are derived from the mid index.
The element at the mid index is compared with the target, and based on the comparison, the search space is narrowed down by updating the left and right indices accordingly.
If the target is found, the function returns true. If the loop completes without finding the target, the function returns false.
The time complexity of this JavaScript solution is O(log(m * n)), as it performs a binary search on a list of size m * n.
*/
-------------------------------------------------------------------------//Javascript code begins here-----------------------------------------------------------------------
/**
* Searches for a target integer in a matrix.
* @param {number[][]} matrix - The matrix to search in.
* @param {number} target - The target integer to search for.
* @return {boolean} - True if the target is found, false otherwise.
*/
function searchMatrix(matrix, target) {
// Check for empty matrix or empty rows
if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
return false;
}
const rows = matrix.length;
const cols = matrix[0].length;
let left = 0;
let right = rows * cols - 1;
// Perform binary search on the matrix
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const row = Math.floor(mid / cols);
const col = mid % cols;
if (matrix[row][col] === target) {
// Target found
return true;
} else if (matrix[row][col] < target) {
// Target is in the right half of the matrix
left = mid + 1;
} else {
// Target is in the left half of the matrix
right = mid - 1;
}
}
// Target not found
return false;
}
================================================
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.py
================================================
'''
Date:28/6/23
About:Search in 2D sorted array in Python
Input:
You are given an m x n integer matrix matrix with the following two properties:
Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
Time Complexity:
You must write a solution in O(log(m * n)) time complexity.
Space Complexity:O(1)
//Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
//Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
//Explanation
The method takes two parameters: matrix, which represents the sorted matrix, and target, which is the value we want to find in the matrix.
The code initializes variables nRows and nCols to store the number of rows and columns in the matrix, respectively.
The starting position for the search is set to the bottom-left corner of the matrix (row = nRows - 1, col = 0).
The code enters a while loop that continues as long as the current row index (row) is within the bounds of the matrix (0 to nRows - 1
and the current column index (col) is within the bounds of the matrix (0 to nCols - 1).
Inside the loop, the code retrieves the value at the current position in the matrix (val = matrix[row][col]).
If the current value (val) == value, the method returns True, indicating that the target is found in the matrix.
If the current value (val) < target value, it means the target can only be found in the rows above the current row.
Therefore, the column index (col) is incremented to move to the next column.
If the current value (val) >target value, it means the target can only be found in the columns to the left of the current column.
Therefore, the row index (row) is decremented to move to the previous row.
If the loop completes without finding the target value, the method returns False.
'''
class Solution(object):
def searchMatrix(self, matrix, target):
nRows = len(matrix)
nCols = len(matrix[0])
row = nRows - 1
col = 0
while 0 <= row < nRows and 0 <= col < nCols:
val = matrix[row][col]
if val == target:
return True
elif val < target:
col += 1
else:
row -= 1
return False
# Create an instance of the Solution class
solution = Solution()
# Define the matrix and target value
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 3
# Call the searchMatrix method and print the result
result = solution.searchMatrix(matrix, target)
print(result)
================================================
FILE: 2D Arrays (Matrix)/set_matrix_0.cpp
================================================
/*
Problem:
You are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you need to set all the elements in the
corresponding row and column to zero as well.
Solution:
To solve this problem, you can follow the steps below:
1. Create two sets, rows and columns, to keep track of the rows and columns that need to be set to zero.
2. Iterate through the matrix row by row, and for each element, if it is zero, add its row index to the rows set and its column index to the columns set.
3. Iterate through the matrix again, and for each element, check if its row index or column index exists in the respective sets (rows or columns).
If either index exists, set the element to zero.
4. Finally, iterate through the matrix one more time, and for each row or column index in the rows or columns sets, set all the elements in that
row or column to zero.
5. Return the modified matrix.
Complexity:
Let's assume the matrix has dimensions MxN.
Step 2: In this step, we iterate through the matrix once, which takes O(M*N) time.
Step 3: In this step, we again iterate through the matrix once, which takes O(M*N) time.
Step 4: In this step, we iterate through the rows and columns sets, which contain at most M+N elements. Therefore, this step takes O(M+N) time.
Overall, the time complexity of the solution is O(MN + M + N), which can be simplified to O(MN). The space complexity is O(M+N) since we are
using two sets to store the rows and columns that need to be set to zero.
*/
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
void setZeroes(vector<vector<int>>& matrix) {
unordered_set<int> rows;
unordered_set<int> columns;
// Step 1: Find the rows and columns that need to be set to zero
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
if (matrix[i][j] == 0) {
rows.insert(i);
columns.insert(j);
}
}
}
// Step 2: Set the corresponding rows and columns to zero
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
if (rows.count(i) || columns.count(j)) {
matrix[i][j] = 0;
}
}
}
}
void printMatrix(const vector<vector<int>>& matrix) {
for (const auto& row : matrix) {
for (int num : row) {
cout << num << " ";
}
cout << endl;
}
}
int main() {
vector<vector<int>> matrix = {
{1, 1, 1},
{1, 0, 1},
{1, 1, 1}
};
cout << "Original Matrix:" << endl;
printMatrix(matrix);
setZeroes(matrix);
cout << "Modified Matrix:" << endl;
printMatrix(matrix);
return 0;
}
================================================
FILE: 2D Arrays (Matrix)/set_matrix_0.go
================================================
/*
Problem:
You are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you need to set all the elements in the
corresponding row and column to zero as well.
Solution:
To solve this problem, you can follow the steps below:
1. Create two sets, rows and columns, to keep track of the rows and columns that need to be set to zero.
2. Iterate through the matrix row by row, and for each element, if it is zero, add its row index to the rows set and its column index to the columns set.
3. Iterate through the matrix again, and for each element, check if its row index or column index exists in the respective sets (rows or columns).
If either index exists, set the element to zero.
4. Finally, iterate through the matrix one more time, and for each row or column index in the rows or columns sets, set all the elements in that
row or column to zero.
5. Return the modified matrix.
Complexity:
Let's assume the matrix has dimensions MxN.
Step 2: In this step, we iterate through the matrix once, which takes O(M*N) time.
Step 3: In this step, we again iterate through the matrix once, which takes O(M*N) time.
Step 4: In this step, we iterate through the rows and columns sets, which contain at most M+N elements. Therefore, this step takes O(M+N) time.
Overall, the time complexity of the solution is O(MN + M + N), which can be simplified to O(MN). The space complexity is O(M+N) since we are
using two sets to store the rows and columns that need to be set to zero.
*/
package main
import (
"fmt"
)
func setZeroes(matrix [][]int) {
rows := make(map[int]bool)
columns := make(map[int]bool)
// Step 1: Find the rows and columns that need to be set to zero
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[0]); j++ {
if matrix[i][j] == 0 {
rows[i] = true
columns[j] = true
}
}
}
// Step 2: Set the corresponding rows and columns to zero
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[0]); j++ {
if rows[i] || columns[j] {
matrix[i][j] = 0
}
}
}
}
func main() {
matrix := [][]int{
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
}
fmt.Println("Original Matrix:")
printMatrix(matrix)
setZeroes(matrix)
fmt.Println("Modified Matrix:")
printMatrix(matrix)
}
func printMatrix(matrix [][]int) {
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[0]); j++ {
fmt.Print(matrix[i][j], " ")
}
fmt.Println()
}
}
================================================
FILE: 2D Arrays (Matrix)/set_matrix_0.java
================================================
/* SET MATRIX ZERO - JAVA LANGUAGE
Problem Link1 : https://leetcode.com/problems/set-matrix-zeroes/
Problem Link2 : https://www.codingninjas.com/codestudio/problems/zero-matrix_1171153
Problem:
You are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you need to set all the elements in the
corresponding row and column to zero as well.
E.g- Input: | 1 1 1 |
| 1 0 1 |
| 1 1 1 |
Output: | 1 0 1 |
| 0 0 0 |
| 1 0 1 |
METHOD 1] Brute Force Approach for Set Matrix Zeroes
Step 1. Create an array answer of size (n X m) and initialize every element as 1.
Step 2. Traverse the matrix array row-wise and set the current row as 0 in answer array if the current row contains an element equals to 0.
Step 3. Traverse the matrix array column-wise and set the current column as 0 in answer array if the current column contains an element equals to 0.
Step 4. Now traverse the answer array, if the current element is 0, then set this element as 0 in a matrix array.
Step 5. Return matrix array
Complexity Analysis:
Time Complexity = O(n * m)
Space Complexity = O(n * m)
where n is the number of rows in the matrix and m is the number of columns in the matrix.
METHOD 2] Optimal Approach for Set Matrix Zeroes
If we assume that -1, do not occur in the matrix array, then
Step 1. Traverse the matrix array row-wise and set all the elements of current row which are not 0 as -1, if the current row contains an element equals to 0.
Step 2. Traverse the matrix array column-wise and set all the elements of the current column which are not 0 as -1, if the current column contains an element equals to 0.
Step 3. Again traverse the matrix and set all the elements that are -1 to 0.
Step 4. Return matrix array.
Complexity Analysis:
Time Complexity = O(n * m)
Space Complexity = O(1)
where n is the number of rows in the matrix and m is the number of columns in the matrix.
*/
public class setMatrixZero {
// Method 1] Brute Force Approach
private static void setZeroes_bruteForce(int[][] matrix, int n, int m) {
int answer[][] = new int[n][m]; // Step 1
// Set all elements of answer array as 1
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
answer[i][j] = 1; // making each element as 1
}
}
// Traverse row wise --> Step 2
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
// Set this row as zero in answer array
for (int k = 0; k < m; k++) {
answer[i][k] = 0;
}
break;
}
}
}
// Traverse column wise --> Step 3
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
if (matrix[i][j] == 0) {
// Set this column as 0 in answer array
for (int k = 0; k < n; k++) {
answer[k][j] = 0;
}
}
}
}
// Update the elements in matrix array --> Step 4
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (answer[i][j] == 0) {
matrix[i][j] = 0;
}
}
}
}
// Method 2] Optimal Approach
private static void setZeroes_optimalMethod(int[][] matrix, int n, int m) {
// Traverse row wise
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
// Set all the elements that are not zero as -1
for (int k = 0; k < m; k++) {
if (matrix[i][k] != 0) {
matrix[i][k] = -1;
}
}
}
}
}
// Traverse column wise
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
if (matrix[i][j] == 0) {
// Set all the elements that are not zero as -1
for (int k = 0; k < n; k++) {
if (matrix[k][j] != 0) {
matrix[k][j] = -1;
}
}
}
}
}
// Update all -1 as 0
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == -1) {
matrix[i][j] = 0;
}
}
}
}
public static void main(String[] args) {
// Example using Method 1 - Brute Force
int[][] matrix1 = new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // Defining Matrix
int n = matrix1.length;
int m = matrix1[0].length;
setZeroes_bruteForce(matrix1, n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(matrix1[i][j] + " "); // Printing Matrix
}
System.out.println();
}
System.out.println("-----------------");
// Example using Method 2 - Optimal
int[][] matrix2 = new int[][] {{0, 0, 6, 0}, {1, 4, 9, 0}, {1, 8, 1, 8}}; // Defining Matrix
n = matrix2.length;
m = matrix2[0].length;
setZeroes_optimalMethod(matrix2, n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(matrix2[i][j] + " "); // Printing Matrix
}
System.out.println();
}
}
}
================================================
FILE: 2D Arrays (Matrix)/spiral_traverse.cpp
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and
returns a one-dimensional array of all the array's elements in spiral order.
Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds
in a spiral pattern all the way until every element has been visited.
Explanation:
The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the
elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise.
The function first initializes an empty slice result to hold the elements of the spiral traversal.
If the input array is empty, the function immediately returns the empty result.
Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the
boundaries of the matrix. These variables will be updated as the function traverses the matrix.
The function then enters a loop that traverses the matrix in a spiral order. The loop continues
as long as startRow <= endRow and startCol <= endCol, which means that there are still elements
in the matrix to be traversed.
The first step in the loop is to traverse the top row of the matrix from left to right, and append
each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom,
and append each element to the result slice. If there is more than one row in the matrix, the function then traverses
the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left,
the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix,
the function traverses the left
O(n) time | O(n) space - where n is the total number of elements in the array
*/
#include<bits/stdc++.h>
using namespace std;
#include <vector>
using namespace std;
vector<int> SpiralTraverse(vector<vector<int>> array) {
vector<int> result; // vector to store the spiral traversal
int rows = array.size(); // number of rows in the input array
int cols = array[0].size(); // number of columns in the input array
int startRow = 0, endRow = rows - 1; // indices for the start and end row of the current subarray
int startCol = 0, endCol = cols - 1; // indices for the start and end column of the current subarray
// loop until the entire input array is traversed
while (startRow <= endRow && startCol <= endCol) {
// traverse the top row from left to right
for (int col = startCol; col <= endCol; col++) {
result.push_back(array[startRow][col]);
}
// traverse the right column from top to bottom
for (int row = startRow + 1; row <= endRow; row++) {
result.push_back(array[row][endCol]);
}
// traverse the bottom row from right to left
for (int col = endCol - 1; col >= startCol; col--) {
// check if there is only one row in the subarray
if (startRow == endRow) {
break;
}
result.push_back(array[endRow][col]);
}
// traverse the left column from bottom to top
for (int row = endRow - 1; row > startRow; row--) {
// check if there is only one column in the subarray
if (startCol == endCol) {
break;
}
result.push_back(array[row][startCol]);
}
// update the indices for the next subarray to be traversed
startRow++;
endRow--;
startCol++;
endCol--;
}
return result;
}
int main() {
vector<vector<int>> array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
vector<int> result = SpiralTraverse(array);
cout << "Spiral traversal: ";
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
cout << endl;
return 0;
}
================================================
FILE: 2D Arrays (Matrix)/spiral_traverse.go
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and
returns a one-dimensional array of all the array's elements in spiral order.
Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds
in a spiral pattern all the way until every element has been visited.
Explanation:
The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the
elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise.
The function first initializes an empty slice result to hold the elements of the spiral traversal.
If the input array is empty, the function immediately returns the empty result.
Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the
boundaries of the matrix. These variables will be updated as the function traverses the matrix.
The function then enters a loop that traverses the matrix in a spiral order. The loop continues
as long as startRow <= endRow and startCol <= endCol, which means that there are still elements
in the matrix to be traversed.
The first step in the loop is to traverse the top row of the matrix from left to right, and append
each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom,
and append each element to the result slice. If there is more than one row in the matrix, the function then traverses
the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left,
the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix,
the function traverses the left
O(n) time | O(n) space - where n is the total number of elements in the array
*/
package main
import "fmt"
func SpiralTraverse(array [][]int) []int {
// Initialize an empty slice to hold the result
result := []int{}
// If the input array is empty, return the empty result
if len(array) == 0 {
return result
}
// Initialize variables to keep track of the boundaries of the matrix
startRow, endRow := 0, len(array)-1
startCol, endCol := 0, len(array[0])-1
// Traverse the matrix in a spiral order
for startRow <= endRow && startCol <= endCol {
// Traverse the top row from left to right
for col := startCol; col <= endCol; col++ {
result = append(result, array[startRow][col])
}
// Traverse the rightmost column from top to bottom
for row := startRow + 1; row <= endRow; row++ {
result = append(result, array[row][endCol])
}
// Traverse the bottom row from right to left, if there is more than one row
for col := endCol - 1; col >= startCol; col-- {
// If there is only one row left, break the loop to avoid duplicating the elements
if startRow == endRow {
break
}
result = append(result, array[endRow][col])
}
// Traverse the leftmost column from bottom to top, if there is more than one column
for row := endRow - 1; row > startRow; row-- {
// If there is only one column left, break the loop to avoid duplicating the elements
if startCol == endCol {
break
}
result = append(result, array[row][startCol])
}
// Update the boundaries of the matrix
startRow++
endRow--
startCol++
endCol--
}
// Return the result slice
return result
}
func main() {
// Example 2D array
array := [][]int{
{1, 2, 3, 4},
{10, 11, 12, 5},
{9, 8, 7, 6},
}
// Call SpiralTraverse function on array
result := SpiralTraverse(array)
// Print the result to console
fmt.Println(result)
}
================================================
FILE: 2D Arrays (Matrix)/spiral_traverse.java
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and
returns a one-dimensional array of all the array's elements in spiral order.
Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds
in a spiral pattern all the way until every element has been visited.
Explanation:
The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the
elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise.
The function first initializes an empty slice result to hold the elements of the spiral traversal.
If the input array is empty, the function immediately returns the empty result.
Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the
boundaries of the matrix. These variables will be updated as the function traverses the matrix.
The function then enters a loop that traverses the matrix in a spiral order. The loop continues
as long as startRow <= endRow and startCol <= endCol, which means that there are still elements
in the matrix to be traversed.
The first step in the loop is to traverse the top row of the matrix from left to right, and append
each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom,
and append each element to the result slice. If there is more than one row in the matrix, the function then traverses
the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left,
the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix,
the function traverses the left
O(n) time | O(n) space - where n is the total number of elements in the array
*/
import java.util.*;
public class SpiralTraverse {
public static void main(String[] args) {
int[][] array = { {1, 2, 3},
{12, 13, 4},
{11, 14, 5},
{10, 15, 6},
{9, 8, 7} };
System.out.println(spiralFillUsingLoop(array));
// spiralFillUsingRecursion(array, 0, array.length - 1, 0, array[0].length - 1, result);
}
public static List<Integer> spiralFillUsingLoop(int[][] array) {
// O(n) time | O(n) space;
if(array.length == 0) return new ArrayList<>();
var result = new ArrayList<Integer>();
var startRow = 0;
var endRow = array.length - 1;
var startCol = 0;
var endCol = array[0].length - 1;
while(startRow <= endRow && startCol <= endCol) {
for(int col = startCol; col <= endCol; col++)
result.add(array[startRow][col]);
for(int row = startRow + 1; row <= endRow; row++)
result.add(array[row][endCol]);
for(int col = endCol - 1; col >= startCol; col--) {
/**
* Handle the edge case when there's a single row
* in the middle of the matrix, In this case. we don't
* want to double-count the values in this row, which
* we've already counted in the first for loop above.
* Test case for this edge case :
* [
* [1, 2, 3, 4],
* [10, 11, 12, 5],
* [9, 8, 7, 6]
* ]
*
*
*/
if(startRow == endRow) break;
result.add(array[endRow][col]);
}
for(int row = endRow - 1; row > startRow; row--) {
/**
* Handle the edge case when there's a single column
* in the middle of the matrix, In this case. we don't
* want to double-count the values in this row, which
* we've already counted in the first for loop above.
* Test case for this edge case :
* [
* [1, 2, 3],
* [12, 13, 4],
* [11, 14, 5],
* [10, 15, 6],
* ]
*
*/
if(startCol == endCol) break;
result.add(array[row][startCol]);
}
startRow++;
endRow--;
startCol++;
endCol--;
}
return result;
}
public static void spiralFillUsingRecursion(
int[][] array,
int startRow,
int endRow,
int startCol,
int endCol,
ArrayList<Integer> result) {
// O(n) time | O(n) space;
if(startRow > endRow || startCol > endCol) return;
for(int col = startCol; col <= endCol; col++)
result.add(array[startRow][col]);
for(int row = startRow + 1; row <= endRow; row++)
result.add(array[row][endCol]);
for(int col = endCol - 1; col >= startCol; col--) {
if(startRow == endRow) break;
result.add(array[endRow][col]);
}
for(int row = endRow - 1; row > startRow; row--) {
if(startCol == endCol) break;
result.add(array[row][startCol]);
}
spiralFillUsingRecursion(array, startRow + 1, endRow -1, startCol + 1, endCol - 1, result);
}
}
================================================
FILE: 2D Arrays (Matrix)/spiral_traverse.py
================================================
##### LEETCODE 54. Spiral Matrix ####
##### INPUT OUTPUT #####
# Given an m x n matrix, return all elements of the matrix in spiral order.
# Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
# Output: [1,2,3,6,9,8,7,4,5]
# Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
# Output: [1,2,3,4,8,12,11,10,9,5,6,7]
# Write python code along with explanation and comments use meaningful variables
##### EXPLAINATION #####
# The given problem statement is to return all elements of the matrix in spiral order. We can start by defining the four boundaries of the matrix - top, bottom, left and right. We can then traverse the matrix in a spiral order by following these four steps:
# Traverse from left to right along the top boundary
# Traverse from top to bottom along the right boundary
# Traverse from right to left along the bottom boundary
# Traverse from bottom to top along the left boundary
# After each traversal, we need to update the corresponding boundary and change the direction of traversal.
# We can implement this algorithm using a while loop that runs as long as the top boundary is less than or equal to the bottom boundary and the left boundary is less than or equal to the right boundary. Within the while loop, we can use an if-else ladder to check the current direction of traversal and perform the corresponding traversal along the boundary.
# Finally, we can return the result list containing all the spiral order elements of the matrix.
#### DRY RUN: ####
# Initially, we have the matrix:
# 1 2 3
# 4 5 6
# 7 8 9
# We initialize the variables top, bottom, left, and right to 0, 2, 0, and 2 respectively. We also set the direction variable to 0.
# Now, we enter the while loop since top<=bottom and left<=right.
# In the first iteration of the while loop, direction=0 means we need to traverse from left to right along the top boundary.
# We iterate the for loop from left=0 to right=2 and append the elements 1, 2, 3 to the result list. After this, we increment top by 1 to mark that the top boundary is now done.
# The result list now contains [1, 2, 3].
# In the second iteration of the while loop, direction=1 means we need to traverse from top to bottom along the right boundary.
# We iterate the for loop from top=1 to bottom=2 and append the elements 6, 9 to the result list. After this, we decrement right by 1 to mark that the right boundary is now done.
# The result list now contains [1, 2, 3, 6, 9].
# In the third iteration of the while loop, direction=2 means we need to traverse from right to left along the bottom boundary.
# We iterate the for loop from right=1 to left=0 and append the elements 8, 7 to the result list. After this, we decrement bottom by 1 to mark that the bottom boundary is now done.
# The result list now contains [1, 2, 3, 6, 9, 8, 7].
# In the fourth iteration of the while loop, direction=3 means we need to traverse from bottom to top along the left boundary.
# We iterate the for loop from bottom=1 to top=1 and append the element 4 and 5 to the result list. After this, we increment left by 1 to mark that the left boundary is now done.
# The result list now contains [1, 2, 3, 6, 9, 8, 7, 4, 5].
# Now, we have completed one full spiral traversal of the matrix. The direction variable is updated as (0+1)%4=1 which sets it to 1 for the next iteration.
# We continue with the while loop since top<=bottom and left<=right. In the second iteration, the process continues in the same way as described above until all elements of the matrix are visited.
# Finally, the function returns the result list containing all the spiral order elements of the matrix.
def spiralOrder(matrix):
# Initialize variables to keep track of indices and boundaries
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
direction = 0 # 0 = right, 1 = down, 2 = left, 3 = up
# Initialize an empty result list to store the spiral order elements
result = []
while top <= bottom and left <= right:
if direction == 0:
# Traverse right
for i in range(left, right+1):
result.append(matrix[top][i])
top += 1
elif direction == 1:
# Traverse down
for i in range(top, bottom+1):
result.append(matrix[i][right])
right -= 1
elif direction == 2:
# Traverse left
for i in range(right, left-1, -1):
result.append(matrix[bottom][i])
bottom -= 1
else:
# Traverse up
for i in range(bottom, top-1, -1):
result.append(matrix[i][left])
left += 1
# Update direction after completing one full traversal
direction = (direction + 1) % 4
return result
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(spiralOrder(matrix))
================================================
FILE: 2D Arrays (Matrix)/zigzag_traversal.cpp
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)
and returns a one-dimensional array of all the array's elements in zigzag order.
Sample Input:= [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16],
]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Explanation:
The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and
returns the elements in a 1D array.
Here's an explanation of the code:
1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing
the elements traversed in zigzag order.
2. `height` and `width`: These variables store the height and width of the 2D array, respectively.
The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing).
3. `row` and `col`: These variables keep track of the current position while traversing the 2D array.
4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal
is in the downward direction; otherwise, it is in the upward direction.
5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result.
6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array).
7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array.
8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag.
If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position).
9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the
2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively).
10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of
the 2D array in zigzag order.
The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches
the boundary or the corners of the array, allowing it to cover all elements in zigzag order.
O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array
*/
#include <vector>
using namespace std;
vector<int> ZigzagTraverse(vector<vector<int>>& array) {
// Get the height (number of rows) and width (number of columns) of the array.
int height = array.size();
int width = array[0].size();
// Initialize the row and column pointers to start from the top-left element (0,0).
int row = 0;
int col = 0;
// Initialize a flag to track the direction of traversal (goingDown).
// true means moving down, false means moving up.
bool goingDown = true;
// Initialize a vector to store the elements in zigzag order.
vector<int> result;
// Loop until the current position is within the bounds of the array.
while (!isOutOfBounds(row, col, height, width)) {
// Append the current element to the result vector.
result.push_back(array[row][col]);
// If moving down, check if we reached the bottom row or leftmost column.
if (goingDown) {
if (col == 0 || row == height - 1) {
// Change direction if we reached the bottom row or leftmost column.
goingDown = false;
if (row == height - 1) {
// Move right if we reached the bottom row.
col++;
} else {
// Move down if we reached the leftmost column.
row++;
}
} else {
// Move diagonally down-left.
row++;
col--;
}
} else {
// If moving up, check if we reached the top row or rightmost column.
if (row == 0 || col == width - 1) {
// Change direction if we reached the top row or rightmost column.
goingDown = true;
if (col == width - 1) {
// Move down if we reached the rightmost column.
row++;
} else {
// Move right if we reached the top row.
col++;
}
} else {
// Move diagonally up-right.
row--;
col++;
}
}
}
// Return the vector containing the elements in zigzag order.
return result;
}
bool isOutOfBounds(int row, int col, int height, int width) {
// Check if the current position is outside the bounds of the array.
return row < 0 || col < 0 || row >= height || col >= width;
}
================================================
FILE: 2D Arrays (Matrix)/zigzag_traversal.go
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)
and returns a one-dimensional array of all the array's elements in zigzag order.
Sample Input:= [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16],
]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Explanation:
The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and
returns the elements in a 1D array.
Here's an explanation of the code:
1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing
the elements traversed in zigzag order.
2. `height` and `width`: These variables store the height and width of the 2D array, respectively.
The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing).
3. `row` and `col`: These variables keep track of the current position while traversing the 2D array.
4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal
is in the downward direction; otherwise, it is in the upward direction.
5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result.
6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array).
7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array.
8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag.
If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position).
9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the
2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively).
10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of
the 2D array in zigzag order.
The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches
the boundary or the corners of the array, allowing it to cover all elements in zigzag order.
O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array
*/
package main
// ZigzagTraverse traverses a 2D array in a zigzag pattern and returns the elements in a 1D array.
func ZigzagTraverse(array [][]int) []int {
// Get the height and width of the 2D array.
height := len(array) - 1
width := len(array[0]) - 1
// Initialize variables to keep track of the current position while traversing.
row, col := 0, 0
// Initialize a boolean variable to determine the direction of traversal.
goingDown := true
// Initialize an array to store the elements traversed in zigzag order.
result := []int{}
// The main loop runs until the current position is within bounds (not out of the 2D array).
for !isOutOfBounds(row, col, height, width) {
// Append the current element at position (row, col) to the result array.
result = append(result, array[row][col])
// Traversal logic: Decide the next position for traversal based on the current position and the goingDown flag.
if goingDown {
if col == 0 || row == height {
// Change direction to upward if at the top-left or bottom-right corner.
goingDown = false
// Decide the next position based on whether we are at the bottom or right boundary.
if row == height {
col++
} else {
row++
}
} else {
// Continue diagonally downward.
row++
col--
}
} else {
if row == 0 || col == width {
// Change direction to downward if at the top-right or bottom-left corner.
goingDown = true
// Decide the next position based on whether we are at the top or right boundary.
if col == width {
row++
} else {
col++
}
} else {
// Continue diagonally upward.
row--
col++
}
}
}
// Return the final result, which contains the elements of the 2D array in zigzag order.
return result
}
// isOutOfBounds checks if the current position (row, col) is out of bounds of the 2D array.
func isOutOfBounds(row, col, height, width int) bool {
return row < 0 || col < 0 || row > height || col > width
}
================================================
FILE: 2D Arrays (Matrix)/zigzag_traversal.java
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)
and returns a one-dimensional array of all the array's elements in zigzag order.
Sample Input:= [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16],
]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Explanation:
The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and
returns the elements in a 1D array.
Here's an explanation of the code:
1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing
the elements traversed in zigzag order.
2. `height` and `width`: These variables store the height and width of the 2D array, respectively.
The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing).
3. `row` and `col`: These variables keep track of the current position while traversing the 2D array.
4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal
is in the downward direction; otherwise, it is in the upward direction.
5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result.
6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array).
7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array.
8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag.
If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position).
9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the
2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively).
10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of
the 2D array in zigzag order.
The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches
the boundary or the corners of the array, allowing it to cover all elements in zigzag order.
O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array
*/
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<Integer> ZigzagTraverse(int[][] array) {
// Get the height (number of rows) and width (number of columns) of the array.
int height = array.length;
int width = array[0].length;
// Initialize the row and column pointers to start from the top-left element (0,0).
int row = 0;
int col = 0;
// Initialize a flag to track the direction of traversal (goingDown).
// true means moving down, false means moving up.
boolean goingDown = true;
// Initialize a list to store the elements in zigzag order.
List<Integer> result = new ArrayList<>();
// Loop until the current position is within the bounds of the array.
while (!isOutOfBounds(row, col, height, width)) {
// Append the current element to the result list.
result.add(array[row][col]);
// If moving down, check if we reached the bottom row or leftmost column.
if (goingDown) {
if (col == 0 || row == height - 1) {
// Change direction if we reached the bottom row or leftmost column.
goingDown = false;
if (row == height - 1) {
// Move right if we reached the bottom row.
col++;
} else {
// Move down if we reached the leftmost column.
row++;
}
} else {
// Move diagonally down-left.
row++;
col--;
}
} else {
// If moving up, check if we reached the top row or rightmost column.
if (row == 0 || col == width - 1) {
// Change direction if we reached the top row or rightmost column.
goingDown = true;
if (col == width - 1) {
// Move down if we reached the rightmost column.
row++;
} else {
// Move right if we reached the top row.
col++;
}
} else {
// Move diagonally up-right.
row--;
col++;
}
}
}
// Return the list containing the elements in zigzag order.
return result;
}
public static boolean isOutOfBounds(int row, int col, int height, int width) {
// Check if the current position is outside the bounds of the array.
return row < 0 || col < 0 || row >= height || col >= width;
}
public static void main(String[] args) {
int[][] array = {
{1, 3, 4, 10},
{2, 5, 9, 11},
{6, 8, 12, 15},
{7, 13, 14, 16}
};
List<Integer> result = ZigzagTraverse(array);
System.out.println(result);
}
}
================================================
FILE: 2D Arrays (Matrix)/zigzag_traversal.js
================================================
/*
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)
and returns a one-dimensional array of all the array's elements in zigzag order.
Sample Input:= [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16],
]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Explanation:
The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and
returns the elements in a 1D array.
Here's an explanation of the code:
1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing
the elements traversed in zigzag order.
2. `height` and `width`: These variables store the height and width of the 2D array, respectively.
The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing).
3. `row` and `col`: These variables keep track of the current position while traversing the 2D array.
4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal
is in the downward direction; otherwise, it is in the upward direction.
5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result.
6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array).
7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array.
8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag.
If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position).
9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the
2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively).
10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of
the 2D array in zigzag order.
The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches
the boundary or the corners of the array, allowing it to cover all elements in zigzag order.
O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array
*/
function ZigzagTraverse(array) {
// Get the height (number of rows) and width (number of columns) of the array.
const height = array.length;
const width = array[0].length;
// Initialize the row and column pointers to start from the top-left element (0,0).
let row = 0;
let col = 0;
// Initialize a flag to track the direction of traversal (goingDown).
// true means moving down, false means moving up.
let goingDown = true;
// Initialize an array to store the elements in zigzag order.
const result = [];
// Loop until the current position is within the bounds of the array.
while (!isOutOfBounds(row, col, height, width)) {
// Append the current element to the result array.
result.push(array[row][col]);
// If moving down, check if we reached the bottom row or leftmost column.
if (goingDown) {
if (col === 0 || row === height - 1) {
// Change direction if we reached the bottom row or leftmost column.
goingDown = false;
if (row === height - 1) {
// Move right if we reached the bottom row.
col++;
} else {
// Move down if we reached the leftmost column.
row++;
}
} else {
// Move diagonally down-left.
row++;
col--;
}
} else {
// If moving up, check if we reached the top row or rightmost column.
if (row === 0 || col === width - 1) {
// Change direction if we reached the top row or rightmost column.
goingDown = true;
if (col === width - 1) {
// Move down if we reached the rightmost column.
row++;
} else {
// Move right if we reached the top row.
col++;
}
} else {
// Move diagonally up-right.
row--;
col++;
}
}
}
// Return the array containing the elements in zigzag order.
return result;
}
function isOutOfBounds(row, col, height, width) {
// Check if the current position is outside the bounds of the array.
return row < 0 || col < 0 || row >= height || col >= width;
}
================================================
FILE: 2D Arrays (Matrix)/zigzag_traversal.py
================================================
'''
Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)
and returns a one-dimensional array of all the array's elements in zigzag order.
Sample Input:= [
[1, 3, 4, 10],
[2, 5, 9, 11],
[6, 8, 12, 15],
[7, 13, 14, 16],
]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Explanation:
The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and
returns the elements in a 1D array.
Here's an explanation of the code:
1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing
the elements traversed in zigzag order.
2. `height` and `width`: These variables store the height and width of the 2D array, respectively.
The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing).
3. `row` and `col`: These variables keep track of the current position while traversing the 2D array.
4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal
is in the downward direction; otherwise, it is in the upward direction.
5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result.
6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array).
7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array.
8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag.
If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position).
9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the
2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively).
10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of
the 2D array in zigzag order.
The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches
the boundary or the corners of the array, allowing it to cover all elements in zigzag order.
O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array
'''
def ZigzagTraverse(array):
# Get the height (number of rows) and width (number of columns) of the array.
height = len(array)
width = len(array[0])
# Initialize the row and column pointers to start from the top-left element (0,0).
row, col = 0, 0
# Initialize a flag to track the direction of traversal (goingDown).
# True means moving down, False means moving up.
goingDown = True
# Initialize a list to store the elements in zigzag order.
result = []
# Loop until the current position is within the bounds of the array.
while not isOutOfBounds(row, col, height, width):
# Append the current element to the result list.
result.append(array[row][col])
# If moving down, check if we reached the bottom row or leftmost column.
if goingDown:
if col == 0 or row == height - 1:
# Change direction if we reached the bottom row or leftmost column.
goingDown = False
if row == height - 1:
# Move right if we reached the bottom row.
col += 1
else:
# Move down if we reached the leftmost column.
row += 1
else:
# Move diagonally down-left.
row += 1
col -= 1
else:
# If moving up, check if we reached the top row or rightmost column.
if row == 0 or col == width - 1:
# Change direction if we reached the top row or rightmost column.
goingDown = True
if col == width - 1:
# Move down if we reached the rightmost column.
row += 1
else:
# Move right if we reached the top row.
col += 1
else:
# Move diagonally up-right.
row -= 1
col += 1
# Return the list containing the elements in zigzag order.
return result
def isOutOfBounds(row, col, height, width):
# Check if the current position is outside the bounds of the array.
return row < 0 or col < 0 or row >= height or col >= width
================================================
FILE: Arrays/Jobassign.cpp
================================================
#include <stdio.h>
#include <limits.h>
#define N 4 // Number of workers and tasks
void hungarianAlgorithm(int costMatrix[N][N]);
int main() {
int costMatrix[N][N] = {
{9, 2, 7, 8},
{6, 4, 3, 7},
{5, 8, 1, 8},
{7, 6, 9, 4}
};
hungarianAlgorithm(costMatrix);
return 0;
}
void hungarianAlgorithm(int costMatrix[N][N]) {
int i, j;
int numWorkers = N, numTasks = N;
int minCost, minCostIdx;
int rowCover[N] = {0};
int colCover[N] = {0};
int assignment[N][2] = {0}; // Stores the assignment
// Step 1: Subtract the smallest value in each row from all elements in that row
for (i = 0; i < numWorkers; i++) {
minCost = INT_MAX;
for (j = 0; j < numTasks; j++) {
if (costMatrix[i][j] < minCost) {
minCost = costMatrix[i][j];
}
}
for (j = 0; j < numTasks; j++) {
costMatrix[i][j] -= minCost;
}
}
// Step 2: Find a zero in the cost matrix and mark the row and column
for (i = 0; i < numWorkers; i++) {
for (j = 0; j < numTasks; j++) {
if (costMatrix[i][j] == 0 && !rowCover[i] && !colCover[j]) {
assignment[i][0] = i;
assignment[i][1] = j;
rowCover[i] = 1;
colCover[j] = 1;
}
}
}
// Step 3: Check if all rows are covered
int rowCoveredCount = 0;
for (i = 0; i < numWorkers; i++) {
rowCoveredCount += rowCover[i];
}
if (rowCoveredCount == numWorkers) {
// All rows are covered, we have the optimal assignment
printf("Optimal Assignment:\n");
for (i = 0; i < numWorkers; i++) {
printf("Worker %d -> Task %d\n", assignment[i][0] + 1, assignment[i][1] + 1);
}
return;
} else {
// Proceed to step 4
}
// Step 4: Find the minimum uncovered value (minCost) in the cost matrix
minCost = INT_MAX;
for (i = 0; i < numWorkers; i++) {
for (j = 0; j < numTasks; j++) {
if (!rowCover[i] && !colCover[j] && costMatrix[i][j] < minCost) {
minCost = costMatrix[i][j];
}
}
}
// Step 5: Subtract minCost from all uncovered elements and add it to all elements at the intersection of covering lines
for (i = 0; i < numWorkers; i++) {
for (j = 0; j < numTasks; j++) {
if (!rowCover[i] && !colCover[j]) {
costMatrix[i][j] -= minCost;
} else if (rowCover[i] && colCover[j]) {
costMatrix[i][j] += minCost;
}
}
}
// Continue to step 3
hungarianAlgorithm(costMatrix);
}
================================================
FILE: Arrays/Maximum_freq.py
================================================
class Solution {
public int majorityElement(int[] nums) {
int candidate = nums[0]; // Initialize the candidate as the first element
int count = 1; // Initialize the count of the current candidate as 1
// Iterate through the array starting from the second element
for (int i = 1; i < nums.length; i++) {
if (nums[i] == candidate) {
// If the current element is the same as the candidate, increment the count
count++;
} else if (count > 0) {
// If the current element is different from the candidate and count is positive,
// decrement the count since we have a matching pair (candidate vs. current element)
count--;
} else {
// If count becomes zero, update the candidate to the current element and set count to 1
candidate = nums[i];
count = 1;
}
}
// At the end, the candidate will be the majority element
return candidate;
}
}
================================================
FILE: Arrays/Rotatedarr.cpp
================================================
class Solution {
public:
int search(std::vector<int>& nums, int target) {
int low = 0, high = nums.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[low] <= nums[mid]) {
if (nums[low] <= target && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
if (nums[mid] < target && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}
};
================================================
FILE: Arrays/array_of_products.cpp
================================================
/*
Given an array of integers A, find and return the product array of the same size where the ith
element of the product array will be equal to the product of all the elements divided by the ith
element of the array.
Note: It is always possible to form the product array with integer (32 bit) values.
Solve it without using the division operator.
Input: [1, 2, 3, 4, 5]
Output : [120, 60, 40, 30, 24]
Explanation:
The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works:
1. It initializes an empty result array with the same length as the input array to store the final products.
2. It uses a left-to-right approach to compute the running product of all elements to the left of each index.
3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side.
4. It iterates over the input array from left to right using a `for` loop.
5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the
`leftRunningProduct` by multiplying it with the corresponding element in the input array.
6. After the loop, the result array will contain the product of all elements to the left of each index.
7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and
multiply it with the corresponding left product in the result array.
8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side.
9. It iterates over the input array from right to left using a `for` loop.
10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array
and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array.
11. After the loop, the result array will contain the product of all elements to the left and right of each index,
except for the element at that index.
12. Finally, it returns the result array.
This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products.
*/
#include <iostream>
#include <vector>
using namespace std;
// Given an array of integers, returns an array where each element
// is the product of all the integers in the input array except for the one at that index.
vector<int> ArrayOfProducts(vector<int>& array) {
int n = array.size();
vector<int> result(n, 1);
// Compute the running product of all elements to the left of each index
// and store it in the result array.
int leftRunningProduct = 1;
for (int i = 0; i < n; i++) {
result[i] = leftRunningProduct; // Store left product in the result array
leftRunningProduct *= array[i]; // Update left product
}
// Compute the running product of all elements to the right of each index
// and multiply it with the corresponding left product in the result array.
int rightRunningProduct = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= rightRunningProduct; // Multiply the right product with the corresponding left product
rightRunningProduct *= array[i]; // Update right product
}
return result;
}
int main() {
// Example usage
vector<int> input = {1, 2, 3, 4, 5};
vector<int> output = ArrayOfProducts(input);
// Print the result
for (int num : output) {
cout << num << " ";
}
cout << endl;
return 0;
}
================================================
FILE: Arrays/array_of_products.go
================================================
/*
Given an array of integers A, find and return the product array of the same size where the ith
element of the product array will be equal to the product of all the elements divided by the ith
element of the array.
Note: It is always possible to form the product array with integer (32 bit) values.
Solve it without using the division operator.
Input: [1, 2, 3, 4, 5]
Output : [120, 60, 40, 30, 24]
Explanation:
The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works:
1. It initializes an empty result array with the same length as the input array to store the final products.
2. It uses a left-to-right approach to compute the running product of all elements to the left of each index.
3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side.
4. It iterates over the input array from left to right using a `for` loop.
5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the
`leftRunningProduct` by multiplying it with the corresponding element in the input array.
6. After the loop, the result array will contain the product of all elements to the left of each index.
7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and
multiply it with the corresponding left product in the result array.
8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side.
9. It iterates over the input array from right to left using a `for` loop.
10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array
and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array.
11. After the loop, the result array will contain the product of all elements to the left and right of each index,
except for the element at that index.
12. Finally, it returns the result array.
This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products.
*/
package main
// Given an array of integers, returns an array where each element
// is the product of all the integers in the input array except for the one at that index.
func ArrayOfProducts(array []int) []int {
result := make([]int, len(array))
// Compute the running product of all elements to the left of each index
// and store it in the result array.
leftRunningProduct := 1
for i := 0; i < len(array); i++ {
result[i] = leftRunningProduct // Store left product in the result array
leftRunningProduct *= array[i] // Update left product
}
// Compute the running product of all elements to the right of each index
// and multiply it with the corresponding left product in the result array.
rightRunningProduct := 1
for i := len(array) - 1; i >= 0; i-- {
result[i] = rightRunningProduct * result[i] // Multiply the right product with the corresponding left product
rightRunningProduct *= array[i] // Update right product
}
return result
}
================================================
FILE: Arrays/array_of_products.java
================================================
/*
Given an array of integers A, find and return the product array of the same size where the ith
element of the product array will be equal to the product of all the elements divided by the ith
element of the array.
Note: It is always possible to form the product array with integer (32 bit) values.
Solve it without using the division operator.
Input: [1, 2, 3, 4, 5]
Output : [120, 60, 40, 30, 24]
Explanation:
The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works:
1. It initializes an empty result array with the same length as the input array to store the final products.
2. It uses a left-to-right approach to compute the running product of all elements to the left of each index.
3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side.
4. It iterates over the input array from left to right using a `for` loop.
5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the
`leftRunningProduct` by multiplying it with the corresponding element in the input array.
6. After the loop, the result array will contain the product of all elements to the left of each index.
7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and
multiply it with the corresponding left product in the result array.
8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side.
9. It iterates over the input array from right to left using a `for` loop.
10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array
and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array.
11. After the loop, the result array will contain the product of all elements to the left and right of each index,
except for the element at that index.
12. Finally, it returns the result array.
This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products.
*/
import java.util.Arrays;
public class ArrayOfProducts {
public static int[] arrayOfProducts(int[] array) {
int n = array.length;
int[] result = new int[n];
// Compute the running product of all elements to the left of each index
// and store it in the result array.
int leftRunningProduct = 1;
for (int i = 0; i < n; i++) {
result[i] = leftRunningProduct; // Store left product in the result array
leftRunningProduct *= array[i]; // Update left product
}
// Compute the running product of all elements to the right of each index
// and multiply it with the corresponding left product in the result array.
int rightRunningProduct = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= rightRunningProduct; // Multiply the right product with the corresponding left product
rightRunningProduct *= array[i]; // Update right product
}
return result;
}
public static void main(String[] args) {
// Example usage
int[] input = {1, 2, 3, 4, 5};
int[] output = arrayOfProducts(input);
// Print the result
System.out.println(Arrays.toString(output));
}
}
================================================
FILE: Arrays/array_of_products.js
================================================
/*
Given an array of integers A, find and return the product array of the same size where the ith
element of the product array will be equal to the product of all the elements divided by the ith
element of the array.
Note: It is always possible to form the product array with integer (32 bit) values.
Solve it without using the division operator.
Input: [1, 2, 3, 4, 5]
Output : [120, 60, 40, 30, 24]
Explanation:
The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works:
1. It initializes an empty result array with the same length as the input array to store the final products.
2. It uses a left-to-right approach to compute the running product of all elements to the left of each index.
3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side.
4. It iterates over the input array from left to right using a `for` loop.
5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the
`leftRunningProduct` by multiplying it with the corresponding element in the input array.
6. After the loop, the result array will contain the product of all elements to the left of each index.
7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and
multiply it with the corresponding left product in the result array.
8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side.
9. It iterates over the input array from right to left using a `for` loop.
10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array
and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array.
11. After the loop, the result array will contain the product of all elements to the left and right of each index,
except for the element at that index.
12. Finally, it returns the result array.
This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products.
*/
function arrayOfProducts(array) {
const n = array.length;
const result = new Array(n).fill(1);
// Compute the running product of all elements to the left of each index
// and store it in the result array.
let leftRunningProduct = 1;
for (let i = 0; i < n; i++) {
result[i] = leftRunningProduct; // Store left product in the result array
leftRunningProduct *= array[i]; // Update left product
}
// Compute the running product of all elements to the right of each index
// and multiply it with the corresponding left product in the result array.
let rightRunningProduct = 1;
for (let i = n - 1; i >= 0; i--) {
result[i] *= rightRunningProduct; // Multiply the right product with the corresponding left product
rightRunningProduct *= array[i]; // Update right product
}
return result;
}
// Example usage
const inputArray = [1, 2, 3, 4, 5];
const outputArray = arrayOfProducts(inputArray);
// Print the result
console.log(outputArray);
================================================
FILE: Arrays/array_of_products.py
================================================
'''
Given an array of integers A, find and return the product array of the same size where the ith
element of the product array will be equal to the product of all the elements divided by the ith
element of the array.
Note: It is always possible to form the product array with integer (32 bit) values.
Solve it without using the division operator.
Input: [1, 2, 3, 4, 5]
Output : [120, 60, 40, 30, 24]
Explanation:
The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works:
1. It initializes an empty result array with the same length as the input array to store the final products.
2. It uses a left-to-right approach to compute the running product of all elements to the left of each index.
3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side.
4. It iterates over the input array from left to right using a `for` loop.
5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the
`leftRunningProduct` by multiplying it with the corresponding element in the input array.
6. After the loop, the result array will contain the product of all elements to the left of each index.
7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and
multiply it with the corresponding left product in the result array.
8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side.
9. It iterates over the input array from right to left using a `for` loop.
10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array
and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array.
11. After the loop, the result array will contain the product of all elements to the left and right of each index,
except for the element at that index.
12. Finally, it returns the result array.
This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products.
'''
def array_of_products(array):
n = len(array)
result = [1] * n
# Compute the running product of all elements to the left of each index
# and store it in the result array.
left_running_product = 1
for i in range(n):
result[i] = left_running_product # Store left product in the result array
left_running_product *= array[i] # Update left product
# Compute the running product of all elements to the right of each index
# and multiply it with the corresponding left product in the result array.
right_running_product = 1
for i in range(n - 1, -1, -1):
result[i] *= right_running_product # Multiply the right product with the corresponding left product
right_running_product *= array[i] # Update right product
return result
# Example usage
input_array = [1, 2, 3, 4, 5]
output_array = array_of_products(input_array)
# Print the result
print(output_array)
================================================
FILE: Arrays/ceaser_cipher.cpp
================================================
/*
Given a non-empty string of lowercase letters and a non-negative integer
representing a key, write a function that returns a new string obtained by
shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet; in other words, the
letter z shifted by one returns the letter a
Sample Input : abz key: 3
Output: dec
Explanation:
The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string
obtained by shifting each character of the input string by the key number of positions to the right in
the alphabet, wrapping around if necessary.
The function first calculates the shift amount and offset value. The shift amount is calculated by taking
the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset
value is calculated by taking 26, which is the number of letters in the alphabet.
The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single
character in a programming language. The rune type is used to represent characters in Go.
The function then iterates over each character in the rune slice. For each character, the function checks
if the character is a lowercase letter and if shifting it will still be within the lowercase range.
If the character is a lowercase letter and shifting it will still be within the lowercase range, the
function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character.
The function then updates the character in the rune slice.
The function then converts the resulting rune slice back to a string and returns it.
The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function iterates over each character in the input string, performing a constant amount
of work for each character.
The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function creates a new rune slice to store the encrypted string. The rune slice is the
same size as the input string, so the space complexity is O(n).
*/
// C++
#include <iostream>
#include <string>
using namespace std;
string CaesarCipherEncryptor(string str, int key) {
// Calculate the shift amount and offset value
int shift = key % 26;
int offset = 26;
// Convert the input string to a vector of characters
vector<char> chars(str.begin(), str.end());
// Iterate over each character in the vector
for (int i = 0; i < chars.size(); i++) {
// If the character is a lowercase letter and shifting it will still be within the lowercase range
if (chars[i] >= 'a' && chars[i] + shift <= 'z') {
chars[i] += shift;
} else {
// If the character is outside of the lowercase range after shifting, wrap it around
chars[i] += shift - offset;
}
}
// Convert the resulting vector of characters back to a string and return it
return string(chars.begin(), chars.end());
}
int main() {
// Get the input string and key from the user
string str;
cout << "Enter a string: ";
cin >> str;
int key;
cout << "Enter a key: ";
cin >> key;
// Encrypt the string using the Caesar cipher
string encrypted_str = CaesarCipherEncryptor(str, key);
// Print the encrypted string
cout << "Encrypted string: " << encrypted_str << endl;
return 0;
}
================================================
FILE: Arrays/ceaser_cipher.go
================================================
/*
Given a non-empty string of lowercase letters and a non-negative integer
representing a key, write a function that returns a new string obtained by
shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet; in other words, the
letter z shifted by one returns the letter a
Sample Input : abz key: 3
Output: dec
Explanation:
The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string
obtained by shifting each character of the input string by the key number of positions to the right in
the alphabet, wrapping around if necessary.
The function first calculates the shift amount and offset value. The shift amount is calculated by taking
the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset
value is calculated by taking 26, which is the number of letters in the alphabet.
The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single
character in a programming language. The rune type is used to represent characters in Go.
The function then iterates over each character in the rune slice. For each character, the function checks
if the character is a lowercase letter and if shifting it will still be within the lowercase range.
If the character is a lowercase letter and shifting it will still be within the lowercase range, the
function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character.
The function then updates the character in the rune slice.
The function then converts the resulting rune slice back to a string and returns it.
The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function iterates over each character in the input string, performing a constant amount
of work for each character.
The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function creates a new rune slice to store the encrypted string. The rune slice is the
same size as the input string, so the space complexity is O(n).
*/
package main
// CaesarCipherEncryptor takes a string and a key (integer) as input and returns
// a new string obtained by shifting each character of the input string by the
// key number of positions to the right in the alphabet, wrapping around if necessary.
func CaesarCipherEncryptor(str string, key int) string {
// Calculate the shift amount and offset value
shift, offset := rune(key % 26), rune(26)
// Convert the input string to a rune slice (for ease of manipulation)
runes := []rune(str)
// Iterate over each character in the rune slice
for i, char := range runes {
// If the character is a lowercase letter and shifting it will still be within the lowercase range
if char >= 'a' && char + shift <= 'z' {
char += shift
} else {
// If the character is outside of the lowercase range after shifting, wrap it around
char += shift - offset
}
// Update the character in the rune slice
runes[i] = char
}
// Convert the resulting rune slice back to a string and return it
return string(runes)
}
================================================
FILE: Arrays/ceaser_cipher.java
================================================
/*
Given a non-empty string of lowercase letters and a non-negative integer
representing a key, write a function that returns a new string obtained by
shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet; in other words, the
letter z shifted by one returns the letter a
Sample Input : abz key: 3
Output: dec
Explanation:
The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string
obtained by shifting each character of the input string by the key number of positions to the right in
the alphabet, wrapping around if necessary.
The function first calculates the shift amount and offset value. The shift amount is calculated by taking
the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset
value is calculated by taking 26, which is the number of letters in the alphabet.
The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single
character in a programming language. The rune type is used to represent characters in Go.
The function then iterates over each character in the rune slice. For each character, the function checks
if the character is a lowercase letter and if shifting it will still be within the lowercase range.
If the character is a lowercase letter and shifting it will still be within the lowercase range, the
function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character.
The function then updates the character in the rune slice.
The function then converts the resulting rune slice back to a string and returns it.
The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function iterates over each character in the input string, performing a constant amount
of work for each character.
The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function creates a new rune slice to store the encrypted string. The rune slice is the
same size as the input string, so the space complexity is O(n).
*/
// Java
import java.util.Scanner;
public class CaesarCipherEncryptor {
public static String encrypt(String str, int key) {
// Calculate the shift amount and offset value
int shift = key % 26;
int offset = 26;
// Convert the input string to a char array
char[] chars = str.toCharArray();
// Iterate over each character in the char array
for (int i = 0; i < chars.length; i++) {
// If the character is a lowercase letter and shifting it will still be within the lowercase range
if (chars[i] >= 'a' && chars[i] + shift <= 'z') {
chars[i] += shift;
} else {
// If the character is outside of the lowercase range after shifting, wrap it around
chars[i] += shift - offset;
}
}
// Convert the resulting char array back to a string and return it
return new String(chars);
}
public static void main(String[] args) {
// Get the input string and key from the user
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = scanner.nextLine();
System.out.println("Enter a key: ");
int key = scanner.nextInt();
// Encrypt the string using the Caesar cipher
String encrypted_str = encrypt(str, key);
// Print the encrypted string
System.out.println("Encrypted string: " + encrypted_str);
}
}
================================================
FILE: Arrays/ceaser_cipher.js
================================================
/*
Given a non-empty string of lowercase letters and a non-negative integer
representing a key, write a function that returns a new string obtained by
shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet; in other words, the
letter z shifted by one returns the letter a
Sample Input : abz key: 3
Output: dec
Explanation:
The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string
obtained by shifting each character of the input string by the key number of positions to the right in
the alphabet, wrapping around if necessary.
The function first calculates the shift amount and offset value. The shift amount is calculated by taking
the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset
value is calculated by taking 26, which is the number of letters in the alphabet.
The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single
character in a programming language. The rune type is used to represent characters in Go.
The function then iterates over each character in the rune slice. For each character, the function checks
if the character is a lowercase letter and if shifting it will still be within the lowercase range.
If the character is a lowercase letter and shifting it will still be within the lowercase range, the
function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character.
The function then updates the character in the rune slice.
The function then converts the resulting rune slice back to a string and returns it.
The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function iterates over each character in the input string, performing a constant amount
of work for each character.
The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function creates a new rune slice to store the encrypted string. The rune slice is the
same size as the input string, so the space complexity is O(n).
*/
function caesarCipherEncryptor(str, key) {
// Calculate the shift amount and offset value
let shift = key % 26;
let offset = 26;
// Convert the input string to a lowercase string
str = str.toLowerCase();
// Iterate over each character in the string
for (let i = 0; i < str.length; i++) {
// If the character is a letter and shifting it will still be within the lowercase range
if (str[i] >= "a" && str[i] + shift <= "z") {
str[i] += shift;
} else {
// If the character is outside of the lowercase range after shifting, wrap it around
str[i] += shift - offset;
}
}
// Return the encrypted string
return str;
}
// Example usage
let str = "Hello, world!";
let key = 3;
let encryptedStr = caesarCipherEncryptor(str, key);
console.log(encryptedStr); // Output: "Khoor, zloor!"
================================================
FILE: Arrays/ceaser_cipher.py
================================================
'''
Given a non-empty string of lowercase letters and a non-negative integer
representing a key, write a function that returns a new string obtained by
shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet; in other words, the
letter z shifted by one returns the letter a
Sample Input : abz key: 3
Output: dec
Explanation:
The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string
obtained by shifting each character of the input string by the key number of positions to the right in
the alphabet, wrapping around if necessary.
The function first calculates the shift amount and offset value. The shift amount is calculated by taking
the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset
value is calculated by taking 26, which is the number of letters in the alphabet.
The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single
character in a programming language. The rune type is used to represent characters in Go.
The function then iterates over each character in the rune slice. For each character, the function checks
if the character is a lowercase letter and if shifting it will still be within the lowercase range.
If the character is a lowercase letter and shifting it will still be within the lowercase range, the
function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character.
The function then updates the character in the rune slice.
The function then converts the resulting rune slice back to a string and returns it.
The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function iterates over each character in the input string, performing a constant amount
of work for each character.
The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string.
This is because the function creates a new rune slice to store the encrypted string. The rune slice is the
same size as the input string, so the space complexity is O(n).
'''
# Python
def caesar_cipher_encryptor(str, key):
# Calculate the shift amount and offset value
shift = key % 26
offset = 26
# Convert the input string to a list of characters
chars = list(str)
# Iterate over each character in the list
for i in range(len(chars)):
# If the character is a lowercase letter and shifting it will still be within the lowercase range
if chars[i] >= 'a' and chars[i] + shift <= 'z':
chars[i] += shift
else:
# If the character is outside of the lowercase range after shifting, wrap it around
chars[i] += shift - offset
# Convert the resulting list of characters back to a string and return it
return ''.join(chars)
================================================
FILE: Arrays/dutch_national_flag.cpp
================================================
/*
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation:
The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements
with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections.
The algorithm iterates through the array using the `low` pointer. Here's how it works:
1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element
with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the
next element to process.
2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments
the `low` pointer and moves to the next element to process.
3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element
with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1.
The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have
been processed.
The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array.
It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections.
Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place
to achieve the sorted order.
Time complexity: O(n)
Space complexity: O(1)
*/
#include <bits/stdc++.h>
using namespace std;
void sortColors(vector<int> &nums)
{
// created 3 variables start , low and end which are pointing start and low which are pointing to first index , end is pointing to last index .
int start = 0, low = 0, end = nums.size() - 1;
while (low <= end)
{
if (nums[low] == 0) // checking if element of low is 0 . If yes then swap to start and low .
{
swap(nums[low], nums[start]);
start++, low++;
}
else if (nums[low] == 1) // checking if element at low index is 1 , If yes then increase the index by 1 .
{
low++;
}
else // else swap the element of low index to end .
{
swap(nums[low], nums[end]);
end--;
}
}
}
int main()
{
vector<int> nums{2, 0, 2, 1, 1, 0};
sortColors(nums);
// Printing array's elements ..
for (auto i : nums)
{
cout << i << " ";
}
}
================================================
FILE: Arrays/dutch_national_flag.go
================================================
/*
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation:
The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements
with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections.
The algorithm iterates through the array using the `low` pointer. Here's how it works:
1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element
with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the
next element to process.
2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments
the `low` pointer and moves to the next element to process.
3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element
with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1.
The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have
been processed.
The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array.
It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections.
Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place
to achieve the sorted order.
Time complexity: O(n)
Space complexity: O(1)
*/
package main
import "fmt"
func sortColors(nums []int) {
start := 0
low := 0
end := len(nums) - 1
for low <= end {
if nums[low] == 0 {
// Swap the element at low with the element at start
nums[low], nums[start] = nums[start], nums[low]
start++
low++
} else if nums[low] == 1 {
// Move to the next element
low++
} else {
// Swap the element at low with the element at end
nums[low], nums[end] = nums[end], nums[low]
end--
}
}
}
func main() {
nums := []int{2, 0, 2, 1, 1, 0}
sortColors(nums)
fmt.Println(nums)
}
================================================
FILE: Arrays/dutch_national_flag.java
================================================
/*
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation:
The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements
with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections.
The algorithm iterates through the array using the `low` pointer. Here's how it works:
1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element
with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the
next element to process.
2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments
the `low` pointer and moves to the next element to process.
3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element
with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1.
The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have
been processed.
The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array.
It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections.
Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place
to achieve the sorted order.
Time complexity: O(n)
Space complexity: O(1)
*/
public class Main {
public static void sortColors(int[] nums) {
int start = 0;
int low = 0;
int end = nums.length - 1;
while (low <= end) {
if (nums[low] == 0) {
// Swap the element at low with the element at start
int temp = nums[low];
nums[low] = nums[start];
nums[start] = temp;
start++;
low++;
} else if (nums[low] == 1) {
// Move to the next element
low++;
} else {
// Swap the element at low with the element at end
int temp = nums[low];
nums[low] = nums[end];
nums[end] = temp;
end--;
}
}
}
public static void main(String[] args) {
int[] nums = {2, 0, 2, 1, 1, 0};
sortColors(nums);
for (int num : nums) {
System.out.print(num + " ");
}
}
}
================================================
FILE: Arrays/dutch_national_flag.js
================================================
/*
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation:
The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements
with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections.
The algorithm iterates through the array using the `low` pointer. Here's how it works:
1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element
with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the
next element to process.
2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments
the `low` pointer and moves to the next element to process.
3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element
with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1.
The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have
been processed.
The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array.
It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections.
Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place
to achieve the sorted order.
Time complexity: O(n)
Space complexity: O(1)
*/
function sortColors(nums) {
let start = 0;
let low = 0;
let end = nums.length - 1;
while (low <= end) {
if (nums[low] === 0) {
// Swap the element at low with the element at start
[nums[low], nums[start]] = [nums[start], nums[low]];
start++;
low++;
} else if (nums[low] === 1) {
// Move to the next element
low++;
} else {
// Swap the element at low with the element at end
[nums[low], nums[end]] = [nums[end], nums[low]];
end--;
}
}
}
// Example usage:
const nums = [2, 0, 2, 1, 1, 0];
sortColors(nums);
console.log(nums);
================================================
FILE: Arrays/dutch_national_flag.py
================================================
'''
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation:
The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements
with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections.
The algorithm iterates through the array using the `low` pointer. Here's how it works:
1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element
with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the
next element to process.
2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments
the `low` pointer and moves to the next element to process.
3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element
with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1.
The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have
been processed.
The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array.
It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections.
Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place
to achieve the sorted order.
Time complexity: O(n)
Space complexity: O(1)
'''
def sortColors(nums):
start = 0
low = 0
end = len(nums) - 1
while low <= end:
if nums[low] == 0:
# Swap the element at low with the element at start
nums[low], nums[start] = nums[start], nums[low]
start += 1
low += 1
elif nums[low] == 1:
# Move to the next element
low += 1
else:
# Swap the element at low with the element at end
nums[low], nums[end] = nums[end], nums[low]
end -= 1
# Example usage:
nums = [2, 0, 2, 1, 1, 0]
sortColors(nums)
print(nums)
================================================
FILE: Arrays/find_three_largest_integers.js
================================================
/*
Write a function that takes in an array of at least three integers and,
without sorting the input array, returns a sorted array of the three largest
integers in the input array.
Explanation:
This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and
returns an array of the three largest integers in the input array.
The `triplets` array is initialized with three smallest possible values. Then, the function iterates through
the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with
the current number if it is larger than one of the values in the array.
The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater
than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the
`triplets` array with the current number at the third index.
If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the second index. Finally, if `num` is not greater than either the third or second value in the `triplets`
array, it checks if `num` is greater than the first value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the first index.
The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the
`triplets` array using a `for` loop and shifts each value to the left by one position until it reaches
the `idx` index. Then it updates the value at the `idx` index with the current number `num`.
Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array
*/
function findThreeLargestNumbers(array) {
// Initialize an array to hold the three largest numbers, starting with negative infinity
let triplets = [-Infinity, -Infinity, -Infinity];
// Iterate through each number in the input array
for (let num of array) {
// Call the updateLargest function to determine if the number should be included in the triplet
updateLargest(triplets, num);
}
// Return the array containing the three largest numbers
return triplets;
}
function updateLargest(triplets, num) {
// If the number is larger than the third-largest element in the triplet
if (num > triplets[2]) {
// Shift the other elements to make room and add the number as the new third-largest element
shiftAndUpdate(triplets, num, 2);
}
// Otherwise, if the number is larger than the second-largest element
else if (num > triplets[1]) {
// Shift and update the triplet accordingly
shiftAndUpdate(triplets, num, 1);
}
// Otherwise, if the number is larger than the first-largest element
else if (num > triplets[0]) {
// Shift and update the triplet accordingly
shiftAndUpdate(triplets, num, 0);
}
}
function shiftAndUpdate(triplets, num, idx) {
// Iterate through the elements of the triplet
for (let i = 0; i <= idx; i++) {
// If the loop reaches the specified index, add the new number to the triplet
if (i === idx) {
triplets[i] = num;
}
// Otherwise, shift the elements to the right
else {
triplets[i] = triplets[i + 1];
}
}
}
// Test the findThreeLargestNumbers function
const array = [1, 5, 2, 9, 10, 3];
const result = findThreeLargestNumbers(array);
console.log(result);
================================================
FILE: Arrays/find_three_largest_number.cpp
================================================
/*
Write a function that takes in an array of at least three integers and,
without sorting the input array, returns a sorted array of the three largest
integers in the input array.
*/
/* Explanation
This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and
returns an array of the three largest integers in the input array.
The `triplets` array is initialized with three smallest possible values. Then, the function iterates through
the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with
the current number if it is larger than one of the values in the array.
The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater
than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the
`triplets` array with the current number at the third index.
If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the second index. Finally, if `num` is not greater than either the third or second value in the `triplets`
array, it checks if `num` is greater than the first value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the first index.
The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the
`triplets` array using a `for` loop and shifts each value to the left by one position until it reaches
the `idx` index. Then it updates the value at the `idx` index with the current number `num`.
Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
// Function to update the triplet if the input number is larger than any of its elements.
void updateLargest(vector<int>& triplets, int num);
// Function to shift the elements of the triplet to make room for a new number and add the number to the specified index.
void shiftAndUpdate(vector<int>& triplets, int num, int idx);
// Function to find the three largest integers in the input array in descending order.
vector<int> findThreeLargestNumbers(vector<int>& array);
int main() {
// Create an input array.
vector<int> array = {141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7};
// Find the three largest integers in the input array.
vector<int> result = findThreeLargestNumbers(array);
// Output the three largest integers in descending order.
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
vector<int> findThreeLargestNumbers(vector<int>& array) {
// Initialize a vector to hold the three largest integers, starting with negative infinity.
vector<int> triplets = {INT_MIN, INT_MIN, INT_MIN};
// Iterate over each number in the input array and call the updateLargest function to determine if it should be included in the triplet.
for (int num : array) {
updateLargest(triplets, num);
}
// Return the vector containing the three largest integers in descending order.
return triplets;
}
void updateLargest(vector<int>& triplets, int num) {
// If the number is larger than the third-largest element in the triplet, shift the other elements to make room and add the number.
if (num > triplets[2]) {
shiftAndUpdate(triplets, num, 2);
// Otherwise, if the number is larger than the second-largest element, shift and update the triplet accordingly.
} else if (num > triplets[1]) {
shiftAndUpdate(triplets, num, 1);
// Otherwise, if the number is larger than the first-largest element, shift and update the triplet accordingly.
} else if (num > triplets[0]) {
shiftAndUpdate(triplets, num, 0);
}
}
void shiftAndUpdate(vector<int>& triplets, int num, int idx) {
// Shift the elements of the triplet to the right starting at the specified index, and add the new number to the specified index.
for (int i = 0; i < idx + 1; i++) {
// If the loop reaches the specified index, add the new number to the triplet.
if (i == idx) {
triplets[i] = num;
// Otherwise, shift the elements to the right.
} else {
triplets[i] = triplets[i + 1];
}
}
}
================================================
FILE: Arrays/find_three_largest_numbers.go
================================================
/*
Write a function that takes in an array of at least three integers and,
without sorting the input array, returns a sorted array of the three largest
integers in the input array.
Explanation:
This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and
returns an array of the three largest integers in the input array.
The `triplets` array is initialized with three smallest possible values. Then, the function iterates through
the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with
the current number if it is larger than one of the values in the array.
The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater
than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the
`triplets` array with the current number at the third index.
If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the second index. Finally, if `num` is not greater than either the third or second value in the `triplets`
array, it checks if `num` is greater than the first value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the first index.
The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the
`triplets` array using a `for` loop and shifts each value to the left by one position until it reaches
the `idx` index. Then it updates the value at the `idx` index with the current number `num`.
Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array
*/
package main
import "math"
// FindThreeLargestNumbers returns the three largest integers in the input array in descending order.
func FindThreeLargestNumbers(array []int) []int {
// Initialize a slice to hold the three largest integers, starting with negative infinity.
triplets := []int{math.MinInt32, math.MinInt32, math.MinInt32}
for _, num := range array {
// For each number in the array, call the updateLargest function to determine if it should be included in the triplet.
updateLargest(triplets, num)
}
return triplets
}
// updateLargest updates the triplet if the input number is larger than any of its elements.
func updateLargest(triplets []int, num int) {
// If the number is larger than the third-largest element in the triplet, shift the other elements to make room and add the number.
if num > triplets[2] {
shiftAndUpdate(triplets, num, 2)
// Otherwise, if the number is larger than the second-largest element, shift and update the triplet accordingly.
} else if num > triplets[1] {
shiftAndUpdate(triplets, num, 1)
// Otherwise, if the number is larger than the first-largest element, shift and update the triplet accordingly.
} else if num > triplets[0] {
shiftAndUpdate(triplets, num, 0)
}
}
// shiftAndUpdate shifts the elements of the triplet to make room for a new number and adds the number to the specified index.
func shiftAndUpdate(triplets []int, num int, idx int) {
for i := 0; i < idx+1; i++ {
// If the loop reaches the specified index, add the new number to the triplet.
if i == idx {
triplets[i] = num
// Otherwise, shift the elements to the right.
} else {
triplets[i] = triplets[i+1]
}
}
}
================================================
FILE: Arrays/find_three_largest_numbers.java
================================================
/*
Write a function that takes in an array of at least three integers and,
without sorting the input array, returns a sorted array of the three largest
integers in the input array.
Explanation:
This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and
returns an array of the three largest integers in the input array.
The `triplets` array is initialized with three smallest possible values. Then, the function iterates through
the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with
the current number if it is larger than one of the values in the array.
The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater
than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the
`triplets` array with the current number at the third index.
If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the second index. Finally, if `num` is not greater than either the third or second value in the `triplets`
array, it checks if `num` is greater than the first value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the first index.
The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the
`triplets` array using a `for` loop and shifts each value to the left by one position until it reaches
the `idx` index. Then it updates the value at the `idx` index with the current number `num`.
Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array
*/
import java.util.Arrays;
public class Main {
// Function to find the three largest numbers in the input array
public static int[] findThreeLargestNumbers(int[] array) {
// Initialize an array to hold the three largest numbers, starting with negative infinity
int[] triplets = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
// Iterate through each number in the input array
for (int num : array) {
// Call the updateLargest function to determine if the number should be included in the triplet
updateLargest(triplets, num);
}
// Return the array containing the three largest numbers
return triplets;
}
// Function to update the triplet if the input number is larger than any of its elements
private static void updateLargest(int[] triplets, int num) {
// If the number is larger than the third-largest element in the triplet
if (num > triplets[2]) {
// Shift the other elements to make room and add the number as the new third-largest element
shiftAndUpdate(triplets, num, 2);
}
// Otherwise, if the number is larger than the second-largest element
else if (num > triplets[1]) {
// Shift and update the triplet accordingly
shiftAndUpdate(triplets, num, 1);
}
// Otherwise, if the number is larger than the first-largest element
else if (num > triplets[0]) {
// Shift and update the triplet accordingly
shiftAndUpdate(triplets, num, 0);
}
}
// Function to shift the elements of the triplet and add the new number to the specified index
private static void shiftAndUpdate(int[] triplets, int num, int idx) {
// Iterate through the elements of the triplet
for (int i = 0; i < idx + 1; i++) {
// If the loop reaches the specified index, add the new number to the triplet
if (i == idx) {
triplets[i] = num;
}
// Otherwise, shift the elements to the right
else {
triplets[i] = triplets[i + 1];
}
}
}
// Main function to test the findThreeLargestNumbers function
public static void main(String[] args) {
int[] array = {1, 5, 2, 9, 10, 3};
int[] result = findThreeLargestNumbers(array);
System.out.println(Arrays.toString(result));
}
}
================================================
FILE: Arrays/find_three_largest_numbers.py
================================================
'''
Write a function that takes in an array of at least three integers and,
without sorting the input array, returns a sorted array of the three largest
integers in the input array.
Explanation:
This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and
returns an array of the three largest integers in the input array.
The `triplets` array is initialized with three smallest possible values. Then, the function iterates through
the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with
the current number if it is larger than one of the values in the array.
The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater
than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the
`triplets` array with the current number at the third index.
If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the second index. Finally, if `num` is not greater than either the third or second value in the `triplets`
array, it checks if `num` is greater than the first value in the `triplets` array.
If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at
the first index.
The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the
`triplets` array using a `for` loop and shifts each value to the left by one position until it reaches
the `idx` index. Then it updates the value at the `idx` index with the current number `num`.
Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array
'''
def find_three_largest_numbers(array):
# Initialize a list to hold the three largest numbers, starting with negative infinity
triplets = [float('-inf'), float('-inf'), float('-inf')]
# Iterate through each number in the input array
for num in array:
# Call the update_largest function to determine if the number should be included in the triplet
update_largest(triplets, num)
# Return the list containing the three largest numbers
return triplets
def update_largest(triplets, num):
# If the number is larger than the third-largest element in the triplet
if num > triplets[2]:
# Shift the other elements to make room and add the number as the new third-largest element
shift_and_update(triplets, num, 2)
# Otherwise, if the number is larger than the second-largest element
elif num > triplets[1]:
# Shift and update the triplet accordingly
shift_and_update(triplets, num, 1)
# Otherwise, if the number is larger than the first-largest element
elif num > triplets[0]:
# Shift and update the triplet accordingly
shift_and_update(triplets, num, 0)
def shift_and_update(triplets, num, idx):
# Iterate through the elements of the triplet
for i in range(idx + 1):
# If the loop reaches the specified index, add the new number to the triplet
if i == idx:
triplets[i] = num
# Otherwise, shift the elements to the right
else:
triplets[i] = triplets[i + 1]
# Test the find_three_largest_numbers function
array = [1, 5, 2, 9, 10, 3]
result = find_three_largest_numbers(array)
print(result)
================================================
FILE: Arrays/first_duplicate_value.cpp
================================================
/*
Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function
that returns the first integer that appears more than once (when the array is read from left to right).
Sample Input = [2, 1, 5, 2, 3, 3, 4]
Output : 2
Please provide O(n) time and O(1) space solution along with O(n) time and O(n) space solution
*/
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
// O(N) time complexity and O(N) Space Complexity Solution
int findDuplicate1(vector<int>& nums)
{
int N=nums.size();
// Use Vector Instead of Unordered Set or Map for O(1) extraction time complexity
vector<bool> trk(N,false);
for(int i=0;i<N;i++)
{
if(trk[nums[i]]==true) return nums[i];
trk[nums[i]]=true;
}
return -1;
}
// O(N) time complexity and O(1) Space Complexity Solution
int findDuplicate2(vector<int>& nums)
{
int N=nums.size();
for(int i=0;i<N;i++)
{
if(nums[abs(nums[i])]<0) return nums[i];
nums[abs(nums[i])]*=-1;
}
return -1;
}
};
================================================
FILE: Arrays/first_duplicate_value.go
================================================
/*
Given an array of integers between 1 and n, inclusive where n is the length of the array, write a function
that returns the first integer that appears more than once (when the array isread from left to right).
Sample Input: [2, 3, 1, 4, 2, 5, 3]
Output: 2
*/
package main
import "fmt"
/*
Approach 1:
1. We define the `FirstDuplicateValue` function that takes an array of integers as input and returns the
first duplicate value found in the array.
2. Inside the function, we create a map named `seenSoFar` using the `make` function. This map will be
used to keep track of the numbers that have been seen so far in the array.
3. We iterate over each number in the `array` using the `range` keyword.
4. For each number, we check if it exists as a key in the `seenSoFar` map. If the value exists, it means
the number has been seen before and is a duplicate.
5. If a duplicate value is found, we immediately return the duplicate value as the result.
6. If the number is not a duplicate, we add it to the `seenSoFar` map by setting the corresponding key to
`true`, indicating that it has been seen.
7. After iterating through all the numbers in the array without finding a duplicate, we return -1 to
indicate that no duplicate value was found.
In the `main` function, we demonstrate the usage of the `FirstDuplicateValue` function by creating an
example array with some duplicate values. We call the function and store the result in the `firstDuplicate`
variable. Finally, we print the `firstDuplicate` value, which gives us the first duplicate value in the array.
In this case, the output will be "2" since it is the first duplicate value encountered in the array
`[2, 3, 1, 4, 2, 5, 3]`.
*/
func FirstDuplicateValue(array []int) int {
// Create a map to store the numbers that have been seen so far.
seenSoFar := make(map[int]bool)
// Iterate over each number in the array.
for _, num := range array {
// Check if the current number has been seen before.
if _, valueExists := seenSoFar[num]; valueExists {
// If the number is already in the map, it is the first duplicate value.
return num
}
// Add the current number to the map to mark it as seen.
seenSoFar[num] = true
}
// If no duplicate value is found, return -1.
return -1
}
/*
Approach2:
The code defines a function FirstDuplicateValue that takes an integer array array as its input and returns the
first integer value that appears more than once in the input array. The function implements this using a
technique called "negation of visited elements".
The function first loops through each element in the input array array. For each element, it computes the
absolute value using the abs function, which is defined as a separate helper function. The absolute value
is used to get the index of the element in the array (adjusted by -1 to account for 0-based indexing).
If the element at the computed index in the array is already negative, it means that we have seen this
element before and hence it is a duplicate. In this case, we return the absolute value of the element.
If the element is not negative, we negate it to mark it as visited. This is done by multiplying the
element at the computed index in the array by -1.
If there are no duplicate values in the input array, the function returns -1.
Overall, this approach uses constant extra space and has a time complexity of O(n), where n is the
length of the input array.
*/
// Function to find the first duplicate value in an array.
func FirstDuplicateValue2(array []int) int {
// Iterate over each element in the array.
for _, num := range array {
// Get the absolute value of the current element.
absValue := abs(num)
// Check if the value at the index (absValue - 1) in the array is negative.
if array[absValue - 1] < 0 {
// If it is negative, then the current element is the first duplicate value.
return absValue
}
// Otherwise, mark the value at the index (absValue - 1) in the array as negative.
array[absValue - 1] *= -1
}
// If no duplicates are found, return -1.
return -1
}
// Function to get the absolute value of a number.
func abs(num int) int {
if num < 0 {
return -num
}
return num
}
func main() {
// Example usage of FirstDuplicateValue function
array := []int{2, 3, 1, 4, 2, 5, 3}
firstDuplicate := FirstDuplicateValue(array)
fmt.Println("First Duplicate Value:", firstDuplicate)
firstDuplicate = FirstDuplicateValue2(array)
fmt.Println("First Duplicate Value:", firstDuplicate)
}
================================================
FILE: Arrays/first_duplicate_value.java
================================================
/* Sure, here's a brief explanation of each solution:
Solution 1 (O(n) time, O(1) space):
This solution uses Floyd's Tortoise and Hare algorithm to find the first duplicate value in the array.
It initializes two pointers, a slow pointer and a fast pointer, to the first value in the array.
The slow pointer moves one step at a time, while the fast pointer moves two steps at a time.
When they meet at a certain point, it indicates that there is a cycle in the array.
Then, the slow pointer is reset to the first value, and both pointers move one step at a time until they meet again,
which is the start of the cycle (i.e., the first duplicate value in the array).
Solution 2 (O(n) time, O(n) space):
This solution uses a HashSet to keep track of the integers that have been seen so far in the array.
As the array is iterated over, each integer is checked to see if it is already in the set.
If it is, then it is returned as the first integer that appears more than once.
If no such integer is found, then -1 is returned. This solution has a time complexity of O(n) and a space complexity of O(n). */
// Solution 1: O(n) time and O(1) space
public static int findDuplicate(int[] nums) {
// iterate through the array
for (int i = 0; i < nums.length; i++) {
// calculate the absolute value of the current element
int val = Math.abs(nums[i]);
// check if the value at the calculated index is negative
if (nums[val - 1] < 0) {
// if it is, return the absolute value of the current element
return val;
}
// otherwise, negate the value at the calculated index
nums[val - 1] = -nums[val - 1];
}
// if no duplicate is found, return -1
return -1;
}
// Solution 2: O(n) time and O(n) space solution:
public static int findDuplicate(int[] nums) {
// create a set to keep track of visited elements
Set<Integer> visited = new HashSet<>();
// iterate through the array
for (int num : nums) {
// check if the current element has already been visited
if (visited.contains(num)) {
// if it has, return the current element
return num;
}
// otherwise, add it to the set of visited elements
visited.add(num);
}
// if no duplicate is found, return -1
return -1;
}
================================================
FILE: Arrays/first_duplicate_value.js
================================================
/*
Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function
that returns the first integer that appears more than once (when the array is read from left to right).
Sample Input = [2, 1, 5, 2, 3, 3, 4]
Output : 2
*/
// O(n) time and O(1) space solution.
// Approach: The approach utilizes the fact that the array contains integers between 1 and n,
// where n is the length of the array. By negating the values at specific indices,
// we can track which numbers have appeared before. If a number has appeared before,
// its corresponding index will have a negative value.
// This allows us to identify the first duplicate encountered during the iteration.
function findFirstDuplicate(nums){
let n=nums.length;
for(let i=0;i<n;i++){
// Check if the absolute value at the current number's index is negative
if(nums[Math.abs(nums[i])]<0){
// If it is negative, the number has appeared before and is a duplicate
return nums[i];
}
else{
// Mark the number at its index as visited by negating its value
nums[nums[i]]*=-1;
}
}
// No duplicates found
return -1;
}
// O(n) time and O(n) space solution.
// Approach: Using Set object or map to check if a number appears more than ones.
function findFirstDuplicate(nums){
let set=new Set();
for(let i=0;i<nums.length;i++){
if(set.has(nums[i])==false){
// If a number does not exists in set add it to set;
set.add(nums[i]);
}
else{
// Number already exits in set. So return the duplicate number.
return nums[i];
}
}
// If no duplicate element found.
return -1;
}
================================================
FILE: Arrays/first_duplicate_value.py
================================================
'''
In the code I implemented a solution using Floyd's Tortoise and Hare algorithm
for finding the first integer that appears more than once in an array of integers.
The first solution has a time complexity of O(n) and a space complexity of O(1).
It uses the fact that the integers in the array are between 1 and n, inclusive, where n is the length of the array.
The solution works by using the array itself as a hash table,
by marking an integer as negative if it is encountered for the first time,
and returning it if it is already marked negative.
'''
def find_duplicate(nums):
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
================================================
FILE: Arrays/four_sum.py
================================================
'''
author:maneesha
Input:
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
Time Complexity:O(n^3)
Space Complexity:O(1)
Explanation:
>>The fourSum function takes in a list of integers (nums) and a target value (target).
>>The code sorts the nums list in ascending order.
>>It initializes an empty list res to store the resulting quadruplets.
>>Code uses two nested loops to iterate over combinations of four numbers from the nums list.
>>It avoids duplicates by skipping iterations when the current element is the same as the previous element
in both the outer and inner loops.
>>Inside nested loops, code uses two pointers (lo and hi) to find pairs of elements that sum up to the remaining target value.
>>It compares the sum of the four elements with the target value and takes appropriate actions:
. If sum equals the target, it adds the quadruplet to the result list res and skips any duplicate elements by moving the pointers accordingly.
. If sum is less than the target, it increments the lo pointer to try larger values.
. If sum is greater than the target, it decrements the hi pointer to try smaller values.
>>After the nested loops, the function returns the resulting list of quadruplets res.
'''
from typing import List
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
nums.sort()
res = []
for i in range(n-3):
# avoid the duplicates while moving i
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i+1, n-2):
# avoid the duplicates while moving j
if j > i + 1 and nums[j] == nums[j - 1]:
continue
lo = j + 1
hi = n - 1
while lo < hi:
temp = nums[i] + nums[j] + nums[lo] + nums[hi]
if temp == target:
res += [nums[i], nums[j], nums[lo], nums[hi]],
# skip duplicates
while lo < hi and nums[lo] == nums[lo + 1]:
lo += 1
lo += 1
while lo < hi and nums[hi] == nums[hi - 1]:
hi -= 1
hi -= 1
elif temp < target:
lo += 1
else:
hi -= 1
return res
# Test case
nums = [1, 0, -1, 0, -2, 2]
target = 0
solution = Solution()
result = solution.fourSum(nums, target)
print(result)
================================================
FILE: Arrays/insert_interval.cpp
================================================
/*
Insert Interval
In this implementation, the `Interval` struct represents an interval with a start and end value.
The `insert` function takes a sorted list of intervals and a new interval as input and returns a new
list of intervals after merging the new interval with the existing intervals.
Here's how the `insert` function works:
1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0.
2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the
`result` slice.
3. It merges intervals that overlap with the new interval by updating the start and end values of the new
interval accordingly.
4. It adds the merged new interval to the `result` slice.
5. It adds any remaining intervals from the original list to the `result` slice.
6. Finally, it returns the `result` slice containing the merged intervals.
The `min` and `max` functions are helper functions to find the minimum and maximum of two integers.
In the `main` function, an example input is provided with a list of intervals and a new interval.
The `insert` function is called with these inputs, and the result is printed to the console.
Time Complexity:
The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to
iterate through each interval in the list to merge and insert the new interval. In the worst case, we may
need to traverse all intervals in the list.
Space Complexity:
The space complexity is O(n), where n is the number of intervals in the input list. This is because we
create a new result slice to store the merged intervals, which can potentially contain all the intervals
from the input list plus the merged new interval. Therefore, the space required is proportional to the
number of intervals in the input list.
Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number
of intervals in the input list.
*/
#include <iostream>
#include <vector>
using namespace std;
// Interval represents a closed interval [start, end].
struct Interval {
int start;
int end;
Interval(int s, int e) : start(s), end(e) {}
};
vector<Interval> insertInterval(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> result;
// Traverse through each interval in the input list
// and perform the necessary merging and inserting.
for (const auto& interval : intervals) {
// If the current interval ends before the new interval starts,
// add it to the result as it does not overlap.
if (interval.end < newInterval.start) {
result.push_back(interval);
}
// If the current interval starts after the new interval ends,
// add the new interval and update it to the current interval
// as there won't be any more overlap with subsequent intervals.
else if (interval.start > newInterval.end) {
result.push_back(newInterval);
newInterval = interval;
}
// If there is an overlap between the current interval and the new interval,
// merge them by updating the new interval's start and end.
else {
newInterval.start = min(interval.start, newInterval.start);
newInterval.end = max(interval.end, newInterval.end);
}
}
// Add the final merged or inserted interval to the result.
result.push_back(newInterval);
return result;
}
// Utility function to print the intervals.
void printIntervals(const vector<Interval>& intervals) {
for (const auto& interval : intervals) {
cout << "[" << interval.start << ", " << interval.end << "] ";
}
cout << endl;
}
int main() {
// Example usage
vector<Interval> intervals = {Interval(1, 3), Interval(6, 9)};
Interval newInterval(2, 5);
cout << "Original intervals: ";
printIntervals(intervals);
vector<Interval> mergedIntervals = insertInterval(intervals, newInterval);
cout << "Merged intervals: ";
printIntervals(mergedIntervals);
return 0;
}
================================================
FILE: Arrays/insert_interval.go
================================================
/*
Insert Interval
In this implementation, the `Interval` struct represents an interval with a start and end value.
The `insert` function takes a sorted list of intervals and a new interval as input and returns a new
list of intervals after merging the new interval with the existing intervals.
Here's how the `insert` function works:
1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0.
2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the
`result` slice.
3. It merges intervals that overlap with the new interval by updating the start and end values of the new
interval accordingly.
4. It adds the merged new interval to the `result` slice.
5. It adds any remaining intervals from the original list to the `result` slice.
6. Finally, it returns the `result` slice containing the merged intervals.
The `min` and `max` functions are helper functions to find the minimum and maximum of two integers.
In the `main` function, an example input is provided with a list of intervals and a new interval.
The `insert` function is called with these inputs, and the result is printed to the console.
Time Complexity:
The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to
iterate through each interval in the list to merge and insert the new interval. In the worst case, we may
need to traverse all intervals in the list.
Space Complexity:
The space complexity is O(n), where n is the number of intervals in the input list. This is because we
create a new result slice to store the merged intervals, which can potentially contain all the intervals
from the input list plus the merged new interval. Therefore, the space required is proportional to the
number of intervals in the input list.
Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number
of intervals in the input list.
*/
package main
import (
"fmt"
)
// Interval represents an interval with a start and end value.
type Interval struct {
Start int
End int
}
// insert merges a new interval into a sorted list of intervals.
func insert(intervals []Interval, newInterval Interval) []Interval {
result := make([]Interval, 0)
i := 0
// Add intervals that end before the new interval starts
for i < len(intervals) && intervals[i].End < newInterval.Start {
result = append(result, intervals[i])
i++
}
// Merge intervals that overlap with the new interval
for i < len(intervals) && intervals[i].Start <= newInterval.End {
newInterval.Start = min(newInterval.Start, intervals[i].Start)
newInterval.End = max(newInterval.End, intervals[i].End)
i++
}
// Add the merged new interval
result = append(result, newInterval)
// Add remaining intervals
for i < len(intervals) {
result = append(result, intervals[i])
i++
}
return result
}
// min returns the minimum of two integers.
func min(a, b int) int {
if a < b {
return a
}
return b
}
// max returns the maximum of two integers.
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
intervals := []Interval{
{1, 3},
{6, 9},
}
newInterval := Interval{2, 5}
result := insert(intervals, newInterval)
fmt.Println("Merged Intervals:", result)
}
================================================
FILE: Arrays/insert_interval.java
================================================
/*
Insert Interval
In this implementation, the `Interval` struct represents an interval with a start and end value.
The `insert` function takes a sorted list of intervals and a new interval as input and returns a new
list of intervals after merging the new interval with the existing intervals.
Here's how the `insert` function works:
1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0.
2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the
`result` slice.
3. It merges intervals that overlap with the new interval by updating the start and end values of the new
interval accordingly.
4. It adds the merged new interval to the `result` slice.
5. It adds any remaining intervals from the original list to the `result` slice.
6. Finally, it returns the `result` slice containing the merged intervals.
The `min` and `max` functions are helper functions to find the minimum and maximum of two integers.
In the `main` function, an example input is provided with a list of intervals and a new interval.
The `insert` function is called with these inputs, and the result is printed to the console.
Time Complexity:
The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to
iterate through each interval in the list to merge and insert the new interval. In the worst case, we may
need to traverse all intervals in the list.
Space Complexity:
The space complexity is O(n), where n is the number of intervals in the input list. This is because we
create a new result slice to store the merged intervals, which can potentially contain all the intervals
from the input list plus the merged new interval. Therefore, the space required is proportional to the
number of intervals in the input list.
Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number
of intervals in the input list.
*/
import java.util.ArrayList;
import java.util.List;
class Interval {
int start;
int end;
Interval(int start, int end) {
this.start = start;
this.end = end;
}
}
public class InsertInterval {
public static List<Interval> insertInterval(List<Interval> intervals, Interval newInterval) {
List<Interval> result = new ArrayList<>();
// Traverse through each interval in the input list
// and perform the necessary merging and inserting.
for (Interval interval : intervals) {
// If the current interval ends before the new interval starts,
// add it to the result as it does not overlap.
if (interval.end < newInterval.start) {
result.add(interval);
}
// If the current interval starts after the new interval ends,
// add the new interval and update it to the current interval
// as there won't be any more overlap with subsequent intervals.
else if (interval.start > newInterval.end) {
result.add(newInterval);
newInterval = interval;
}
// If there is an overlap between the current interval and the new interval,
// merge them by updating the new interval's start and end.
else {
newInterval.start = Math.min(interval.start, newInterval.start);
newInterval.end = Math.max(interval.end, newInterval.end);
}
}
// Add the final merged or inserted interval to the result.
result.add(newInterval);
return result;
}
// Utility function to print the intervals.
public static void printIntervals(List<Interval> intervals) {
for (Interval interval : intervals) {
System.out.print("[" + interval.start + ", " + interval.end + "] ");
}
System.out.println();
}
public static void main(String[] args) {
// Example usage
List<Interval> intervals = new ArrayList<>();
intervals.add(new Interval(1, 3));
intervals.add(new Interval(6, 9));
Interval newInterval = new Interval(2, 5);
System.out.print("Original intervals: ");
printIntervals(intervals);
List<Interval> mergedIntervals = insertInterval(intervals, newInterval);
System.out.print("Merged intervals: ");
printIntervals(mergedIntervals);
}
}
================================================
FILE: Arrays/insert_interval.js
================================================
/*
Insert Interval
In this implementation, the `Interval` struct represents an interval with a start and end value.
The `insert` function takes a sorted list of intervals and a new interval as input and returns a new
list of intervals after merging the new interval with the existing intervals.
Here's how the `insert` function works:
1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0.
2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the
`result` slice.
3. It merges intervals that overlap with the new interval by updating the start and end values of the new
interval accordingly.
4. It adds the merged new interval to the `result` slice.
5. It adds any remaining intervals from the original list to the `result` slice.
6. Finally, it returns the `result` slice containing the merged intervals.
The `min` and `max` functions are helper functions to find the minimum and maximum of two integers.
In the `main` function, an example input is provided with a list of intervals and a new interval.
The `insert` function is called with these inputs, and the result is printed to the console.
Time Complexity:
The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to
iterate through each interval in the list to merge and insert the new interval. In the worst case, we may
need to traverse all intervals in the list.
Space Complexity:
The space complexity is O(n), where n is the number of intervals in the input list. This is because we
create a new result slice to store the merged intervals, which can potentially contain all the intervals
from the input list plus the merged new interval. Therefore, the space required is proportional to the
number of intervals in the input list.
Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number
of intervals in the input list.
*/
class Interval {
constructor(start, end) {
this.start = start;
this.end = end;
}
}
function insertInterval(intervals, newInterval) {
const mergedIntervals = [];
let i = 0;
// Skip all intervals that end before the new interval starts
while (i < intervals.length && intervals[i].end < newInterval.start) {
mergedIntervals.push(intervals[i]);
i++;
}
// Merge intervals that overlap with the new interval
while (i < intervals.length && intervals[i].start <= newInterval.end) {
newInterval.start = Math.min(intervals[i].start, newInterval.start);
newInterval.end = Math.max(intervals[i].end, newInterval.end);
i++;
}
mergedIntervals.push(newInterval);
// Add the remaining intervals to the merged intervals list
while (i < intervals.length) {
mergedIntervals.push(intervals[i]);
i++;
}
return mergedIntervals;
}
// Example usage
const intervals = [new Interval(1, 3), new Interval(6, 9)];
const newInterval = new Interval(2, 5);
console.log("Original intervals:", intervals);
const mergedIntervals = insertInterval(intervals, newInterval);
console.log("Merged intervals:", mergedIntervals);
================================================
FILE: Arrays/insert_interval.py
================================================
'''
Insert Interval
In this implementation, the `Interval` struct represents an interval with a start and end value.
The `insert` function takes a sorted list of intervals and a new interval as input and returns a new
list of intervals after merging the new interval with the existing intervals.
Here's how the `insert` function works:
1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0.
2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the
`result` slice.
3. It merges intervals that overlap with the new interval by updating the start and end values of the new
interval accordingly.
4. It adds the merged new interval to the `result` slice.
5. It adds any remaining intervals from the original list to the `result` slice.
6. Finally, it returns the `result` slice containing the merged intervals.
The `min` and `max` functions are helper functions to find the minimum and maximum of two integers.
In the `main` function, an example input is provided with a list of intervals and a new interval.
The `insert` function is called with these inputs, and the result is printed to the console.
Time Complexity:
The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to
iterate through each interval in the list to merge and insert the new interval. In the worst case, we may
need to traverse all intervals in the list.
Space Complexity:
The space complexity is O(n), where n is the number of intervals in the input list. This is because we
create a new result slice to store the merged intervals, which can potentially contain all the intervals
from the input list plus the merged new interval. Therefore, the space required is proportional to the
number of intervals in the input list.
Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number
of intervals in the input list.
'''
class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def insertInterval(intervals, newInterval):
mergedIntervals = []
i = 0
# Skip all intervals that end before the new interval starts
while i < len(intervals) and intervals[i].end < newInterval.start:
mergedIntervals.append(intervals[i])
i += 1
# Merge intervals that overlap with the new interval
while i < len(intervals) and intervals[i].start <= newInterval.end:
newInterval.start = min(intervals[i].start, newInterval.start)
newInterval.end = max(in
gitextract_p9w8rb_6/
├── .github/
│ └── ISSUE_TEMPLATE/
│ └── feature_request.md
├── .gitignore
├── 2D Arrays (Matrix)/
│ ├── 2D_sorted.go
│ ├── 2D_sorted_array.java
│ ├── binary_search.cpp
│ ├── count_negatives_in_sorted_matrix.cpp
│ ├── matrix_diagonal_sum.cpp
│ ├── matrix_wave_print.cpp
│ ├── rotate_matrix.cpp
│ ├── rotate_matrix.go
│ ├── rotate_matrix.java
│ ├── rotate_matrix.js
│ ├── rotate_matrix.py
│ ├── search_element.cpp
│ ├── searching_in_sorted_array.cpp
│ ├── searching_in_sorted_array.java
│ ├── searching_in_sorted_array.js
│ ├── searching_in_sorted_array.py
│ ├── set_matrix_0.cpp
│ ├── set_matrix_0.go
│ ├── set_matrix_0.java
│ ├── spiral_traverse.cpp
│ ├── spiral_traverse.go
│ ├── spiral_traverse.java
│ ├── spiral_traverse.py
│ ├── zigzag_traversal.cpp
│ ├── zigzag_traversal.go
│ ├── zigzag_traversal.java
│ ├── zigzag_traversal.js
│ └── zigzag_traversal.py
├── Arrays/
│ ├── Jobassign.cpp
│ ├── Maximum_freq.py
│ ├── Rotatedarr.cpp
│ ├── array_of_products.cpp
│ ├── array_of_products.go
│ ├── array_of_products.java
│ ├── array_of_products.js
│ ├── array_of_products.py
│ ├── ceaser_cipher.cpp
│ ├── ceaser_cipher.go
│ ├── ceaser_cipher.java
│ ├── ceaser_cipher.js
│ ├── ceaser_cipher.py
│ ├── dutch_national_flag.cpp
│ ├── dutch_national_flag.go
│ ├── dutch_national_flag.java
│ ├── dutch_national_flag.js
│ ├── dutch_national_flag.py
│ ├── find_three_largest_integers.js
│ ├── find_three_largest_number.cpp
│ ├── find_three_largest_numbers.go
│ ├── find_three_largest_numbers.java
│ ├── find_three_largest_numbers.py
│ ├── first_duplicate_value.cpp
│ ├── first_duplicate_value.go
│ ├── first_duplicate_value.java
│ ├── first_duplicate_value.js
│ ├── first_duplicate_value.py
│ ├── four_sum.py
│ ├── insert_interval.cpp
│ ├── insert_interval.go
│ ├── insert_interval.java
│ ├── insert_interval.js
│ ├── insert_interval.py
│ ├── insert_intervals.cpp
│ ├── insert_intervals.go
│ ├── is_monotonic.cpp
│ ├── is_monotonic.go
│ ├── is_monotonic.java
│ ├── is_monotonic.js
│ ├── is_monotonic.py
│ ├── longest_peak.cpp
│ ├── longest_peak.go
│ ├── longest_peak.java
│ ├── longest_peak.js
│ ├── longest_peak.py
│ ├── majority_element.go
│ ├── majority_element.java
│ ├── maximum_subarray_sum.cpp
│ ├── maximum_subarray_sum.go
│ ├── maximum_subarray_sum.py
│ ├── merge_intervals.cpp
│ ├── merge_intervals.go
│ ├── merge_intervals.java
│ ├── merge_intervals.js
│ ├── merge_intervals.py
│ ├── merge_sorted_array.cpp
│ ├── merge_sorted_array.java
│ ├── merge_sorted_arrays.py
│ ├── minimum_size_subarray_sum.java
│ ├── move_element_to_end.cpp
│ ├── move_element_to_end.go
│ ├── move_element_to_end.java
│ ├── move_element_to_end.js
│ ├── move_element_to_end.py
│ ├── non-overlapping intervals.cpp
│ ├── pallindromic_permutations.cpp
│ ├── sign_of_the_product_of_an_array.cpp
│ ├── smallest_difference.cpp
│ ├── smallest_difference.go
│ ├── smallest_difference.java
│ ├── smallest_difference.js
│ ├── smallest_difference.py
│ ├── sorted_square_array,js
│ ├── sorted_square_array.cpp
│ ├── sorted_square_array.go
│ ├── sorted_square_array.java
│ ├── sorted_square_array.py
│ ├── string_halves.cpp
│ ├── three_largest_no.py
│ ├── total_hamming_distance.cpp
│ ├── tournament_winner.go
│ ├── triplet_sum.cpp
│ ├── triplet_sum.go
│ ├── triplet_sum.java
│ ├── triplet_sum.js
│ ├── triplet_sum.py
│ └── urlify.go
├── Backtracking/
│ ├── Generate_Parentheses.py
│ ├── geenrate_parentheses.go
│ ├── n_queen.cpp
│ ├── n_queens.java
│ └── sudoko_solver.java
├── Binary Search/
│ ├── BinarySearchRecursive.java
│ ├── binary_search.cpp
│ ├── binary_search.js
│ ├── binary_search.py
│ ├── binary_search_iterative.go
│ ├── binary_search_recursive.go
│ ├── binary_serach_first_and_last_occurence.py
│ ├── first_and_last_pos.js
│ ├── first_and_last_pos_of_element.cpp
│ ├── first_and_last_position.java
│ ├── first_last_pos.java
│ ├── first_occurance.go
│ ├── first_occurence.java
│ ├── first_true.cpp
│ ├── first_true.go
│ ├── first_true.java
│ ├── first_true.js
│ ├── first_true.py
│ ├── floor_of_target.java
│ ├── index_position.java
│ ├── infinity_array.java
│ ├── last_occurance.go
│ ├── median_of_two_sorted_arrays.cpp
│ ├── median_of_two_sorted_arrays.js
│ ├── minimum_in_rotated_sorted_array.cpp
│ ├── perfect_square.java
│ ├── search_in_rotated_sorted_array.cpp
│ ├── search_in_sorted_rotated_array.cpp
│ ├── search_in_sorted_rotated_array.go
│ ├── search_in_sorted_rotated_array.java
│ ├── search_in_sorted_rotated_array.py
│ ├── search_insert_position.js
│ └── square_root.java
├── Bit Manipulation/
│ ├── bloom_filter.cpp
│ ├── bloom_filter.py
│ ├── count_bits.go
│ ├── interesting_array.java
│ ├── mod_array.java
│ ├── number_of_1_bits.java
│ ├── parity_of_a_word.go
│ ├── power_of_2.cpp
│ ├── reduce_to_zero.cpp
│ ├── setbits.cpp
│ ├── single_number.java
│ └── subarrays_with_bitwise_OR_1.java
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dynamic Programming/
│ ├── best_time_to_buy_and_sell_stock.cpp
│ ├── best_time_to_buy_and_sell_stock.go
│ ├── best_time_to_buy_and_sell_stock.java
│ ├── best_time_to_buy_and_sell_stock.js
│ ├── best_time_to_buy_and_sell_stock.py
│ ├── climb_stairs.cpp
│ ├── climb_stairs.go
│ ├── climb_stairs.java
│ ├── climb_stairs.js
│ ├── climb_stairs.py
│ ├── coin_change.cpp
│ ├── coin_change.go
│ ├── coin_change.java
│ ├── coin_change.js
│ ├── coin_change.py
│ ├── dice_throws.go
│ ├── disk_stacking.go
│ ├── disk_stacking.py
│ ├── distance_of_nearest_0.cpp
│ ├── distance_of_nearest_0.py
│ ├── distane_of_nearest_0.go
│ ├── distane_of_nearest_0.java
│ ├── distane_of_nearest_0.js
│ ├── edit_distance_dp.cpp
│ ├── edit_distance_dp.go
│ ├── edit_distance_dp.java
│ ├── edit_distance_dp.js
│ ├── edit_distance_dp.py
│ ├── edit_distance_memoized.cpp
│ ├── edit_distance_recursive.cpp
│ ├── house_robber.cpp
│ ├── juice_bottling.cpp
│ ├── juice_bottling.go
│ ├── juice_bottling.java
│ ├── juice_bottling.js
│ ├── juice_bottling.py
│ ├── knapsack.cpp
│ ├── knapsack.go
│ ├── knapsack.java
│ ├── knapsack.js
│ ├── knapsack.py
│ ├── knight_probability_chessboard.cpp
│ ├── knight_probability_chessboard.go
│ ├── knight_probability_chessboard.java
│ ├── knight_probability_chessboard.js
│ ├── knight_probability_chessboard.py
│ ├── kth_closest_point_to origin.java
│ ├── largest_rectangle.java
│ ├── largest_rectangle.js
│ ├── largest_rectangle.py
│ ├── longest_common_subsequence_dp.cpp
│ ├── longest_common_subsequence_memoization.cpp
│ ├── longest_common_subsequence_recursive.cpp
│ ├── longest_increasing_subsequence.cpp
│ ├── longest_pallindromic_substring.cpp
│ ├── longest_pallindromic_substring.go
│ ├── longest_pallindromic_substring.java
│ ├── longest_pallindromic_substring.js
│ ├── longest_pallindromic_substring.py
│ ├── max_path_sum.go
│ ├── max_sum_increasing_subsequence.cpp
│ ├── max_sum_increasing_subsequence.go
│ ├── max_sum_increasing_subsequence.java
│ ├── max_sum_increasing_subsequence.js
│ ├── max_sum_increasing_subsequence.py
│ ├── maximal_sqaure.cpp
│ ├── maximal_sqaure.go
│ ├── maximal_sqaure.js
│ ├── maximal_sqaure.py
│ ├── maximal_square.java
│ ├── min_cost_travel_in_a_grid.cpp
│ ├── min_insertion_steps_for_string_palindrome.java
│ ├── min_number_of_jumps.cpp
│ ├── min_number_of_jumps.go
│ ├── min_number_of_jumps.java
│ ├── min_number_of_jumps.js
│ ├── min_number_of_jumps.py
│ ├── min_steps_to_make_string_palindrome.go
│ ├── min_steps_to_make_string_palindrome.java
│ ├── min_steps_to_make_string_palindrome.py
│ ├── min_steps_to_make_string_pallindrome.cpp
│ ├── min_steps_to_make_string_pallindrome.js
│ ├── min_steps_to_reduce_a_number_to_one.cpp
│ ├── num_ways_to_make_change.cpp
│ ├── num_ways_to_make_change.go
│ ├── num_ways_to_make_change.java
│ ├── num_ways_to_make_change.js
│ ├── num_ways_to_make_change.py
│ ├── num_ways_to_traverse_graph.cpp
│ ├── num_ways_to_traverse_graph.go
│ ├── num_ways_to_traverse_graph.js
│ ├── num_ways_to_traverse_graph.py
│ ├── numbers_in_pi.go
│ ├── reconstruct_bst_in_python.py
│ ├── rod_cutting_problem_dp.cpp
│ ├── rod_cutting_problem_memoized.cpp
│ ├── rod_cutting_problem_recursive.cpp
│ ├── trapping_rain_water.cpp
│ ├── unique_paths_with_obstacles.cpp
│ ├── wine_selling_problem_dp.cpp
│ ├── wine_selling_problem_memoized.cpp
│ └── wine_selling_problem_recursive.cpp
├── Famous Algorithms/
│ ├── N_queen.js
│ ├── euclidean_algorithm.java
│ ├── euclidean_algorithm.js
│ ├── euclidean_algorithm.py
│ ├── kadanes_algorithm.c++
│ ├── kadanes_algorithm.go
│ ├── kadanes_algorithm.java
│ ├── kadanes_algorithm.py
│ ├── kadenes_algorithm.js
│ ├── kmp.java
│ ├── kmp.js
│ └── kmp.py
├── Fast and Slow Pointers/
│ ├── happy_number.go
│ ├── linked_list_compute_midpoint.cpp
│ ├── linked_list_compute_midpoint.java
│ ├── linked_list_find_middle.py
│ ├── linked_list_floyds_cycle_detection.cpp
│ └── linked_list_floyds_cycle_detection.py
├── Graphs/
│ ├── Diljstra.go
│ ├── GraphBFS.java
│ ├── Graph_Dijstra.java
│ ├── Graphs_Dijkstras.py
│ ├── Graphs_Ford_Fulkerson.cpp
│ ├── Graphs_bfs.cpp
│ ├── Graphs_bfs.js
│ ├── Graphs_bfs.py
│ ├── Graphs_bfs_sssp.cpp
│ ├── Graphs_cycle_detection_bfs.cpp
│ ├── Graphs_cycle_detection_dfs.cpp
│ ├── Graphs_dfs.cpp
│ ├── Graphs_dfs.java
│ ├── Graphs_dfs.js
│ ├── Graphs_dfs.py
│ ├── Graphs_dfs_connected_components.cpp
│ ├── Graphs_dijkstras.js
│ ├── Graphs_flood_fill.cpp
│ ├── Graphs_kill_process.cpp
│ ├── Graphs_kruskals_algo.cpp
│ ├── Graphs_kruskals_algorithm.js
│ ├── Graphs_topological_sort_bfs.cpp
│ ├── Graphs_topological_sort_dfs.cpp
│ ├── a_star_algorithm.py
│ ├── adjacency_list.java
│ ├── adjacency_matrix.go
│ ├── adjacency_matrix.java
│ ├── dijkstras.cpp
│ ├── dijkstras.go
│ ├── dijkstras.java
│ ├── dijkstras.py
│ ├── dijkstras_heap_based.go
│ ├── ford_fulkerson.cpp
│ ├── graphs_adjacency_list.cpp
│ ├── graphs_adjacency_list_generic.cpp
│ ├── graphs_bfs.go
│ ├── graphs_dfs.go
│ ├── kruskals_algorithm.java
│ ├── kruskals_algorithm.py
│ ├── remove_island.go
│ ├── river_sizes.cpp
│ ├── river_sizes.go
│ ├── river_sizes.java
│ ├── river_sizes.js
│ ├── river_sizes.py
│ ├── single_cycle_check.cpp
│ ├── single_cycle_check.go
│ ├── single_cycle_check.java
│ ├── single_cycle_check.js
│ ├── single_cycle_check.py
│ ├── snack_ladders.cpp
│ ├── snack_ladders.js
│ ├── snack_ladders.py
│ ├── snakes_ladders.java
│ ├── topological_sort.cpp
│ ├── topological_sort.go
│ ├── topological_sort.java
│ ├── topological_sort.js
│ ├── topological_sort.py
│ ├── two_colorable.cpp
│ ├── two_colorable.go
│ ├── two_colorable.java
│ ├── two_colorable.js
│ ├── two_colorable.py
│ ├── union_find.cpp
│ ├── union_find.go
│ ├── union_find.java
│ ├── union_find.js
│ ├── union_find.py
│ ├── validate_bst.cpp
│ ├── validate_bst.go
│ ├── validate_bst.java
│ ├── validate_bst.js
│ ├── validate_bst.py
│ ├── youngest_common_ancestor.cpp
│ ├── youngest_common_ancestor.go
│ ├── youngest_common_ancestor.java
│ ├── youngest_common_ancestor.js
│ └── youngest_common_ancestor.py
├── Greedy/
│ ├── coin_change.go
│ ├── coin_change.java
│ ├── coin_change.js
│ ├── coin_change.py
│ ├── task_assignment.cpp
│ ├── task_assignment.go
│ ├── task_assignment.java
│ ├── task_assignment.js
│ └── task_assignment.py
├── Hash Table/
│ ├── Bloomfilter.cpp
│ ├── Convert an array to reduced form using hashing.cpp
│ ├── Count_Pairs_of_Points_With_Distance_k.py
│ ├── HashTable.java
│ ├── Longest_substring_without_repeating_characters.py
│ ├── Partition.java
│ ├── Partition_string.py
│ ├── add_first_missing_positive.cpp
│ ├── add_first_missing_positive.java
│ ├── find_optimal_partition_of_string.cpp
│ ├── find_optimal_partition_of_string.go
│ ├── first_duplicate_value.go
│ ├── first_missing_positve.go
│ ├── first_missing_positve.js
│ ├── first_missing_positve.py
│ ├── first_non_repeated_character.go
│ ├── first_repeated_character.go
│ ├── four_number_sum.java
│ ├── frequency_of_elements.java
│ ├── group_anagrams.cpp
│ ├── group_anagrams.go
│ ├── group_anagrams.java
│ ├── group_anagrams.js
│ ├── group_anagrams.py
│ ├── integer_to_roman.cpp
│ ├── integer_to_roman.go
│ ├── integer_to_roman.java
│ ├── integer_to_roman.js
│ ├── integer_to_roman.py
│ ├── remove_duplicates.go
│ ├── roman_to_integer.cpp
│ ├── roman_to_integer.go
│ ├── roman_to_integer.java
│ ├── roman_to_integer.js
│ ├── roman_to_integer.py
│ ├── sum_of_unique_elements.java
│ ├── three_number_sum.java
│ ├── two_sum.cpp
│ ├── two_sum.go
│ ├── two_sum.java
│ ├── two_sum.js
│ ├── two_sum.py
│ ├── zero_sum_subarray.cpp
│ ├── zero_sum_subarray.go
│ ├── zero_sum_subarray.java
│ ├── zero_sum_subarray.js
│ └── zero_sum_subarray.py
├── Heaps/
│ ├── heap.cpp
│ ├── heap.go
│ ├── heap.java
│ ├── heap.js
│ ├── heap.py
│ └── k_closest.py
├── LICENSE
├── Linked List/
│ ├── Add_two_numbers.py
│ ├── Intersection_LL.cpp
│ ├── LFU_Cache.cpp
│ ├── Linked_List_Component.java
│ ├── MiddleOfLinkedList.java
│ ├── MiddleofLL.py
│ ├── RemoveKthNodeFromEnd.java
│ ├── Remove_nth_node_from_end.java
│ ├── add_two_numbers.cpp
│ ├── add_two_numbers.js
│ ├── delete_kth_node.js
│ ├── double_linked_list.go
│ ├── doubly_linked_list.cpp
│ ├── doubly_linked_list.java
│ ├── doubly_linked_list.js
│ ├── floyds_cycle_detection.cpp
│ ├── floyds_cycle_detection.go
│ ├── floyds_cycle_detection.java
│ ├── intersection_of_two_linked_lists.cpp
│ ├── liniked_list_sort_list.cpp
│ ├── linked_list.go
│ ├── linked_list.js
│ ├── linked_list.py
│ ├── linked_list_add_two_numbers.py
│ ├── linked_list_compute_middle.cpp
│ ├── linked_list_compute_middle.java
│ ├── linked_list_delete_at_any_pos.cpp
│ ├── linked_list_delete_at_head.cpp
│ ├── linked_list_delete_at_tail.cpp
│ ├── linked_list_delete_node.go
│ ├── linked_list_even_or_odd.go
│ ├── linked_list_find_length.cpp
│ ├── linked_list_insert_at_any_pos.cpp
│ ├── linked_list_insert_at_head.cpp
│ ├── linked_list_insert_at_tail.cpp
│ ├── linked_list_kth_from_end.go
│ ├── linked_list_kth_node_from_end.cpp
│ ├── linked_list_linear_search.cpp
│ ├── linked_list_merge_k_sorted_lists.cpp
│ ├── linked_list_merge_two_sorted_linked_list.cpp
│ ├── linked_list_mergesort_an_unsorted_list.cpp
│ ├── linked_list_middle.go
│ ├── linked_list_middle.js
│ ├── linked_list_odd_even.cpp
│ ├── linked_list_pallindrome.cpp
│ ├── linked_list_recursive_search.cpp
│ ├── linked_list_remove_dups.cpp
│ ├── linked_list_remove_kth_node_from_end.py
│ ├── linked_list_remove_nth_node_from_end.cpp
│ ├── linked_list_remove_nth_node_from_end.py
│ ├── linked_list_reverse.cpp
│ ├── linked_list_reverse.js
│ ├── linked_list_reverse_recursive.cpp
│ ├── linked_list_sum_lists.cpp
│ ├── linked_list_swap_nodes_in_pair.cpp
│ ├── linked_list_swap_nodes_in_pair_iterative.cpp
│ ├── linked_list_take_input.cpp
│ ├── linked_list_take_input_as_array_operator_overloading.cpp
│ ├── linked_list_take_input_operator_overloading.cpp
│ ├── recursive and iterative in singly linkedlist.py
│ ├── reverse_linked_list.go
│ ├── reverse_linked_list.java
│ ├── singly_linked_list.cpp
│ ├── singly_linked_list.go
│ ├── singly_linked_list.java
│ ├── singly_linked_list.py
│ ├── sll.go
│ └── sort_linked_list.cpp
├── Math/
│ ├── Basic_operations.py
│ ├── Count.go
│ ├── Factorial.cpp
│ ├── Factorial.go
│ ├── Factorial.java
│ ├── Factorial.py
│ ├── Hamming_distance.py
│ ├── Hammingdistance.cpp
│ ├── K_closest.cpp
│ ├── K_closest_points_to_origin.java
│ ├── K_closest_points_to_origin.py
│ ├── Number_of_Substrings_With_Only_1s.cpp
│ ├── PowXn.go
│ ├── PowXn.java
│ ├── PowXn.py
│ ├── Reverse_Integer.cpp
│ ├── Sum_four.cpp
│ ├── circle.cpp
│ ├── count_numbers_with_unique_digits.java
│ ├── count_primes.cpp
│ ├── count_primes.java
│ ├── count_unique_digits.cpp
│ ├── count_unique_digits.go
│ ├── factorial.py
│ ├── factorial_iterative.js
│ ├── find_longest_increasing_subsequence.cpp
│ ├── hamming_distance.cpp
│ ├── is_power_of_two.js
│ ├── is_prime.js
│ ├── k_closest_points_to_origin.cpp
│ ├── missing_number.py
│ ├── modular_expo_itera.cpp
│ ├── modular_expo_recursive.cpp
│ ├── num_points_inside_a_circle.cpp
│ ├── num_points_inside_a_circle.js
│ ├── num_points_inside_a_circle.py
│ ├── num_steps_reduce_to_zero.Go
│ ├── num_steps_reduce_to_zero.cpp
│ ├── num_steps_reduce_to_zero.java
│ ├── num_steps_reduce_to_zero.js
│ ├── num_steps_reduce_to_zero.py
│ ├── number_of_substrings_with_only_1s.js
│ ├── op.js
│ ├── palindrome_number.java
│ ├── pallindrome_number.cpp
│ ├── pallindrome_number.py
│ ├── powXn.cpp
│ ├── powXn.js
│ ├── prime_factorization.cpp
│ ├── shuffle_an_array.cpp
│ ├── shuffle_an_array.py
│ ├── sieve_of_eratosthenes.cpp
│ ├── substrings_with_1s.py
│ ├── unique_digits.cpp
│ ├── unique_digits.java
│ ├── unique_digits.py
│ └── unique_integers_that_sum_up_to_0.cpp
├── Misc/
│ └── tictactoe.java
├── Patterns/
│ ├── CompleteSquare.java
│ ├── HollowPattern.cpp
│ ├── HollowPattern.go
│ ├── HollowPattern.java
│ ├── HollowPattern.py
│ ├── Ladder_Pattern.java
│ ├── ReverseRightTrianglePattern.java
│ ├── RightPascalTriangle.java
│ ├── StarDiamond.java
│ ├── diamond_pattern.cpp
│ ├── diamond_pattern.go
│ ├── diamond_pattern.java
│ ├── diamond_pattern.py
│ ├── numerical_pattern.java
│ ├── triangular_pattern.java
│ └── triangular_pattern.py
├── Priority Queues/
│ ├── In_Place_HeapSort.cpp
│ ├── buy_the_ticket.cpp
│ ├── check_max_heap.cpp
│ ├── kth_largest_element.cpp
│ ├── kth_smallest_element.cpp
│ ├── merge_k_sorted_arrays.cpp
│ └── running_median.cpp
├── Queue/
│ ├── queue.cpp
│ ├── queue.go
│ ├── queue.java
│ ├── queue.js
│ ├── queue.py
│ ├── queue_using_stack.js
│ ├── queue_using_stacks.go
│ ├── queues_using_stacks.py
│ └── stack_using_queue.cpp
├── README.md
├── Recursion/
│ ├── calculatextopowern.cpp
│ ├── count_digits.cpp
│ ├── count_digits.go
│ ├── count_zeros.cpp
│ ├── count_zeros.go
│ ├── factorial.cpp
│ ├── factorial.go
│ ├── factorial.js
│ ├── fibonacci.cpp
│ ├── fibonacci.go
│ ├── fibonacci_memoization.cpp
│ ├── fibonacci_memoization.go
│ ├── geometric_sum.cpp
│ ├── is_array_sorted.cpp
│ ├── is_array_sorted.go
│ ├── is_element_present.cpp
│ ├── modular_exponentiation.cpp
│ ├── multiplication.cpp
│ ├── powerset.cpp
│ ├── powerset.go
│ ├── powerset.java
│ ├── powerset.js
│ ├── powerset.py
│ ├── print_numbers.cpp
│ ├── recursive_bubble_sort.cpp
│ ├── reverse_print.go
│ ├── tower_of_hannoi.cpp
│ ├── tower_of_hannoi.java
│ ├── tower_of_hannoi.js
│ ├── tower_of_hannoi.py
│ ├── tower_of_hanoi.go
│ └── valid_palindrome_2.py
├── SECURITY.md
├── Scheduling/
│ ├── fcfs.c
│ ├── sjf.c
│ └── srtf.c
├── Scheduling Algortihms/
│ ├── fcfs.c
│ ├── sjf.c
│ └── srtf.c
├── Searching/
│ ├── first_duplicate_value.js
│ ├── linear_search_string.cpp
│ ├── semordnilap.go
│ ├── separate_0s_and_1s.go
│ └── separate_even_odd.go
├── Sliding Window/
│ ├── find_max.go
│ ├── fruits_into_basket.cpp
│ ├── fruits_into_basket.go
│ ├── fruits_into_basket.java
│ ├── fruits_into_basket.js
│ ├── fruits_into_basket.py
│ ├── longest_repeated_character_replacement.cpp
│ ├── longest_repeated_character_replacement.go
│ ├── longest_repeated_character_replacement.java
│ ├── longest_repeated_character_replacement.js
│ ├── longest_repeated_character_replacement.py
│ ├── longest_substring_with_k_distinct_chars.go
│ ├── longest_substring_with_k_distinct_chars.java
│ ├── longest_substring_with_k_distinct_chars.js
│ ├── longest_substring_with_k_distinct_chars.py
│ ├── longest_substring_without_repeating_characters.go
│ ├── max_eraser_value.go
│ ├── max_eraser_value.java
│ ├── sliding_window_max.java
│ ├── sliding_window_max.js
│ ├── sliding_window_max.py
│ ├── subaray_sum_equals_k.cpp
│ ├── subaray_sum_equals_k.go
│ ├── subaray_sum_equals_k.java
│ ├── subaray_sum_equals_k.js
│ ├── subaray_sum_equals_k.py
│ ├── subarray_product_less_than_k,js
│ ├── subarray_product_less_than_k.cpp
│ ├── subarray_product_less_than_k.go
│ ├── subarray_product_less_than_k.java
│ └── subarray_product_less_than_k.py
├── Stacks/
│ ├── Stack_with_max_API.cpp
│ ├── Stacks_using_queues.py
│ ├── balanced_parenthesis.go
│ ├── is_palindrome.go
│ ├── next_greater_element.c++
│ ├── next_greater_element.go
│ ├── next_greater_element.java
│ ├── next_greater_element.js
│ ├── next_greater_element.py
│ ├── queue using stack.go
│ ├── queue using stack.java
│ ├── queue using stack.js
│ ├── queue using stack.py
│ ├── queue_using_stacks.cpp
│ ├── reverse_polish_notation.cpp
│ ├── stack.cpp
│ ├── stack.go
│ ├── stack.java
│ ├── stack.js
│ ├── stack.py
│ ├── stack_array_based.go
│ ├── stack_dynamic_array.go
│ ├── stack_linked_list.go
│ ├── stack_using_queue.cpp
│ ├── stack_using_queue.go
│ ├── stack_using_queue.java
│ ├── stack_using_queue.js
│ ├── stack_using_queue.py
│ ├── stacks_API.cpp
│ ├── stacks_using_queues.java
│ ├── stacks_with_queues.cpp
│ ├── stacks_with_queues.py
│ └── valid_parentheses.cpp
├── Strings/
│ ├── Dp_plaindrome.py
│ ├── KMP.go
│ ├── Longest_palindromic_substring.py
│ ├── MaxConcatenatedstr.java
│ ├── Min_palindrome.js
│ ├── Valid_palindrome.py
│ ├── case_specific_sorting_of_strings.cpp
│ ├── check panagram.java
│ ├── check_anagrams.java
│ ├── check_palindrome.cpp
│ ├── check_permutations.cpp
│ ├── count_occurances.java
│ ├── group_anagrams.cpp
│ ├── group_anagrams.go
│ ├── group_anagrams.java
│ ├── group_anagrams.js
│ ├── group_anagrams.py
│ ├── is_pallindrome.cpp
│ ├── is_pallindrome.go
│ ├── is_pallindrome.java
│ ├── is_pallindrome.js
│ ├── is_pallindrome.py
│ ├── is_unique.cpp
│ ├── is_unique.go
│ ├── is_unique.java
│ ├── is_unique.js
│ ├── is_unique.py
│ ├── length_of_longest_substring.java
│ ├── longest palindromic substring.java
│ ├── longest_common_prefix.cpp
│ ├── longest_string.cpp
│ ├── one_edit.cpp
│ ├── one_edit.go
│ ├── one_edit.java
│ ├── one_edit.js
│ ├── one_edit.py
│ ├── plaindrome_str.cpp
│ ├── reverse_string.go
│ ├── reverse_words_in_a_string.cpp
│ ├── reverse_words_in_a_string.go
│ ├── reverse_words_in_a_string.js
│ ├── reverse_words_in_string.java
│ ├── valid_palindrome.js
│ ├── valid_pallindrome2.cpp
│ ├── valid_pallindrome2.go
│ ├── valid_pallindrome2.java
│ ├── valid_pallindrome2.js
│ ├── valid_pallindrome2.py
│ ├── well_formed_parentheses.cpp
│ ├── well_formed_parentheses.java
│ └── zigzag_conversion.cpp
├── Trees/
│ ├── AVL/
│ │ └── avl.go
│ ├── Binary Search Trees/
│ │ ├── Kth_Largest_Value_In_BST.py
│ │ ├── Kth_largest_BST.cpp
│ │ ├── Kth_largest_BST.java
│ │ ├── Kth_largest_BST.js
│ │ ├── Validate_BST.cpp
│ │ ├── Validate_BST.java
│ │ ├── Validate_BST.js
│ │ ├── Validate_BST.py
│ │ ├── bst.go
│ │ ├── find_closest_value.cpp
│ │ ├── find_closest_value.go
│ │ ├── find_closest_value.js
│ │ ├── find_closest_value.py
│ │ ├── insert_into_bst.cpp
│ │ ├── kth_largest.go
│ │ ├── min_height_BST.cpp
│ │ ├── min_height_BST.go
│ │ ├── min_height_BST.java
│ │ ├── min_height_BST.js
│ │ ├── min_height_BST.py
│ │ ├── reconstruct_bst.cpp
│ │ ├── reconstruct_bst.go
│ │ ├── reconstruct_bst.java
│ │ ├── reconstruct_bst.js
│ │ ├── reconstruct_bst.py
│ │ ├── search.cpp
│ │ └── validate_bst.go
│ ├── Binary Trees/
│ │ ├── Trie.js
│ │ ├── bfs.cpp
│ │ ├── bfs.go
│ │ ├── binary_tree.go
│ │ ├── branch_sum.go
│ │ ├── build_tree_preorder.cpp
│ │ ├── calculate_size.go
│ │ ├── count_nodes.cpp
│ │ ├── delete.go
│ │ ├── dfs.cpp
│ │ ├── dfs.go
│ │ ├── dfs.java
│ │ ├── dfs.js
│ │ ├── dfs.py
│ │ ├── diameter.cpp
│ │ ├── diameter.go
│ │ ├── diameter.java
│ │ ├── diameter.js
│ │ ├── diameter.py
│ │ ├── find_branch_sum.go
│ │ ├── find_max.go
│ │ ├── height.cpp
│ │ ├── height.go
│ │ ├── height_balanced_binary_tree.cpp
│ │ ├── height_balanced_binary_tree.go
│ │ ├── height_balanced_binary_tree.java
│ │ ├── height_balanced_binary_tree.js
│ │ ├── height_balanced_binary_tree.py
│ │ ├── inorder_traversal.cpp
│ │ ├── inorder_traversal.go
│ │ ├── inorder_traversal.java
│ │ ├── inorder_traversal.js
│ │ ├── inorder_traversal.py
│ │ ├── invert.cpp
│ │ ├── invert.go
│ │ ├── invert.java
│ │ ├── invert.js
│ │ ├── invert.py
│ │ ├── is_symmetric.cpp
│ │ ├── is_symmetric.go
│ │ ├── is_symmetric.java
│ │ ├── is_symmetric.js
│ │ ├── is_symmetric.py
│ │ ├── level_by_level.cpp
│ │ ├── level_order_traversal.cpp
│ │ ├── level_order_traversal.go
│ │ ├── node_depth.go
│ │ ├── postorder_traversal.cpp
│ │ ├── preorder_traversal.cpp
│ │ ├── remove_leaf_nodes.go
│ │ ├── search_an_element.go
│ │ └── sum_of_all_nodes.cpp
│ ├── Implement_Trie.cpp
│ ├── Implement_Trie.py
│ ├── MaxpathBinaryTree.cpp
│ ├── tree.go
│ ├── trie.cpp
│ ├── trie.go
│ └── trie.java
├── Tries/
│ ├── pattern_matching.cpp
│ ├── search_in_tries.cpp
│ └── trie_node_class.cpp
└── sorting/
├── Cyclic_Sort.java
├── bubble_sort.cpp
├── bubble_sort.go
├── bubble_sort.java
├── bubble_sort.js
├── bubble_sort.py
├── bucket-sort.js
├── bucket_sort.cpp
├── bucket_sort.go
├── bucket_sort.java
├── bucket_sort.js
├── count_sort.cpp
├── count_sort.java
├── count_sort.js
├── count_sort.py
├── dnf.cpp
├── dnf.go
├── dnf.java
├── dnf.js
├── dnf.py
├── heap_sort.cpp
├── heap_sort.java
├── heap_sort.js
├── heap_sort.py
├── insertion_sort.cpp
├── insertion_sort.go
├── insertion_sort.java
├── insertion_sort.js
├── insertion_sort.py
├── merge_sort.cpp
├── merge_sort.go
├── merge_sort.java
├── merge_sort.js
├── merge_sort.py
├── quick_sort.cpp
├── quick_sort.go
├── quick_sort.java
├── quick_sort.js
├── quick_sort.py
├── radix_sort.cpp
├── radix_sort.go
├── radix_sort.java
├── radix_sort.js
├── radix_sort.py
├── selection_sort.cpp
├── selection_sort.go
├── selection_sort.java
├── selection_sort.js
├── selection_sort.py
├── tim_sort.cpp
├── tim_sort.go
├── tim_sort.java
├── tim_sort.py
└── wave_sort.cpp
Showing preview only (234K chars total). Download the full file or copy to clipboard to get everything.
SYMBOL INDEX (2986 symbols across 852 files)
FILE: 2D Arrays (Matrix)/2D_sorted.go
function searchMatrix (line 1) | func searchMatrix(matrix [][]int, target int) bool {
FILE: 2D Arrays (Matrix)/binary_search.cpp
class Solution (line 18) | class Solution {
method costumBinarySearch (line 19) | bool costumBinarySearch(const vector<vector<int>>& matrix, int target,...
method searchMatrix (line 35) | bool searchMatrix(vector<vector<int>>& matrix, int target) {
FILE: 2D Arrays (Matrix)/count_negatives_in_sorted_matrix.cpp
class Solution (line 22) | class Solution {
method countNegatives (line 24) | int countNegatives(vector<vector<int>>& grid) {
FILE: 2D Arrays (Matrix)/matrix_diagonal_sum.cpp
class Solution (line 31) | class Solution {
method diagonalSum (line 33) | int diagonalSum(vector<vector<int>>& mat) {
FILE: 2D Arrays (Matrix)/matrix_wave_print.cpp
function wave_print (line 4) | void wave_print(int Mat[][10], int R, int C){
function main (line 18) | int main(){
FILE: 2D Arrays (Matrix)/rotate_matrix.cpp
function rotateClockwise (line 19) | void rotateClockwise(vector<vector<int>>& image) {
function rotateCounterclockwise (line 33) | void rotateCounterclockwise(vector<vector<int>>& image) {
function printImage (line 47) | void printImage(vector<vector<int>>& image) {
function main (line 57) | int main() {
FILE: 2D Arrays (Matrix)/rotate_matrix.go
function rotateClockwise (line 18) | func rotateClockwise(image [][]int) [][]int {
function rotateCounterClockwise (line 30) | func rotateCounterClockwise(image [][]int) [][]int {
function main (line 42) | func main() {
FILE: 2D Arrays (Matrix)/rotate_matrix.java
class RotateMatrix (line 11) | public class RotateMatrix {
method rotateClockwise (line 14) | public static int[][] rotateClockwise(int[][] matrix) {
method rotateAntiClockwise (line 28) | public static int[][] rotateAntiClockwise(int[][] matrix) {
method printMatrix (line 42) | public static void printMatrix(int[][] matrix) {
method main (line 52) | public static void main(String[] args) {
FILE: 2D Arrays (Matrix)/rotate_matrix.js
function rotateClockwise (line 13) | function rotateClockwise(matrix) {
function rotateAntiClockwise (line 36) | function rotateAntiClockwise(matrix) {
FILE: 2D Arrays (Matrix)/rotate_matrix.py
function rotate_clockwise (line 14) | def rotate_clockwise(matrix):
function rotate_counterclockwise (line 31) | def rotate_counterclockwise(matrix):
FILE: 2D Arrays (Matrix)/search_element.cpp
class Solution (line 18) | class Solution {
method searchMatrix (line 20) | bool searchMatrix(vector<vector<int>> &matrix,int target) {
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.cpp
function main (line 47) | int main(){
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.java
class Solution (line 33) | class Solution
method searchMatrix (line 35) | public boolean searchMatrix(int[][] matrix, int target)
method main (line 50) | public static void main(String[] args)
FILE: 2D Arrays (Matrix)/searching_in_sorted_array.py
class Solution (line 45) | class Solution(object):
method searchMatrix (line 46) | def searchMatrix(self, matrix, target):
FILE: 2D Arrays (Matrix)/set_matrix_0.cpp
function setZeroes (line 40) | void setZeroes(vector<vector<int>>& matrix) {
function printMatrix (line 64) | void printMatrix(const vector<vector<int>>& matrix) {
function main (line 73) | int main() {
FILE: 2D Arrays (Matrix)/set_matrix_0.go
function setZeroes (line 40) | func setZeroes(matrix [][]int) {
function main (line 64) | func main() {
function printMatrix (line 80) | func printMatrix(matrix [][]int) {
FILE: 2D Arrays (Matrix)/set_matrix_0.java
class setMatrixZero (line 44) | public class setMatrixZero {
method setZeroes_bruteForce (line 47) | private static void setZeroes_bruteForce(int[][] matrix, int n, int m) {
method setZeroes_optimalMethod (line 89) | private static void setZeroes_optimalMethod(int[][] matrix, int n, int...
method main (line 127) | public static void main(String[] args) {
FILE: 2D Arrays (Matrix)/spiral_traverse.cpp
function SpiralTraverse (line 38) | vector<int> SpiralTraverse(vector<vector<int>> array) {
function main (line 81) | int main() {
FILE: 2D Arrays (Matrix)/spiral_traverse.go
function SpiralTraverse (line 36) | func SpiralTraverse(array [][]int) []int {
function main (line 83) | func main() {
FILE: 2D Arrays (Matrix)/spiral_traverse.java
class SpiralTraverse (line 33) | public class SpiralTraverse {
method main (line 35) | public static void main(String[] args) {
method spiralFillUsingLoop (line 45) | public static List<Integer> spiralFillUsingLoop(int[][] array) {
method spiralFillUsingRecursion (line 109) | public static void spiralFillUsingRecursion(
FILE: 2D Arrays (Matrix)/spiral_traverse.py
function spiralOrder (line 52) | def spiralOrder(matrix):
FILE: 2D Arrays (Matrix)/zigzag_traversal.cpp
function ZigzagTraverse (line 56) | vector<int> ZigzagTraverse(vector<vector<int>>& array) {
function isOutOfBounds (line 118) | bool isOutOfBounds(int row, int col, int height, int width) {
FILE: 2D Arrays (Matrix)/zigzag_traversal.go
function ZigzagTraverse (line 54) | func ZigzagTraverse(array [][]int) []int {
function isOutOfBounds (line 114) | func isOutOfBounds(row, col, height, width int) bool {
FILE: 2D Arrays (Matrix)/zigzag_traversal.java
class Main (line 54) | public class Main {
method ZigzagTraverse (line 56) | public static List<Integer> ZigzagTraverse(int[][] array) {
method isOutOfBounds (line 118) | public static boolean isOutOfBounds(int row, int col, int height, int ...
method main (line 123) | public static void main(String[] args) {
FILE: 2D Arrays (Matrix)/zigzag_traversal.js
function ZigzagTraverse (line 51) | function ZigzagTraverse(array) {
function isOutOfBounds (line 113) | function isOutOfBounds(row, col, height, width) {
FILE: 2D Arrays (Matrix)/zigzag_traversal.py
function ZigzagTraverse (line 52) | def ZigzagTraverse(array):
function isOutOfBounds (line 106) | def isOutOfBounds(row, col, height, width):
FILE: Arrays/Jobassign.cpp
function main (line 8) | int main() {
function hungarianAlgorithm (line 21) | void hungarianAlgorithm(int costMatrix[N][N]) {
FILE: Arrays/Rotatedarr.cpp
class Solution (line 1) | class Solution {
method search (line 3) | int search(std::vector<int>& nums, int target) {
FILE: Arrays/array_of_products.cpp
function ArrayOfProducts (line 42) | vector<int> ArrayOfProducts(vector<int>& array) {
function main (line 65) | int main() {
FILE: Arrays/array_of_products.go
function ArrayOfProducts (line 39) | func ArrayOfProducts(array []int) []int {
FILE: Arrays/array_of_products.java
class ArrayOfProducts (line 36) | public class ArrayOfProducts {
method arrayOfProducts (line 37) | public static int[] arrayOfProducts(int[] array) {
method main (line 60) | public static void main(String[] args) {
FILE: Arrays/array_of_products.js
function arrayOfProducts (line 34) | function arrayOfProducts(array) {
FILE: Arrays/array_of_products.py
function array_of_products (line 34) | def array_of_products(array):
FILE: Arrays/ceaser_cipher.cpp
function string (line 52) | string CaesarCipherEncryptor(string str, int key) {
function main (line 75) | int main() {
FILE: Arrays/ceaser_cipher.go
function CaesarCipherEncryptor (line 50) | func CaesarCipherEncryptor(str string, key int) string {
FILE: Arrays/ceaser_cipher.java
class CaesarCipherEncryptor (line 49) | public class CaesarCipherEncryptor {
method encrypt (line 51) | public static String encrypt(String str, int key) {
method main (line 74) | public static void main(String[] args) {
FILE: Arrays/ceaser_cipher.js
function caesarCipherEncryptor (line 45) | function caesarCipherEncryptor(str, key) {
FILE: Arrays/ceaser_cipher.py
function caesar_cipher_encryptor (line 47) | def caesar_cipher_encryptor(str, key):
FILE: Arrays/dutch_national_flag.cpp
function sortColors (line 45) | void sortColors(vector<int> &nums)
function main (line 68) | int main()
FILE: Arrays/dutch_national_flag.go
function sortColors (line 42) | func sortColors(nums []int) {
function main (line 64) | func main() {
FILE: Arrays/dutch_national_flag.java
class Main (line 38) | public class Main {
method sortColors (line 39) | public static void sortColors(int[] nums) {
method main (line 65) | public static void main(String[] args) {
FILE: Arrays/dutch_national_flag.js
function sortColors (line 38) | function sortColors(nums) {
FILE: Arrays/dutch_national_flag.py
function sortColors (line 38) | def sortColors(nums):
FILE: Arrays/find_three_largest_integers.js
function findThreeLargestNumbers (line 34) | function findThreeLargestNumbers(array) {
function updateLargest (line 48) | function updateLargest(triplets, num) {
function shiftAndUpdate (line 66) | function shiftAndUpdate(triplets, num, idx) {
FILE: Arrays/find_three_largest_number.cpp
function main (line 49) | int main() {
function findThreeLargestNumbers (line 64) | vector<int> findThreeLargestNumbers(vector<int>& array) {
function updateLargest (line 77) | void updateLargest(vector<int>& triplets, int num) {
function shiftAndUpdate (line 90) | void shiftAndUpdate(vector<int>& triplets, int num, int idx) {
FILE: Arrays/find_three_largest_numbers.go
function FindThreeLargestNumbers (line 39) | func FindThreeLargestNumbers(array []int) []int {
function updateLargest (line 50) | func updateLargest(triplets []int, num int) {
function shiftAndUpdate (line 64) | func shiftAndUpdate(triplets []int, num int, idx int) {
FILE: Arrays/find_three_largest_numbers.java
class Main (line 37) | public class Main {
method findThreeLargestNumbers (line 39) | public static int[] findThreeLargestNumbers(int[] array) {
method updateLargest (line 54) | private static void updateLargest(int[] triplets, int num) {
method shiftAndUpdate (line 73) | private static void shiftAndUpdate(int[] triplets, int num, int idx) {
method main (line 88) | public static void main(String[] args) {
FILE: Arrays/find_three_largest_numbers.py
function find_three_largest_numbers (line 35) | def find_three_largest_numbers(array):
function update_largest (line 48) | def update_largest(triplets, num):
function shift_and_update (line 63) | def shift_and_update(triplets, num, idx):
FILE: Arrays/first_duplicate_value.cpp
class Solution (line 14) | class Solution{
method findDuplicate1 (line 17) | int findDuplicate1(vector<int>& nums)
method findDuplicate2 (line 33) | int findDuplicate2(vector<int>& nums)
FILE: Arrays/first_duplicate_value.go
function FirstDuplicateValue (line 41) | func FirstDuplicateValue(array []int) int {
function FirstDuplicateValue2 (line 83) | func FirstDuplicateValue2(array []int) int {
function abs (line 104) | func abs(num int) int {
function main (line 111) | func main() {
FILE: Arrays/first_duplicate_value.java
method findDuplicate (line 18) | public static int findDuplicate(int[] nums) {
method findDuplicate (line 37) | public static int findDuplicate(int[] nums) {
FILE: Arrays/first_duplicate_value.js
function findFirstDuplicate (line 17) | function findFirstDuplicate(nums){
function findFirstDuplicate (line 37) | function findFirstDuplicate(nums){
FILE: Arrays/first_duplicate_value.py
function find_duplicate (line 13) | def find_duplicate(nums):
FILE: Arrays/four_sum.py
class Solution (line 39) | class Solution:
method fourSum (line 40) | def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
FILE: Arrays/insert_interval.cpp
type Interval (line 44) | struct Interval {
method Interval (line 48) | Interval(int s, int e) : start(s), end(e) {}
function insertInterval (line 51) | vector<Interval> insertInterval(vector<Interval>& intervals, Interval ne...
function printIntervals (line 84) | void printIntervals(const vector<Interval>& intervals) {
function main (line 91) | int main() {
FILE: Arrays/insert_interval.go
type Interval (line 45) | type Interval struct
function insert (line 51) | func insert(intervals []Interval, newInterval Interval) []Interval {
function min (line 81) | func min(a, b int) int {
function max (line 89) | func max(a, b int) int {
function main (line 96) | func main() {
FILE: Arrays/insert_interval.java
class Interval (line 41) | class Interval {
method Interval (line 45) | Interval(int start, int end) {
class InsertInterval (line 51) | public class InsertInterval {
method insertInterval (line 52) | public static List<Interval> insertInterval(List<Interval> intervals, ...
method printIntervals (line 85) | public static void printIntervals(List<Interval> intervals) {
method main (line 92) | public static void main(String[] args) {
FILE: Arrays/insert_interval.js
class Interval (line 38) | class Interval {
method constructor (line 39) | constructor(start, end) {
function insertInterval (line 45) | function insertInterval(intervals, newInterval) {
FILE: Arrays/insert_interval.py
class Interval (line 38) | class Interval:
method __init__ (line 39) | def __init__(self, start, end):
function insertInterval (line 43) | def insertInterval(intervals, newInterval):
FILE: Arrays/insert_intervals.cpp
class Solution (line 14) | class Solution {
method insert (line 16) | vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>...
FILE: Arrays/insert_intervals.go
function insert (line 53) | func insert(intervals [][]int, newInterval []int) [][]int {
function main (line 85) | func main() {
FILE: Arrays/is_monotonic.cpp
function IsMonotonic (line 25) | bool IsMonotonic(vector<int>& array) {
function main (line 45) | int main() {
FILE: Arrays/is_monotonic.go
function IsMonotonic (line 25) | func IsMonotonic(array []int) bool {
function main (line 44) | func main() {
FILE: Arrays/is_monotonic.java
class Main (line 20) | public class Main {
method isMonotonic (line 21) | public static boolean isMonotonic(int[] array) {
method main (line 38) | public static void main(String[] args) {
FILE: Arrays/is_monotonic.js
function isMonotonic (line 20) | function isMonotonic(array) {
FILE: Arrays/is_monotonic.py
function is_monotonic (line 20) | def is_monotonic(array):
FILE: Arrays/longest_peak.cpp
function LongestPeak (line 37) | int LongestPeak(std::vector<int>& array) {
FILE: Arrays/longest_peak.go
function LongestPeak (line 40) | func LongestPeak(array []int) int {
function main (line 78) | func main() {
FILE: Arrays/longest_peak.js
function longestPeak (line 35) | function longestPeak(array) {
FILE: Arrays/longest_peak.py
function longest_peak (line 37) | def longest_peak(array):
function longestPeak (line 82) | def longestPeak(arr: list) -> int:
FILE: Arrays/majority_element.go
function MajorityElement (line 72) | func MajorityElement(nums []int) int {
function main (line 87) | func main() {
FILE: Arrays/majority_element.java
class Solution (line 15) | class Solution {
method majorityElement (line 16) | public int majorityElement(int[] nums) {
FILE: Arrays/maximum_subarray_sum.cpp
function maxSubArraySum (line 38) | int maxSubArraySum(vector<int>& nums) {
function maxSubarraySumBruteForce (line 63) | int maxSubarraySumBruteForce(vector<int>& nums) {
function main (line 80) | int main() {
FILE: Arrays/maximum_subarray_sum.go
function maxSubarraySum (line 42) | func maxSubarraySum(arr []int) int {
function maxSubarraySumBruteForce (line 66) | func maxSubarraySumBruteForce(nums []int) int {
function main (line 89) | func main() {
FILE: Arrays/maximum_subarray_sum.py
function max_subarray_sum (line 27) | def max_subarray_sum(arr):
FILE: Arrays/merge_intervals.cpp
class Solution (line 12) | class Solution {
method merge (line 14) | vector<vector<int>> merge(vector<vector<int>>& intervals) {
FILE: Arrays/merge_intervals.go
function MergeOverlappingIntervals (line 32) | func MergeOverlappingIntervals(intervals [][]int) [][]int {
function max (line 81) | func max(a, b int) int {
FILE: Arrays/merge_intervals.js
function merge (line 35) | function merge(intervals) {
FILE: Arrays/merge_intervals.py
class Solution (line 34) | class Solution(object):
method mergeIntervals (line 35) | def mergeIntervals(self, Intervals):
FILE: Arrays/merge_sorted_array.cpp
function merge (line 27) | void merge( vector < int > & nums1 , int m , vector< int > & nums2 , int...
function merge (line 53) | void merge( vector< int > & nums1 , int m , vector< int > & nums2 , int ...
FILE: Arrays/merge_sorted_array.java
class merge_sorted_array (line 13) | class merge_sorted_array{
method merge (line 15) | public void merge(int[] nums1, int m, int[] nums2, int n){
method main (line 27) | public static void main(String[] args){
FILE: Arrays/merge_sorted_arrays.py
class Solution (line 1) | class Solution:
method merge (line 2) | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) ->...
FILE: Arrays/minimum_size_subarray_sum.java
class MinimumSizeSubarraySum (line 29) | public class MinimumSizeSubarraySum {
method main (line 30) | public static void main(String[] args) {
method solve (line 37) | public static int solve(int[] nums, int target) {
FILE: Arrays/move_element_to_end.cpp
function MoveElementToEnd (line 25) | std::vector<int> MoveElementToEnd(std::vector<int>& array, int toMove) {
FILE: Arrays/move_element_to_end.go
function MoveElementToEnd (line 25) | func MoveElementToEnd(array []int, toMove int) []int {
FILE: Arrays/move_element_to_end.java
class MoveElementToEnd (line 26) | public class MoveElementToEnd {
method moveElementToEnd (line 27) | public static List<Integer> moveElementToEnd(List<Integer> array, int ...
FILE: Arrays/move_element_to_end.js
function moveElementToEnd (line 23) | function moveElementToEnd(array, toMove) {
FILE: Arrays/move_element_to_end.py
function move_element_to_end (line 23) | def move_element_to_end(array, to_move):
FILE: Arrays/non-overlapping intervals.cpp
class Solution (line 26) | class Solution {
method eraseOverlapIntervals (line 28) | int eraseOverlapIntervals(vector<vector<int>>& intervals) {
FILE: Arrays/pallindromic_permutations.cpp
function is_permutation_pallindrome (line 6) | bool is_permutation_pallindrome(string s){
function is_permutation_pallindrome_improved (line 25) | bool is_permutation_pallindrome_improved(string s){
function print_ans (line 43) | void print_ans(bool ans){
function main (line 51) | int main(){
FILE: Arrays/sign_of_the_product_of_an_array.cpp
function arraySign (line 60) | int arraySign(vector<int> &nums)
function main (line 81) | int main()
FILE: Arrays/smallest_difference.cpp
function SmallestDifference (line 37) | vector<int> SmallestDifference(vector<int> array1, vector<int> array2) {
function main (line 73) | int main() {
FILE: Arrays/smallest_difference.go
function SmallestDifference (line 46) | func SmallestDifference(array1, array2 []int) []int {
FILE: Arrays/smallest_difference.java
class Main (line 38) | public class Main {
method smallestDifference (line 40) | public static int[] smallestDifference(int[] array1, int[] array2) {
method main (line 86) | public static void main(String[] args) {
FILE: Arrays/smallest_difference.js
function smallestDifference (line 32) | function smallestDifference(array1, array2) {
FILE: Arrays/smallest_difference.py
function smallest_difference (line 26) | def smallest_difference(array1: List[int], array2: List[int]) -> List[int]:
function main (line 75) | def main():
FILE: Arrays/sorted_square_array.cpp
function sortedSquaredArray (line 42) | std::vector<int> sortedSquaredArray(std::vector<int>& array) {
function main (line 71) | int main() {
FILE: Arrays/sorted_square_array.go
function SortedSquaredArray (line 43) | func SortedSquaredArray(array []int) []int {
function main (line 69) | func main() {
FILE: Arrays/sorted_square_array.java
class Main (line 41) | public class Main {
method sortedSquaredArray (line 43) | public static int[] sortedSquaredArray(int[] array) {
method main (line 72) | public static void main(String[] args) {
FILE: Arrays/sorted_square_array.py
function sortedSquaredArray (line 39) | def sortedSquaredArray(array):
FILE: Arrays/string_halves.cpp
class Solution (line 31) | class Solution {
method halvesAreAlike (line 33) | bool halvesAreAlike(string s) {
FILE: Arrays/three_largest_no.py
function three_max_no (line 21) | def three_max_no(arr:list)-> list:
FILE: Arrays/total_hamming_distance.cpp
function totalHammingDistance (line 80) | int totalHammingDistance(vector<int>& nums) {
function main (line 96) | int main()
FILE: Arrays/tournament_winner.go
constant HOME_TEAM_WON (line 44) | HOME_TEAM_WON = 1
constant AWAY_TEAM_WON (line 45) | AWAY_TEAM_WON = 0
function TournamentWinner (line 47) | func TournamentWinner(competitions [][]string, results []int) string {
function main (line 74) | func main() {
FILE: Arrays/triplet_sum.cpp
function threeNumberSum (line 21) | std::vector<std::vector<int>> threeNumberSum(std::vector<int>& nums, int...
function main (line 56) | int main() {
FILE: Arrays/triplet_sum.go
function findSumOfThree (line 18) | func findSumOfThree(nums []int, target int) bool {
function main (line 55) | func main() {
FILE: Arrays/triplet_sum.java
class ThreeNumberSum (line 23) | public class ThreeNumberSum {
method threeNumberSum (line 25) | public static List<List<Integer>> threeNumberSum(int[] nums, int targe...
method main (line 58) | public static void main(String[] args) {
FILE: Arrays/triplet_sum.py
function find3Numbers (line 7) | def find3Numbers(A, arr_size, sum):
FILE: Arrays/urlify.go
function Urlify (line 9) | func Urlify(s string, length int) string {
function main (line 41) | func main() {
FILE: Backtracking/Generate_Parentheses.py
class Solution (line 13) | class Solution:
method generate (line 17) | def generate(self,n,open,close,s,final_arr):
method generateParenthesis (line 26) | def generateParenthesis(self, n: int) -> List[str]:
FILE: Backtracking/geenrate_parentheses.go
function generateParenthesis (line 50) | func generateParenthesis(n int) []string {
function backtrack (line 57) | func backtrack(result *[]string, cur string, open int, close int, max in...
function main (line 75) | func main() {
FILE: Backtracking/n_queen.cpp
function isSafe (line 7) | bool isSafe(vector<string>& board, int row, int col, int N) {
function solveNQueens (line 33) | bool solveNQueens(vector<string>& board, int col, int N) {
function solveNQueens (line 59) | void solveNQueens(int N) {
function main (line 72) | int main() {
FILE: Backtracking/n_queens.java
class Solution (line 32) | class Solution {
method solveNQueens (line 33) | public List<List<String>> solveNQueens(int n) {
method queens (line 56) | static void queens(boolean board[][], int row, List<List<String>> list) {
method isSafe (line 86) | private static boolean isSafe(boolean[][] board, int row, int col) {
FILE: Backtracking/sudoko_solver.java
class sudokoSolver (line 22) | public class sudokoSolver {
method solveSudoku (line 25) | public void solveSudoku(char[][] board) {
method Solver (line 29) | static boolean Solver(char[][] board , int total)
method print (line 57) | static void print(char[][] board)
method canElementBePlaced (line 69) | static boolean canElementBePlaced(char[][] board , int r , int c , cha...
FILE: Binary Search/BinarySearchRecursive.java
class BinarySearchRecursive (line 22) | public class BinarySearchRecursive {
method main (line 24) | public static void main(String[] args) {
method binarySearch (line 30) | static int binarySearch(int[] arr ,int target, int start , int end) {
FILE: Binary Search/binary_search.cpp
function binarySearch (line 22) | int binarySearch(vector<int> arr, int target) {
function main (line 49) | int main() {
FILE: Binary Search/binary_search.py
function binary_search (line 22) | def binary_search(lst, target):
FILE: Binary Search/binary_search_iterative.go
function BinarySearch (line 15) | func BinarySearch(array []int, target int) int {
function main (line 39) | func main() {
FILE: Binary Search/binary_search_recursive.go
function BinarySearchRecursive (line 19) | func BinarySearchRecursive(Arr []int, key int) bool {
function main (line 35) | func main() {
FILE: Binary Search/binary_serach_first_and_last_occurence.py
class Solution (line 1) | class Solution:
method __init__ (line 2) | def __init__(self):
method binarySearchLast (line 21) | def binarySearchLast(self,arr,low,high,target):
method searchRange (line 33) | def searchRange(self, nums: List[int], target: int) -> List[int]:
FILE: Binary Search/first_and_last_pos_of_element.cpp
class Solution (line 33) | class Solution {
method get_index (line 35) | int get_index(vector<int>& nums, int target, bool found){
method searchRange (line 58) | vector<int> searchRange(vector<int>& nums, int target) {
FILE: Binary Search/first_and_last_position.java
class FirstandLastPosition (line 21) | class FirstandLastPosition {
method searchRange (line 22) | public int[] searchRange(int[] nums, int target) {
method firstPos (line 33) | private int firstPos(int[] arr,int target){
method lastPos (line 51) | private int lastPos(int[] arr,int target,int low){
FILE: Binary Search/first_last_pos.java
class FirstLastPos (line 18) | public class FirstLastPos{
method firstOccurence (line 19) | public static int firstOccurence(int[] arr,int target){
method lastOccurence (line 41) | public static int lastOccurence(int[] arr,int target){
method main (line 63) | public static void main(String[] args){
FILE: Binary Search/first_occurance.go
function FirstOccurance (line 9) | func FirstOccurance(Arr []int, key int) int {
function main (line 26) | func main() {
FILE: Binary Search/first_occurence.java
class FirstOccurence (line 27) | public class FirstOccurence{
method firstOccurence (line 28) | public static int firstOccurence(int[] arr,int target){
method main (line 50) | public static void main(String[] args){
FILE: Binary Search/first_true.cpp
function findBoundary (line 14) | int findBoundary(std::vector<bool>& arr) {
function main (line 39) | int main() {
FILE: Binary Search/first_true.go
function findBoundary (line 18) | func findBoundary(arr []bool) int {
function main (line 43) | func main() {
FILE: Binary Search/first_true.java
class Solution (line 16) | class Solution {
method findBoundary (line 17) | public static int findBoundary(List<Boolean> arr) {
FILE: Binary Search/first_true.js
function findBoundary (line 11) | function findBoundary(arr) {
FILE: Binary Search/first_true.py
function findBoundary (line 11) | def findBoundary(arr):
FILE: Binary Search/floor_of_target.java
class FloorOfTarget (line 19) | public class FloorOfTarget{
method search_floor (line 21) | public static int search_floor(int[] nums,int target){
method main (line 37) | public static void main(String[] args){
FILE: Binary Search/index_position.java
class IndexPosition (line 17) | public class IndexPosition {
method search (line 20) | public static int search(int[] nums, int target) {
method main (line 39) | public static void main(String[] args){
FILE: Binary Search/infinity_array.java
class InfinityArray (line 15) | public class InfinityArray {
method main (line 16) | public static void main(String[] args){
method range (line 22) | public static int range(int[] nums,int target){
method search (line 31) | public static int search(int[] nums, int target,int start,int end) {
FILE: Binary Search/last_occurance.go
function LastOccurance (line 9) | func LastOccurance(Arr []int, key int) int {
function main (line 26) | func main() {
FILE: Binary Search/median_of_two_sorted_arrays.cpp
class Solution (line 32) | class Solution {
method findMedianSortedArrays (line 34) | double findMedianSortedArrays(std::vector<int>& nums1, std::vector<int...
function main (line 68) | int main(int argc, char const *argv[])
FILE: Binary Search/median_of_two_sorted_arrays.js
function findMedianSortedArrays (line 26) | function findMedianSortedArrays(arr1, arr2) {
function findMedianSortedArrays (line 39) | function findMedianSortedArrays(arr1, arr2) {
FILE: Binary Search/minimum_in_rotated_sorted_array.cpp
class Solution (line 35) | class Solution {
method findMin (line 37) | int findMin(vector<int>& nums) {
FILE: Binary Search/perfect_square.java
class PerfectSquare (line 23) | class PerfectSquare {
method isPerfectSquare (line 24) | public static boolean isPerfectSquare(int num) {
method main (line 41) | public static void main(String[] args){
FILE: Binary Search/search_in_rotated_sorted_array.cpp
class Solution (line 31) | class Solution {
method search (line 33) | int search(vector<int>& nums, int target) {
FILE: Binary Search/search_in_sorted_rotated_array.cpp
class Solution (line 31) | class Solution {
method search (line 33) | int search(vector<int>& nums, int target) {
FILE: Binary Search/search_in_sorted_rotated_array.go
function SearchInSortedMatrix (line 33) | func SearchInSortedMatrix(matrix [][]int, target int) []int {
function main (line 57) | func main() {
FILE: Binary Search/search_in_sorted_rotated_array.java
class searchInRotatedArray (line 26) | public class searchInRotatedArray {
method searchTarget (line 30) | public static int searchTarget(int nums[] , int target)
method search (line 44) | public static int search(int nums[], int l, int h, int target)
method main (line 92) | public static void main(String[] args)
FILE: Binary Search/search_in_sorted_rotated_array.py
class Solution (line 25) | class Solution:
method binarySearch (line 26) | def binarySearch(nums,low,high,target):
method search (line 37) | def search(self, nums: List[int], target: int) -> int:
FILE: Binary Search/search_insert_position.js
function findSearchPosition (line 30) | function findSearchPosition(nums, target) {
FILE: Binary Search/square_root.java
class SquareRoot (line 21) | public class SquareRoot{
method sqrt (line 22) | public static int sqrt(int x){
method main (line 39) | public static void main(String[] args){
FILE: Bit Manipulation/bloom_filter.cpp
function h1 (line 30) | int h1(std::string s, int arrSize)
function h2 (line 43) | int h2(std::string s, int arrSize)
function h3 (line 56) | int h3(std::string s, int arrSize)
function h4 (line 68) | int h4(std::string s, int arrSize)
function lookup (line 82) | bool lookup(std::bitset<1000000> &bitarray, std::string s)
function insert (line 94) | void insert(std::bitset<1000000> &bitarray, std::string s)
function main (line 117) | int main()
FILE: Bit Manipulation/bloom_filter.py
class BloomFilter (line 32) | class BloomFilter:
method __init__ (line 33) | def __init__(self, capacity, false_positive_rate):
method calculate_size (line 41) | def calculate_size(self):
method calculate_num_hashes (line 47) | def calculate_num_hashes(self):
method add (line 52) | def add(self, item):
method contains (line 59) | def contains(self, item):
FILE: Bit Manipulation/count_bits.go
function CountBits (line 12) | func CountBits(x int) (int, error) {
function main (line 24) | func main() {
FILE: Bit Manipulation/interesting_array.java
class InterestingArray (line 5) | public class InterestingArray {
method main (line 6) | public static void main(String[] args) {
method solve (line 16) | public static String solve(int[] array) {
FILE: Bit Manipulation/mod_array.java
class ModArray (line 98) | public class ModArray {
method main (line 99) | public static void main(String[] args) {
method solve (line 105) | public static int solve(int[] array, int divisor) {
FILE: Bit Manipulation/number_of_1_bits.java
class NumberOf1Bits (line 40) | public class NumberOf1Bits {
method main (line 41) | public static void main(String[] args) {
method solve (line 46) | public static int solve(int num) {
FILE: Bit Manipulation/parity_of_a_word.go
function Parity (line 17) | func Parity(x int) int {
function ParityImproved (line 26) | func ParityImproved(x int) int {
function main (line 36) | func main() {
FILE: Bit Manipulation/power_of_2.cpp
class Solution (line 29) | class Solution {
method isPowerOfTwo (line 31) | bool isPowerOfTwo(int n) {
FILE: Bit Manipulation/reduce_to_zero.cpp
class Solution (line 40) | class Solution {
method numberOfSteps (line 42) | int numberOfSteps (int num) {
FILE: Bit Manipulation/setbits.cpp
function find_set_bits (line 7) | int find_set_bits(int n){
function main (line 15) | int main(){
FILE: Bit Manipulation/single_number.java
class SingleNumber (line 55) | public class SingleNumber {
method main (line 56) | public static void main(String[] args) {
method solve (line 65) | public static int solve(int[] array) {
FILE: Bit Manipulation/subarrays_with_bitwise_OR_1.java
class subArrayWithBitwiseOR1 (line 46) | public class subArrayWithBitwiseOR1 {
method main (line 47) | public static void main(String[] args) {
method solve (line 53) | public static int solve(int[] array, int len) {
FILE: Dynamic Programming/best_time_to_buy_and_sell_stock.cpp
function maxProfit (line 22) | int maxProfit(vector<int>& prices) {
function main (line 34) | int main() {
FILE: Dynamic Programming/best_time_to_buy_and_sell_stock.go
function maxProfit (line 23) | func maxProfit(prices []int) int {
function main (line 36) | func main() {
FILE: Dynamic Programming/best_time_to_buy_and_sell_stock.java
class Solution (line 16) | public class Solution {
method maxProfit (line 17) | public int maxProfit(int[] prices) {
method main (line 37) | public static void main(String[] args) {
FILE: Dynamic Programming/best_time_to_buy_and_sell_stock.py
function maxProfit (line 20) | def maxProfit(prices: List[int]) -> int:
FILE: Dynamic Programming/climb_stairs.cpp
function climbStairs (line 9) | int climbStairs(int n) {
function climbStairsVariation (line 28) | int climbStairsVariation(int n) {
function main (line 45) | int main() {
FILE: Dynamic Programming/climb_stairs.go
function ClimbStairs (line 10) | func ClimbStairs(n int) int {
function ClimbStairs2 (line 28) | func ClimbStairs2(n int) int {
function main (line 42) | func main() {
FILE: Dynamic Programming/climb_stairs.java
class StairClimbing (line 3) | public class StairClimbing {
method climbStairs (line 7) | public static int climbStairs(int n) {
method climbStairsVariation (line 26) | public static int climbStairsVariation(int n) {
method main (line 43) | public static void main(String[] args) {
FILE: Dynamic Programming/climb_stairs.js
function climbStairs (line 7) | function climbStairs(n) {
function climbStairsVariation (line 26) | function climbStairsVariation(n) {
FILE: Dynamic Programming/climb_stairs.py
function climb_stairs (line 8) | def climb_stairs(n):
function climb_stairs_variation (line 23) | def climb_stairs_variation(n):
FILE: Dynamic Programming/coin_change.cpp
function coinChange (line 33) | int coinChange(vector<int>& coins, int amount) {
function main (line 60) | int main() {
FILE: Dynamic Programming/coin_change.go
function coinChange (line 38) | func coinChange(coins []int, amount int) int {
function min (line 71) | func min(a, b int) int {
function main (line 78) | func main() {
FILE: Dynamic Programming/coin_change.java
class Solution (line 52) | class Solution {
method coinChange (line 53) | public int coinChange(int[] coins, int amount) {
FILE: Dynamic Programming/coin_change.py
function coin_change (line 21) | def coin_change(coins, amount):
FILE: Dynamic Programming/dice_throws.go
function DiceThrows (line 51) | func DiceThrows(numDice int, numSides int, target int) int {
function diceThrowsHelper (line 67) | func diceThrowsHelper(numDice, numSides, target int, storedResults [][]i...
function max (line 99) | func max(a, b int) int {
FILE: Dynamic Programming/disk_stacking.go
type Disk (line 67) | type Disk
type Disks (line 70) | type Disks
method Len (line 73) | func (disks Disks) Len() int { return len(disks) }
method Swap (line 74) | func (disks Disks) Swap(i, j int) { disks[i], disks[j] = disks[j]...
method Less (line 75) | func (disks Disks) Less(i, j int) bool { return disks[i][2] < disks[j]...
function DiskStacking (line 78) | func DiskStacking(input [][]int) [][]int {
function areValidDimensions (line 127) | func areValidDimensions(o Disk, c Disk) bool {
function buildSequence (line 132) | func buildSequence(disks []Disk, sequences []int, index int) [][]int {
function reverse (line 144) | func reverse(numbers [][]int) {
FILE: Dynamic Programming/disk_stacking.py
function DiskStacking (line 62) | def DiskStacking(disks):
function are_valid_dimensions (line 89) | def are_valid_dimensions(other_disk, current_disk):
function build_sequence (line 93) | def build_sequence(disks, sequences, index):
FILE: Dynamic Programming/distance_of_nearest_0.cpp
class Solution (line 59) | class Solution
method updateMatrix (line 62) | vector<vector<int>> updateMatrix(vector<vector<int>> &mat)
function main (line 114) | int main()
FILE: Dynamic Programming/distance_of_nearest_0.py
class Solution (line 49) | class Solution:
method updateMatrix (line 50) | def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
FILE: Dynamic Programming/distane_of_nearest_0.go
function updateMatrix (line 30) | func updateMatrix(mat [][]int) [][]int {
FILE: Dynamic Programming/distane_of_nearest_0.java
class Solution (line 23) | class Solution {
method updateMatrix (line 26) | public int[][] updateMatrix(int[][] mat) {
FILE: Dynamic Programming/distane_of_nearest_0.js
function updateMatrix (line 23) | function updateMatrix(mat) {
FILE: Dynamic Programming/edit_distance_dp.cpp
function find_edit_distance (line 18) | int find_edit_distance(string s1, string s2, int l1, int l2){
function main (line 55) | int main(){
FILE: Dynamic Programming/edit_distance_dp.go
function findEditDistance (line 20) | func findEditDistance(s1, s2 string) int {
function main (line 62) | func main() {
FILE: Dynamic Programming/edit_distance_dp.java
class EditDistance (line 13) | public class EditDistance {
method findEditDistance (line 16) | public static int findEditDistance(String s1, String s2) {
method main (line 56) | public static void main(String[] args) {
FILE: Dynamic Programming/edit_distance_dp.js
function findEditDistance (line 14) | function findEditDistance(s1, s2) {
FILE: Dynamic Programming/edit_distance_dp.py
function find_edit_distance (line 15) | def find_edit_distance(s1, s2):
FILE: Dynamic Programming/edit_distance_memoized.cpp
function find_edit_distance (line 18) | int find_edit_distance(string s1, string s2, int l1, int l2){
function main (line 34) | int main(){
FILE: Dynamic Programming/edit_distance_recursive.cpp
function find_edit_distance (line 17) | int find_edit_distance(string s1, string s2, int l1, int l2){
function main (line 31) | int main(){
FILE: Dynamic Programming/house_robber.cpp
class Solution (line 30) | class Solution {
method rob (line 32) | int rob(vector<int>& nums) {
FILE: Dynamic Programming/juice_bottling.cpp
function juiceBottling (line 33) | std::vector<int> juiceBottling(std::vector<int>& prices) {
function main (line 65) | int main() {
FILE: Dynamic Programming/juice_bottling.go
function JuiceBottling (line 31) | func JuiceBottling(prices []int) []int {
FILE: Dynamic Programming/juice_bottling.java
class JuiceBottling (line 33) | public class JuiceBottling {
method juiceBottling (line 35) | public static List<Integer> juiceBottling(int[] prices) {
method main (line 67) | public static void main(String[] args) {
FILE: Dynamic Programming/juice_bottling.js
function juiceBottling (line 29) | function juiceBottling(prices) {
FILE: Dynamic Programming/juice_bottling.py
function juice_bottling (line 28) | def juice_bottling(prices):
FILE: Dynamic Programming/knapsack.cpp
function knapsackProblem (line 75) | vector<int> knapsackProblem(vector<vector<int>>& items, int capacity) {
function getKnapSackItems (line 112) | vector<int> getKnapSackItems(vector<vector<int>>& values, vector<vector<...
FILE: Dynamic Programming/knapsack.go
function KnapsackProblem (line 72) | func KnapsackProblem(items [][]int, capacity int) []interface{} {
function getKnapSackItems (line 110) | func getKnapSackItems(values [][]int, items [][]int) []int {
function max (line 140) | func max(a, b int) int {
function reverse (line 148) | func reverse(numbers []int) {
FILE: Dynamic Programming/knapsack.java
class KnapsackProblem (line 73) | public class KnapsackProblem {
method knapsackProblem (line 74) | public static List<Object> knapsackProblem(int[][] items, int capacity) {
method getKnapSackItems (line 112) | private static List<Integer> getKnapSackItems(int[][] values, int[][] ...
method max (line 143) | private static int max(int a, int b) {
method reverseList (line 148) | private static void reverseList(List<Integer> list) {
FILE: Dynamic Programming/knapsack.js
function KnapsackProblem (line 70) | function KnapsackProblem(items, capacity) {
function getKnapSackItems (line 110) | function getKnapSackItems(values, items) {
function max (line 141) | function max(a, b) {
FILE: Dynamic Programming/knapsack.py
function knapsack_problem (line 70) | def knapsack_problem(items, capacity):
function get_knapsack_items (line 101) | def get_knapsack_items(values, items):
FILE: Dynamic Programming/knight_probability_chessboard.cpp
class Solution (line 32) | class Solution {
method knightProbability (line 34) | double knightProbability(int n, int k, int row, int column) {
method dfs (line 42) | double dfs(int n, int k, int row, int column, vector<vector<vector<dou...
function main (line 74) | int main() {
FILE: Dynamic Programming/knight_probability_chessboard.go
function knightProbability (line 27) | func knightProbability(n int, k int, row int, column int) float64 {
FILE: Dynamic Programming/knight_probability_chessboard.java
class KnightProbability (line 27) | public class KnightProbability {
method knightProbability (line 28) | public double knightProbability(int n, int k, int row, int column) {
method dfs (line 36) | private double dfs(int n, int k, int row, int column, double[][][] dp) {
method main (line 67) | public static void main(String[] args) {
FILE: Dynamic Programming/knight_probability_chessboard.py
class Solution (line 27) | class Solution:
method knightProbability (line 28) | def knightProbability(self, n: int, k: int, row: int, column: int) -> ...
FILE: Dynamic Programming/kth_closest_point_to origin.java
class Solution (line 51) | class Solution {
method kClosest (line 53) | public int[][] kClosest(int[][] points, int k) {
FILE: Dynamic Programming/largest_rectangle.java
class Solution (line 44) | public class Solution {
method maxArea (line 45) | public static int maxArea(int[][] matrix, int rows, int cols) {
method main (line 77) | public static void main(String[] args) {
FILE: Dynamic Programming/largest_rectangle.py
class Solution (line 42) | class Solution:
method maxArea (line 43) | def maxArea(self,matrix, rows, cols):
FILE: Dynamic Programming/longest_common_subsequence_dp.cpp
function find_longest_common_subsequence (line 7) | int find_longest_common_subsequence(string a, string b, int n, int m, in...
function main (line 30) | int main(){
FILE: Dynamic Programming/longest_common_subsequence_memoization.cpp
function get_max (line 14) | int get_max(int x, int y){
function find_longest_common_subsequence (line 17) | int find_longest_common_subsequence(string a, string b, int n, int m, in...
function main (line 35) | int main(){
FILE: Dynamic Programming/longest_common_subsequence_recursive.cpp
function get_max (line 11) | int get_max(int x, int y){
function find_longest_common_subsequence (line 14) | int find_longest_common_subsequence(string a, string b, int n, int m){
function main (line 32) | int main(){
FILE: Dynamic Programming/longest_increasing_subsequence.cpp
function find_longest_increasing_subsequence (line 11) | int find_longest_increasing_subsequence(vector<int> V, int n){
function main (line 26) | int main(){
FILE: Dynamic Programming/longest_pallindromic_substring.cpp
function longestPalindromicSubstring (line 23) | int longestPalindromicSubstring(const std::string& Array) {
function main (line 57) | int main() {
FILE: Dynamic Programming/longest_pallindromic_substring.go
function LongestPalindromicSubstring (line 25) | func LongestPalindromicSubstring(Array string) int {
function main (line 63) | func main() {
FILE: Dynamic Programming/longest_pallindromic_substring.java
class LongestPalindromicSubstring (line 18) | public class LongestPalindromicSubstring {
method longestPalindromicSubstring (line 20) | public static int longestPalindromicSubstring(String Array) {
method main (line 54) | public static void main(String[] args) {
FILE: Dynamic Programming/longest_pallindromic_substring.js
function longestPalindromicSubstring (line 18) | function longestPalindromicSubstring(Array) {
FILE: Dynamic Programming/longest_pallindromic_substring.py
function longest_palindromic_substring (line 18) | def longest_palindromic_substring(Array):
FILE: Dynamic Programming/max_path_sum.go
type treenode (line 38) | type treenode struct
function pathMaxSum (line 45) | func pathMaxSum(root *treenode) int{
function findMaxSum (line 52) | func findMaxSum(node *treenode, maxSum *int) int {
function max (line 67) | func max(a,b int) int {
function main (line 74) | func main() {
FILE: Dynamic Programming/max_sum_increasing_subsequence.cpp
function MaxSumIncreasingSubsequence (line 35) | std::pair<int, std::vector<int>> MaxSumIncreasingSubsequence(std::vector...
FILE: Dynamic Programming/max_sum_increasing_subsequence.go
function MaxSumIncreasingSubsequence (line 36) | func MaxSumIncreasingSubsequence(array []int) (int, []int) {
function buildSequence (line 76) | func buildSequence(array []int, sequences []int, index int) []int {
function reverse (line 94) | func reverse(numbers []int) {
FILE: Dynamic Programming/max_sum_increasing_subsequence.java
class Main (line 35) | public class Main {
method maxSumIncreasingSubsequence (line 36) | public static int[] maxSumIncreasingSubsequence(int[] array) {
method main (line 76) | public static void main(String[] args) {
FILE: Dynamic Programming/max_sum_increasing_subsequence.js
function maxSumIncreasingSubsequence (line 32) | function maxSumIncreasingSubsequence(array) {
FILE: Dynamic Programming/max_sum_increasing_subsequence.py
function max_sum_increasing_subsequence (line 31) | def max_sum_increasing_subsequence(array):
FILE: Dynamic Programming/maximal_sqaure.cpp
function maximalSquare (line 83) | int maximalSquare(std::vector<std::vector<char>>& matrix) {
FILE: Dynamic Programming/maximal_sqaure.go
function maximalSquare (line 87) | func maximalSquare(matrix [][]byte) int {
function max (line 129) | func max(a, b int) int {
function min (line 136) | func min(a, b int) int {
FILE: Dynamic Programming/maximal_sqaure.js
function maximalSquare (line 79) | function maximalSquare(matrix) {
FILE: Dynamic Programming/maximal_sqaure.py
function maximalSquare (line 80) | def maximalSquare(matrix):
FILE: Dynamic Programming/maximal_square.java
class LargestSquare (line 33) | public class LargestSquare {
method maximalSquare (line 34) | public int maximalSquare(char[][] matrix) {
FILE: Dynamic Programming/min_cost_travel_in_a_grid.cpp
function min_cost_path_in_a_grid (line 19) | int min_cost_path_in_a_grid(int grid[][100], int m, int n){
function main (line 38) | int main(){
FILE: Dynamic Programming/min_insertion_steps_for_string_palindrome.java
class PalindromeInsertion (line 22) | public class PalindromeInsertion {
method findMinInsertions (line 23) | public static int findMinInsertions(String s) {
method main (line 40) | public static void main(String[] args) {
FILE: Dynamic Programming/min_number_of_jumps.cpp
function MinNumberOfJumpsOptimal (line 42) | int MinNumberOfJumpsOptimal(std::vector<int>& array) {
FILE: Dynamic Programming/min_number_of_jumps.go
function MinNumberOfJumps (line 38) | func MinNumberOfJumps(array []int) int {
function min (line 66) | func min(a, b int) int {
function MinNumberOfJumpsOptimal (line 112) | func MinNumberOfJumpsOptimal(array []int) int {
FILE: Dynamic Programming/min_number_of_jumps.java
class min_number_of_jumps (line 1) | public class min_number_of_jumps {
method minNumberOfJumpsOptimal (line 42) | public static int minNumberOfJumpsOptimal(int[] array) {
FILE: Dynamic Programming/min_number_of_jumps.js
function minNumberOfJumpsOptimal (line 39) | function minNumberOfJumpsOptimal(array) {
FILE: Dynamic Programming/min_number_of_jumps.py
function min_number_of_jumps_optimal (line 39) | def min_number_of_jumps_optimal(array):
FILE: Dynamic Programming/min_steps_to_make_string_palindrome.go
function lcs (line 28) | func lcs(s1, s2 string) int {
function max (line 48) | func max(a, b int) int {
function minInsertions (line 55) | func minInsertions(s string) int {
function main (line 65) | func main() {
FILE: Dynamic Programming/min_steps_to_make_string_palindrome.java
class Main (line 23) | public class Main {
method lcs (line 26) | public static int lcs(String s1, String s2) {
method minInsertions (line 59) | public static int minInsertions(String s) {
method main (line 68) | public static void main(String[] args) {
FILE: Dynamic Programming/min_steps_to_make_string_palindrome.py
function lcs (line 22) | def lcs(s1, s2):
function min_insertions (line 42) | def min_insertions(s):
FILE: Dynamic Programming/min_steps_to_make_string_pallindrome.cpp
function lcs (line 25) | int lcs(string s1,string s2){
function main (line 54) | int main(){
FILE: Dynamic Programming/min_steps_to_make_string_pallindrome.js
function lcs (line 22) | function lcs(s1, s2) {
function minInsertions (line 47) | function minInsertions(s) {
FILE: Dynamic Programming/min_steps_to_reduce_a_number_to_one.cpp
function find_min_steps (line 18) | int find_min_steps(int number){
function find_min_steps (line 38) | int find_min_steps(int number){
function main (line 53) | int main(){
FILE: Dynamic Programming/num_ways_to_make_change.cpp
function NumberOfWaysToMakeChange (line 46) | int NumberOfWaysToMakeChange(int n, const std::vector<int>& denoms) {
FILE: Dynamic Programming/num_ways_to_make_change.go
function NumberOfWaysToMakeChange (line 46) | func NumberOfWaysToMakeChange(n int, denoms []int) int {
FILE: Dynamic Programming/num_ways_to_make_change.java
class CoinChange (line 46) | public class CoinChange {
method numberOfWaysToMakeChange (line 48) | public static int numberOfWaysToMakeChange(int n, int[] denoms) {
method main (line 72) | public static void main(String[] args) {
FILE: Dynamic Programming/num_ways_to_make_change.js
function numberOfWaysToMakeChange (line 44) | function numberOfWaysToMakeChange(n, denoms) {
FILE: Dynamic Programming/num_ways_to_make_change.py
function number_of_ways_to_make_change (line 43) | def number_of_ways_to_make_change(n, denoms):
FILE: Dynamic Programming/num_ways_to_traverse_graph.cpp
function numberOfWaysToTraverseGraph (line 56) | int numberOfWaysToTraverseGraph(int width, int height) {
function numberOfWaysToTraverseGraphCombinatorics (line 106) | int numberOfWaysToTraverseGraphCombinatorics(int width, int height) {
function factorial (line 119) | int factorial(int n) {
function numberOfWaysToTraverseGraphRecursive (line 171) | int numberOfWaysToTraverseGraphRecursive(int width, int height) {
FILE: Dynamic Programming/num_ways_to_traverse_graph.go
function NumberOfWaysToTraverseGraph (line 57) | func NumberOfWaysToTraverseGraph(width int, height int) int {
function NumberOfWaysToTraverseGraphCombinatorics (line 119) | func NumberOfWaysToTraverseGraphCombinatorics(width int, height int) int {
function factorial (line 134) | func factorial(num int) int {
function NumberOfWaysToTraverseGraphRecursive (line 184) | func NumberOfWaysToTraverseGraphRecursive(width int, height int) int {
FILE: Dynamic Programming/num_ways_to_traverse_graph.js
function numberOfWaysToTraverseGraph (line 55) | function numberOfWaysToTraverseGraph(width, height) {
function numberOfWaysToTraverseGraphCombinatorics (line 106) | function numberOfWaysToTraverseGraphCombinatorics(width, height) {
function factorial (line 120) | function factorial(n) {
function numberOfWaysToTraverseGraphRecursive (line 171) | function numberOfWaysToTraverseGraphRecursive(width, height) {
FILE: Dynamic Programming/num_ways_to_traverse_graph.py
function number_of_ways_to_traverse_graph (line 54) | def number_of_ways_to_traverse_graph(width, height):
function number_of_ways_to_traverse_graph_combinatorics (line 111) | def number_of_ways_to_traverse_graph_combinatorics(width, height):
function number_of_ways_to_traverse_graph_recursive (line 165) | def number_of_ways_to_traverse_graph_recursive(width, height):
FILE: Dynamic Programming/numbers_in_pi.go
function NumbersInPi (line 50) | func NumbersInPi(pi string, numbers []string) int {
function getMinSpaces (line 68) | func getMinSpaces(pi string, numbersTable map[string]bool, cache map[int...
function min (line 98) | func min(a, b int) int {
FILE: Dynamic Programming/reconstruct_bst_in_python.py
class TreeNode (line 1) | class TreeNode:
method __init__ (line 2) | def __init__(self, val):
function constructBST (line 7) | def constructBST(preorder):
function inorderTraversal (line 22) | def inorderTraversal(root):
FILE: Dynamic Programming/rod_cutting_problem_dp.cpp
function max_profit (line 15) | int max_profit(vector<int> profit, int total_length){
function main (line 26) | int main(){
FILE: Dynamic Programming/rod_cutting_problem_memoized.cpp
function max_profit (line 16) | int max_profit(vector<int> length, int n){
function main (line 27) | int main(){
FILE: Dynamic Programming/rod_cutting_problem_recursive.cpp
function max_profit (line 15) | int max_profit(vector<int> length, int n){
function main (line 24) | int main(){
FILE: Dynamic Programming/trapping_rain_water.cpp
class Solution (line 24) | class Solution {
method trap (line 26) | int trap(vector<int>& height) {
FILE: Dynamic Programming/unique_paths_with_obstacles.cpp
class Solution (line 19) | class Solution {
method uniquePathsWithObstacles (line 21) | int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
FILE: Dynamic Programming/wine_selling_problem_dp.cpp
function find_max_profit (line 17) | int find_max_profit(int *A, int n){
function main (line 45) | int main(){
FILE: Dynamic Programming/wine_selling_problem_memoized.cpp
function find_max_profit (line 18) | int find_max_profit(int *A, int start, int end, int year){
function main (line 29) | int main(){
FILE: Dynamic Programming/wine_selling_problem_recursive.cpp
function find_max_profit (line 17) | int find_max_profit(int *A, int start, int end, int year){
function main (line 24) | int main(){
FILE: Famous Algorithms/N_queen.js
function solveNQueens (line 1) | function solveNQueens(n) {
FILE: Famous Algorithms/euclidean_algorithm.java
class euclidean_algorithm (line 5) | public class euclidean_algorithm {
method euclid (line 6) | public static int euclid(int a, int b, int c, int d){
method main (line 20) | public static void main(String[] args) {
FILE: Famous Algorithms/euclidean_algorithm.js
function euclid (line 6) | function euclid(a,b,c,d){
FILE: Famous Algorithms/euclidean_algorithm.py
function euclidExtended (line 5) | def euclidExtended(a,b):
FILE: Famous Algorithms/kadanes_algorithm.go
function KadanesAlgorithm (line 31) | func KadanesAlgorithm(array []int) int {
function max (line 49) | func max(a, b int) int {
FILE: Famous Algorithms/kadanes_algorithm.java
class kadanes_algo (line 42) | public class kadanes_algo {
method maxSubArraySum (line 43) | public static int maxSubArraySum(int[] arr) {
method main (line 66) | public static void main(String[] args) {
FILE: Famous Algorithms/kadanes_algorithm.py
function maxSubArraySum (line 63) | def maxSubArraySum(a, size):
FILE: Famous Algorithms/kadenes_algorithm.js
function largestSumOfSubArray (line 61) | function largestSumOfSubArray(arr) {
FILE: Famous Algorithms/kmp.java
class Graph_KMPAlgorithm (line 34) | public class Graph_KMPAlgorithm {
method computeLPSArray (line 36) | public static int[] computeLPSArray(String pattern) {
method searchPattern (line 59) | public static int searchPattern(String text, String pattern) {
method main (line 88) | public static void main(String[] args) {
FILE: Famous Algorithms/kmp.js
function computeLPSArray (line 38) | function computeLPSArray(pattern) {
function KMP (line 69) | function KMP(text, pattern) {
FILE: Famous Algorithms/kmp.py
function search (line 23) | def search(pat, txt):
FILE: Fast and Slow Pointers/happy_number.go
function pow (line 25) | func pow(digit int, power int) int {
function sumDigits (line 34) | func sumDigits(number int) int {
function happyNumber (line 44) | func happyNumber(num int) bool {
function main (line 54) | func main() {
FILE: Fast and Slow Pointers/linked_list_compute_midpoint.cpp
class node (line 7) | class node{
method node (line 11) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 28) | void print_linked_list(node *head){
function makeLinkedList (line 34) | void makeLinkedList(node *&head){
function node (line 42) | node* compute_midpoint(node *head){
method node (line 11) | node(int d){
function main (line 54) | int main(){
FILE: Fast and Slow Pointers/linked_list_compute_midpoint.java
class linked_list_compute_midpoint (line 47) | public class linked_list_compute_midpoint {
class Node (line 49) | static class Node {
method Node (line 54) | public Node(int data) {
method insertAtTail (line 60) | static Node insertAtTail(Node head, int data) {
method printLinkedList (line 74) | static void printLinkedList(Node head) {
method makeLinkedList (line 81) | static Node makeLinkedList() {
method computeMidpoint (line 93) | static Node computeMidpoint(Node head) {
method main (line 106) | public static void main(String[] args) {
FILE: Fast and Slow Pointers/linked_list_find_middle.py
class Node (line 3) | class Node:
method __init__ (line 6) | def __init__(self, data):
class LinkedList (line 10) | class LinkedList:
method __init__ (line 12) | def __init__(self):
method push (line 15) | def push(self, new_data):
method printMiddle (line 24) | def printMiddle(self):
FILE: Fast and Slow Pointers/linked_list_floyds_cycle_detection.cpp
class node (line 8) | class node{
method node (line 12) | node(int d){
function insert_at_tail (line 17) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 29) | void print_linked_list(node *head){
function makeLinkedList (line 35) | void makeLinkedList(node *&head){
function detect_cycle (line 44) | bool detect_cycle(node *head){
function main (line 68) | int main(){
FILE: Fast and Slow Pointers/linked_list_floyds_cycle_detection.py
class Solution (line 14) | class Solution:
method hasCycle (line 15) | def hasCycle(self, head: Optional[ListNode]) -> bool:
FILE: Graphs/Diljstra.go
type Graph (line 9) | type Graph struct
method AddEdge (line 14) | func (g *Graph) AddEdge(node1, node2 string, weight float64) {
function Dijkstra (line 29) | func Dijkstra(graph Graph, startNode string) map[string]float64 {
function main (line 66) | func main() {
FILE: Graphs/GraphBFS.java
class GraphBFS (line 8) | class GraphBFS {
method GraphBFS (line 13) | GraphBFS(int v) {
method addEdge (line 22) | void addEdge(int u, int v) {
method bfs (line 32) | void bfs(int s) {
method main (line 54) | public static void main(String[] args) {
FILE: Graphs/Graph_Dijstra.java
class Graph (line 3) | class Graph {
method Graph (line 7) | public Graph(int V) {
method addEdge (line 16) | public void addEdge(int source, int destination, int weight) {
method dijkstra (line 21) | public void dijkstra(int source) {
class Node (line 50) | private static class Node {
method Node (line 54) | Node(int vertex, int weight) {
class DijkstraAlgorithm (line 61) | public class DijkstraAlgorithm {
method main (line 62) | public static void main(String[] args) {
FILE: Graphs/Graphs_Dijkstras.py
function dijkstra (line 8) | def dijkstra(graph, start):
FILE: Graphs/Graphs_Ford_Fulkerson.cpp
function bfs (line 27) | bool bfs(int rGraph[V][V], int s, int t, int parent[])
function fordFulkerson (line 61) | int fordFulkerson(int graph[V][V], int s, int t)
function main (line 106) | int main()
FILE: Graphs/Graphs_bfs.cpp
class Graph (line 7) | class Graph{
method Graph (line 10) | Graph(){
method addEdge (line 13) | void addEdge(T u, T v, bool bidir = true){
method printAdjList (line 19) | void printAdjList(){
method bfs (line 28) | void bfs(int n){
function main (line 47) | int main(){
FILE: Graphs/Graphs_bfs.js
function bfs (line 2) | function bfs(graph, startNode) {
FILE: Graphs/Graphs_bfs.py
class Graph (line 3) | class Graph:
method __init__ (line 4) | def __init__(self):
method insertEdge (line 7) | def insertEdge(self,v1,v2):
method subBfs (line 10) | def subBfs(self,visited,queue):
method bfs (line 21) | def bfs(self,v):
FILE: Graphs/Graphs_bfs_sssp.cpp
class Graph (line 7) | class Graph{
method Graph (line 10) | Graph(){
method addEdge (line 13) | void addEdge(T u, T v, bool bidir = true){
method printAdjList (line 19) | void printAdjList(){
method bfs_sssp (line 28) | void bfs_sssp(int n){
function main (line 61) | int main(){
FILE: Graphs/Graphs_cycle_detection_bfs.cpp
class Graph (line 6) | class Graph{
method Graph (line 9) | Graph(){
method add_edge (line 12) | void add_edge(T u, T v, bool bidir = true){
method print_edge (line 18) | void print_edge(){
method is_cyclic (line 27) | bool is_cyclic(T source){
function main (line 53) | int main(){
FILE: Graphs/Graphs_cycle_detection_dfs.cpp
class Graph (line 6) | class Graph{
method Graph (line 9) | Graph(){
method add_edge (line 12) | void add_edge(T u, T v, bool bidir = true){
method is_cyclic_helper (line 18) | bool is_cyclic_helper(T node, map<T, bool> &visited, map<T, bool> &in_...
method is_cyclic (line 29) | bool is_cyclic(){
function main (line 47) | int main(){
FILE: Graphs/Graphs_dfs.cpp
class Graph (line 7) | class Graph{
method Graph (line 10) | Graph(){
method addEdge (line 13) | void addEdge(T u, T v, bool bidir = true){
method printAdjList (line 19) | void printAdjList(){
method dfsHelper (line 28) | void dfsHelper(int node, map<int, bool> &visited){
method dfs (line 37) | void dfs(int src){
function main (line 42) | int main(){
FILE: Graphs/Graphs_dfs.java
class Node (line 25) | class Node {
method Node (line 30) | Node(int value) {
method addNeighbor (line 36) | void addNeighbor(Node neighbor) {
class DepthFirstSearch (line 41) | class DepthFirstSearch {
method dfs (line 42) | void dfs(Node startNode) {
class Main (line 56) | public class Main {
method main (line 57) | public static void main(String[] args) {
FILE: Graphs/Graphs_dfs.js
function dfs (line 2) | function dfs(graph, startNode) {
function dfsHelper (line 12) | function dfsHelper(node, visited, graph) {
FILE: Graphs/Graphs_dfs.py
class Graph (line 3) | class Graph:
method __init__ (line 4) | def __init__(self):
method insertEdge (line 7) | def insertEdge(self,v1,v2):
method dfsSub (line 10) | def dfsSub(self,v,visited):
method dfs (line 19) | def dfs(self,v):
FILE: Graphs/Graphs_dfs_connected_components.cpp
class Graph (line 7) | class Graph{
method Graph (line 10) | Graph(){
method addEdge (line 13) | void addEdge(T u, T v, bool bidir = true){
method printAdjList (line 19) | void printAdjList(){
method dfsHelper (line 28) | void dfsHelper(T node, map<T, bool> &visited){
method dfs (line 37) | void dfs(T src){
function main (line 53) | int main(){
FILE: Graphs/Graphs_dijkstras.js
class PriorityQueue (line 2) | class PriorityQueue {
method constructor (line 3) | constructor() {
method enqueue (line 8) | enqueue(item, priority) {
method dequeue (line 23) | dequeue() {
method isEmpty (line 30) | isEmpty() {
method size (line 35) | size() {
function dijkstra (line 41) | function dijkstra(graph, n, start) {
function findShortestPath (line 84) | function findShortestPath(graph, n, start, end) {
FILE: Graphs/Graphs_flood_fill.cpp
function print_matrix (line 73) | void print_matrix(char input[][50]){
function flood_fill (line 83) | void flood_fill(char input[][50], int i, int j, char ch, char color){
function main (line 98) | int main(){
FILE: Graphs/Graphs_kill_process.cpp
class Graph (line 17) | class Graph{
method Graph (line 20) | Graph(){
method add_list (line 23) | void add_list(int u, int v, bool bidir = false){
method print_graph (line 29) | void print_graph(){
method kill_process (line 38) | void kill_process(int process){
function main (line 56) | int main(){
FILE: Graphs/Graphs_kruskals_algo.cpp
class D_S (line 27) | class D_S {
method D_S (line 33) | D_S(int n)
method find (line 44) | int find(int i)
method unite (line 52) | void unite(int x, int y)
class Graph (line 70) | class Graph {
method Graph (line 77) | Graph(int V) { this->V = V; }
method addEdge (line 80) | void addEdge(int x, int y, int w)
method kruskals_mst (line 87) | void kruskals_mst()
function main (line 113) | int main()
FILE: Graphs/Graphs_kruskals_algorithm.js
class DisjointSet (line 16) | class DisjointSet {
method constructor (line 17) | constructor(n) {
method find (line 28) | find(x) {
method union (line 42) | union(x, y) {
function kruskalsAlgorithm (line 63) | function kruskalsAlgorithm(n, edges) {
FILE: Graphs/Graphs_topological_sort_bfs.cpp
class Graph (line 10) | class Graph{
method Graph (line 13) | Graph(){
method addEdge (line 16) | void addEdge(int u, int v, bool bidir = false){
method printList (line 22) | void printList(){
method bfsTopologicalSort (line 31) | void bfsTopologicalSort(){
function main (line 69) | int main(){
FILE: Graphs/Graphs_topological_sort_dfs.cpp
class Graph (line 10) | class Graph{
method Graph (line 13) | Graph(){
method addEdge (line 16) | void addEdge(T v, T u, bool bidir = false){
method print_edge (line 22) | void print_edge(){
method dfsHelper (line 31) | void dfsHelper(T node, map<T, bool> &visited, list<T> &ordering){
method dfs (line 41) | void dfs(){
function main (line 55) | int main(){
FILE: Graphs/a_star_algorithm.py
class Graph (line 51) | class Graph:
method __init__ (line 59) | def __init__(self, adjacency_list):
method get_neighbors (line 62) | def get_neighbors(self, v):
method h (line 66) | def h(self, n):
method a_star_algorithm (line 71) | def a_star_algorithm(self, start_node, stop_node):
FILE: Graphs/adjacency_list.java
class GraphNode (line 37) | public class GraphNode {
method GraphNode (line 43) | public GraphNode(String name, int index) {
class AdjacencyList (line 49) | public class AdjacencyList {
method AdjacencyList (line 53) | public AdjacencyList(ArrayList<GraphNode> nodeList) {
method addUndirectedEdge (line 58) | public void addUndirectedEdge(int i, int j) {
method printGraph (line 66) | public String printGraph() {
class Main (line 83) | public class Main {
method main (line 84) | public static void main(String[] args) {
FILE: Graphs/adjacency_matrix.go
type AdjacencyMatrix (line 5) | type AdjacencyMatrix struct
method Init (line 32) | func (G *AdjacencyMatrix) Init() {
method AddEdge (line 39) | func (G *AdjacencyMatrix) AddEdge(vertexOne int, vertexTwo int) error {
method AddEdgeWithWeight (line 52) | func (G *AdjacencyMatrix) AddEdgeWithWeight(vertexOne int, vertexTwo i...
method RemoveEdge (line 65) | func (G *AdjacencyMatrix) RemoveEdge(vertexOne int, vertexTwo int) err...
method HasEdge (line 77) | func (G *AdjacencyMatrix) HasEdge(vertexOne int, vertexTwo int) bool {
method GetIndegreeForVertex (line 84) | func (G *AdjacencyMatrix) GetIndegreeForVertex(vertex int) int {
method GetGraphType (line 95) | func (G *AdjacencyMatrix) GetGraphType() GraphType {
method GetAdjacentNodesForVertex (line 98) | func (G *AdjacencyMatrix) GetAdjacentNodesForVertex(vertex int) map[in...
method GetWeightOfEdge (line 111) | func (G *AdjacencyMatrix) GetWeightOfEdge(vertexOne int, vertexTwo int...
method GetNumberOfVertices (line 118) | func (G *AdjacencyMatrix) GetNumberOfVertices() int {
method GetNumberOfEdges (line 122) | func (G *AdjacencyMatrix) GetNumberOfEdges() int {
type GraphType (line 11) | type GraphType
constant DIRECTED (line 14) | DIRECTED GraphType = "DIRECTED"
constant UNDIRECTED (line 15) | UNDIRECTED GraphType = "UNDIRECTED"
type Graph (line 18) | type Graph interface
FILE: Graphs/adjacency_matrix.java
class GraphNode (line 45) | public class GraphNode {
method GraphNode (line 50) | GraphNode(String name, int index) {
class AdjacencyMatrix (line 57) | public class AdjacencyMatrix {
method AdjacencyMatrix (line 62) | public AdjacencyMatrix(ArrayList<GraphNode> nodeList) {
method addUndirectedEdge (line 68) | public void addUndirectedEdge(int i, int j) {
method printGraph (line 74) | public String printGraph() {
class Main (line 97) | public class Main {
method main (line 98) | public static void main(String[] args) {
FILE: Graphs/dijkstras.cpp
function dijkstra (line 33) | vector<int> dijkstra(vector<vector<pii>>& graph, int start, int n) {
function main (line 61) | int main() {
FILE: Graphs/dijkstras.go
function DijkstrasAlgorithm (line 55) | func DijkstrasAlgorithm(start int, edges [][][]int) []int {
function getVertexWithMinDistance (line 115) | func getVertexWithMinDistance(distances []int, visited map[int]bool) (in...
FILE: Graphs/dijkstras.java
class Main (line 3) | class Main {
class Node (line 5) | static class Node implements Comparable<Node> {
method Node (line 9) | Node(String name) {
method compareTo (line 14) | @Override
class Edge (line 21) | static class Edge {
method Edge (line 26) | Edge(Node source, Node destination, int weight) {
method dijkstra (line 34) | static void dijkstra(Map<String, List<Edge>> graph, String start) {
method main (line 68) | public static void main(String[] args) {
FILE: Graphs/dijkstras_heap_based.go
function DijkstrasAlgorithm (line 54) | func DijkstrasAlgorithm(start int, edges [][][]int) []int {
type Item (line 114) | type Item struct
type MinHeap (line 120) | type MinHeap struct
method IsEmpty (line 140) | func (h *MinHeap) IsEmpty() bool {
method Remove (line 145) | func (h *MinHeap) Remove() (int, int) {
method Update (line 156) | func (h *MinHeap) Update(vertex int, value int) {
method swap (line 162) | func (h MinHeap) swap(i, j int) {
method length (line 169) | func (h MinHeap) length() int {
method buildHeap (line 174) | func (h *MinHeap) buildHeap() {
method siftDown (line 182) | func (h *MinHeap) siftDown(currentIdx, endIdx int) {
method siftUp (line 204) | func (h *MinHeap) siftUp(currentIdx int) {
function NewMinHeap (line 126) | func NewMinHeap(array []Item) *MinHeap {
FILE: Graphs/ford_fulkerson.cpp
function bfs (line 38) | bool bfs(int rGraph[V][V], int s, int t, int parent[])
function fordFulkerson (line 80) | int fordFulkerson(int graph[V][V], int s, int t)
function main (line 130) | int main()
FILE: Graphs/graphs_adjacency_list.cpp
class Graph (line 6) | class Graph{
method Graph (line 10) | Graph(int v){
method addEdge (line 15) | void addEdge(int u, int v, bool bidir = true){
method printAdjacencyList (line 21) | void printAdjacencyList(){
function main (line 31) | int main(){
FILE: Graphs/graphs_adjacency_list_generic.cpp
class Graph (line 7) | class Graph{
method Graph (line 10) | Graph(){
method addEdge (line 13) | void addEdge(T u, T v, bool bidir = true){
method printAdjList (line 19) | void printAdjList(){
function main (line 29) | int main(){
FILE: Graphs/graphs_bfs.go
type Graph (line 31) | type Graph struct
method addEdge (line 38) | func (g *Graph) addEdge(u, v int) {
function BFS (line 46) | func BFS(g *Graph, start int) {
function main (line 70) | func main() {
FILE: Graphs/graphs_dfs.go
type Node (line 33) | type Node struct
function DFS (line 40) | func DFS(node *Node) {
function main (line 56) | func main() {
FILE: Graphs/kruskals_algorithm.java
class KruskalsMST (line 25) | public class KruskalsMST {
class Edge (line 28) | static class Edge {
method Edge (line 31) | public Edge(int src, int dest, int weight)
class Subset (line 40) | static class Subset {
method Subset (line 43) | public Subset(int parent, int rank)
method main (line 51) | public static void main(String[] args)
method kruskals (line 72) | private static void kruskals(int V, List<Edge> edges)
method union (line 124) | private static void union(Subset[] subsets, int x,
method findRoot (line 144) | private static int findRoot(Subset[] subsets, int i)
FILE: Graphs/kruskals_algorithm.py
class UnionFind (line 13) | class UnionFind:
method __init__ (line 14) | def __init__(self, n):
method find (line 19) | def find(self, x):
method union (line 25) | def union(self, x, y):
function kruskal (line 40) | def kruskal(graph):
FILE: Graphs/remove_island.go
function RemoveIslands (line 83) | func RemoveIslands(matrix [][]int) [][]int {
function findOnesConnectedToBorder (line 124) | func findOnesConnectedToBorder(matrix [][]int, startRow, startCol int, o...
function getNeighbors (line 151) | func getNeighbors(matrix [][]int, row, col int) [][]int {
function main (line 172) | func main() {
function printMatrix (line 192) | func printMatrix(matrix [][]int) {
FILE: Graphs/river_sizes.cpp
function riverSizes (line 67) | vector<int> riverSizes(vector<vector<int>>& matrix) {
function traverseNode (line 90) | vector<int> traverseNode(int i, int j, vector<vector<int>>& matrix, vect...
function getUnvisitedNeighbors (line 138) | vector<vector<int>> getUnvisitedNeighbors(int i, int j, vector<vector<in...
function main (line 168) | int main() {
FILE: Graphs/river_sizes.go
function RiverSizes (line 65) | func RiverSizes(matrix [][]int) []int {
function traverseNode (line 91) | func traverseNode(i, j int, matrix [][]int, visited [][]bool, sizes []in...
function getUnvisitedNeighbors (line 138) | func getUnvisitedNeighbors(i, j int, matrix [][]int, visited [][]bool) [...
FILE: Graphs/river_sizes.java
class RiverSizes (line 66) | public class RiverSizes {
method riverSizes (line 68) | public static List<Integer> riverSizes(int[][] matrix) {
method traverseNode (line 90) | private static List<Integer> traverseNode(int i, int j, int[][] matrix...
method getUnvisitedNeighbors (line 131) | private static List<int[]> getUnvisitedNeighbors(int i, int j, int[][]...
method main (line 160) | public static void main(String[] args) {
FILE: Graphs/river_sizes.js
function riverSizes (line 62) | function riverSizes(matrix) {
function traverseNode (line 87) | function traverseNode(i, j, matrix, visited) {
function getUnvisitedNeighbors (line 130) | function getUnvisitedNeighbors(i, j, matrix, visited) {
FILE: Graphs/river_sizes.py
function riverSizes (line 64) | def riverSizes(matrix):
function traverseNode (line 84) | def traverseNode(i, j, matrix, visited, sizes):
function getUnvisitedNeighbors (line 124) | def getUnvisitedNeighbors(i, j, matrix, visited):
FILE: Graphs/single_cycle_check.cpp
function hasSingleCycle (line 56) | bool hasSingleCycle(vector<int>& array) {
function getNextIdx (line 74) | int getNextIdx(vector<int>& array, int currIdx) {
function main (line 85) | int main() {
FILE: Graphs/single_cycle_check.go
function HasSingleCycle (line 55) | func HasSingleCycle(array []int) bool {
function getNextIdx (line 72) | func getNextIdx(array []int, currIdx int) int {
function main (line 84) | func main() {
FILE: Graphs/single_cycle_check.java
class Main (line 52) | public class Main {
method hasSingleCycle (line 54) | public static boolean hasSingleCycle(int[] array) {
method getNextIdx (line 72) | public static int getNextIdx(int[] array, int currIdx) {
method main (line 83) | public static void main(String[] args) {
FILE: Graphs/single_cycle_check.js
function hasSingleCycle (line 50) | function hasSingleCycle(array) {
function getNextIdx (line 67) | function getNextIdx(array, currIdx) {
FILE: Graphs/single_cycle_check.py
function has_single_cycle (line 51) | def has_single_cycle(array):
function get_next_idx (line 66) | def get_next_idx(array, curr_idx):
FILE: Graphs/snack_ladders.cpp
class Graph (line 49) | class Graph{
method Graph (line 52) | Graph(){
method addEdge (line 55) | void addEdge(T u, T v, bool bidir = true){
method printAdjList (line 61) | void printAdjList(){
method bfs_sssp (line 70) | int bfs_sssp(int n, int m){
function main (line 108) | int main(){
FILE: Graphs/snack_ladders.js
constant BOARD_SIZE (line 3) | const BOARD_SIZE = 100;
function buildGraph (line 19) | function buildGraph() {
function playGame (line 49) | function playGame() {
FILE: Graphs/snack_ladders.py
function snakesAndLadders (line 41) | def snakesAndLadders(board):
function getRowCol (line 64) | def getRowCol(idx, n):
FILE: Graphs/snakes_ladders.java
class SnakesAndLadders (line 35) | public class SnakesAndLadders {
method SnakesAndLadders (line 40) | public SnakesAndLadders() {
method addSnake (line 46) | public void addSnake(int start, int end) {
method addLadder (line 50) | public void addLadder(int start, int end) {
method playGame (line 54) | public int playGame() {
method rollDice (line 83) | private int rollDice() {
method main (line 88) | public static void main(String[] args) {
FILE: Graphs/topological_sort.cpp
type Dep (line 77) | struct Dep {
class JobGraph (line 82) | class JobGraph
method JobGraph (line 92) | JobGraph(vector<int>& jobs) {
method addPrereq (line 100) | void addPrereq(int job, int prereq) {
method addNode (line 108) | void addNode(int job) {
method JobNode (line 115) | JobNode* getNode(int job) {
class JobGraph (line 89) | class JobGraph {
method JobGraph (line 92) | JobGraph(vector<int>& jobs) {
method addPrereq (line 100) | void addPrereq(int job, int prereq) {
method addNode (line 108) | void addNode(int job) {
method JobNode (line 115) | JobNode* getNode(int job) {
function TopologicalSort (line 129) | vector<int> TopologicalSort(vector<int>& jobs, vector<Dep>& deps) {
function JobGraph (line 137) | JobGraph createJobGraph(vector<int>& jobs, vector<Dep>& deps) {
method JobGraph (line 92) | JobGraph(vector<int>& jobs) {
method addPrereq (line 100) | void addPrereq(int job, int prereq) {
method addNode (line 108) | void addNode(int job) {
method JobNode (line 115) | JobNode* getNode(int job) {
function getOrderedJobs (line 148) | vector<int> getOrderedJobs(JobGraph& graph) {
function depthFirstTraverse (line 167) | bool depthFirstTraverse(JobGraph& graph, int jobId, vector<int>& ordered...
class JobNode (line 204) | class JobNode {
method JobNode (line 212) | JobNode(int jobId) : job(jobId), visited(false), visiting(false) {}
FILE: Graphs/topological_sort.go
type Dep (line 74) | type Dep struct
function TopologicalSort (line 80) | func TopologicalSort(jobs []int, deps []Dep) []int {
function createJobGraph (line 89) | func createJobGraph(jobs []int, deps []Dep) *JobGraph {
function getOrderedJobs (line 99) | func getOrderedJobs(graph *JobGraph) []int {
function depthFirstTraverse (line 121) | func depthFirstTraverse(node *JobNode, orderedJobs *[]int) bool {
type JobGraph (line 155) | type JobGraph struct
method Addprereq (line 173) | func (g *JobGraph) Addprereq(job, prereq int) {
method AddNode (line 181) | func (g *JobGraph) AddNode(job int) {
method GetNode (line 188) | func (g *JobGraph) GetNode(job int) *JobNode {
function NewJobGraph (line 161) | func NewJobGraph(jobs []int) *JobGraph {
type JobNode (line 197) | type JobNode struct
FILE: Graphs/topological_sort.java
class Dep (line 77) | class Dep {
method Dep (line 81) | public Dep(int Prereq, int Job) {
class JobGraph (line 87) | class JobGraph {
class JobNode (line 90) | static class JobNode {
method JobNode (line 97) | public JobNode(int job) {
method JobGraph (line 109) | public JobGraph(List<Integer> jobs) {
method addPrereq (line 119) | public void addPrereq(int job, int prereq) {
method addNode (line 127) | public void addNode(int job) {
method getNode (line 135) | public JobNode getNode(int job) {
method TopologicalSort (line 147) | public static List<Integer> TopologicalSort(List<Integer> jobs, List<Dep...
method createJobGraph (line 155) | public static JobGraph createJobGraph(List<Integer> jobs, List<Dep> deps) {
method getOrderedJobs (line 166) | public static List<Integer> getOrderedJobs(JobGraph graph) {
FILE: Graphs/topological_sort.js
class Dep (line 72) | class Dep {
method constructor (line 73) | constructor(Prereq, Job) {
class JobGraph (line 79) | class JobGraph {
method constructor (line 80) | constructor(jobs) {
method addPrereq (line 89) | addPrereq(job, prereq) {
method addNode (line 96) | addNode(job) {
method getNode (line 103) | getNode(job) {
function TopologicalSort (line 112) | function TopologicalSort(jobs, deps) {
function createJobGraph (line 119) | function createJobGraph(jobs, deps) {
function getOrderedJobs (line 129) | function getOrderedJobs(graph) {
function depthFirstTraverse (line 146) | function depthFirstTraverse(graph, jobId, orderedJobs) {
FILE: Graphs/topological_sort.py
function main (line 11) | def main():
function dfs (line 25) | def dfs(adj_list, visited, stack):
function dfs_visit (line 34) | def dfs_visit(adj_list, visited, node, stack):
FILE: Graphs/two_colorable.cpp
function isTwoColorable (line 42) | bool isTwoColorable(std::vector<std::vector<int>>& edges) {
function main (line 80) | int main() {
FILE: Graphs/two_colorable.go
function TwoColorable (line 39) | func TwoColorable(edges [][]int) bool {
FILE: Graphs/two_colorable.java
class TwoColorable (line 39) | public class TwoColorable {
method isTwoColorable (line 41) | public static boolean isTwoColorable(List<List<Integer>> edges) {
method main (line 78) | public static void main(String[] args) {
FILE: Graphs/two_colorable.js
function isTwoColorable (line 37) | function isTwoColorable(edges) {
FILE: Graphs/two_colorable.py
function is_two_colorable (line 37) | def is_two_colorable(edges):
FILE: Graphs/union_find.cpp
class UnionFind (line 59) | class UnionFind {
method createSet (line 64) | void createSet(int value) {
method find (line 69) | int find(int value) {
method unionSets (line 90) | void unionSets(int valueOne, int valueTwo) {
function main (line 109) | int main() {
FILE: Graphs/union_find.go
type UnionFind (line 60) | type UnionFind struct
method CreateSet (line 74) | func (union *UnionFind) CreateSet(value int) {
method Find (line 80) | func (union *UnionFind) Find(value int) *int {
method Union (line 101) | func (union *UnionFind) Union(valueOne, valueTwo int) {
function NewUnionFind (line 66) | func NewUnionFind() *UnionFind {
function main (line 122) | func main() {
FILE: Graphs/union_find.java
class UnionFind (line 59) | class UnionFind {
method UnionFind (line 63) | public UnionFind() {
method createSet (line 68) | public void createSet(int value) {
method find (line 73) | public int find(int value) {
method unionSets (line 94) | public void unionSets(int valueOne, int valueTwo) {
class Main (line 113) | public class Main {
method main (line 114) | public static void main(String[] args) {
FILE: Graphs/union_find.js
class UnionFind (line 56) | class UnionFind {
method constructor (line 57) | constructor() {
method createSet (line 62) | createSet(value) {
method find (line 67) | find(value) {
method union (line 88) | union(valueOne, valueTwo) {
FILE: Graphs/union_find.py
class UnionFind (line 56) | class UnionFind:
method __init__ (line 57) | def __init__(self):
method create_set (line 61) | def create_set(self, value):
method find (line 65) | def find(self, value):
method union (line 82) | def union(self, value_one, value_two):
FILE: Graphs/validate_bst.cpp
type TreeNode (line 28) | struct TreeNode {
method TreeNode (line 33) | TreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
function isValidBST (line 37) | bool isValidBST(TreeNode* root) {
function isValidBSTHelper (line 42) | bool isValidBSTHelper(TreeNode* node, long long minVal, long long maxVal) {
function main (line 62) | int main() {
FILE: Graphs/validate_bst.go
type BST (line 29) | type BST struct
method ValidateBst (line 37) | func (tree *BST) ValidateBst() bool {
method validateBST (line 44) | func (tree *BST) validateBST(min, max int) bool {
FILE: Graphs/validate_bst.java
class TreeNode (line 27) | class TreeNode {
method TreeNode (line 32) | TreeNode(int x) {
class ValidateBST (line 39) | public class ValidateBST {
method isValidBST (line 42) | public static boolean isValidBST(TreeNode root) {
method isValidBSTHelper (line 47) | private static boolean isValidBSTHelper(TreeNode node, long minVal, lo...
method main (line 67) | public static void main(String[] args) {
FILE: Graphs/validate_bst.js
class TreeNode (line 25) | class TreeNode {
method constructor (line 26) | constructor(value) {
function isValidBST (line 34) | function isValidBST(root) {
function isValidBSTHelper (line 39) | function isValidBSTHelper(node, minVal, maxVal) {
FILE: Graphs/validate_bst.py
class BST (line 27) | class BST:
method __init__ (line 28) | def __init__(self, value):
method validate_bst (line 34) | def validate_bst(self):
method _validate_bst (line 38) | def _validate_bst(self, min_val, max_val):
FILE: Graphs/youngest_common_ancestor.cpp
class AncestralTree (line 49) | class AncestralTree {
method AncestralTree (line 54) | AncestralTree(string name) {
function getDescendantDepth (line 61) | int getDescendantDepth(AncestralTree* descendant, AncestralTree* topAnce...
function AncestralTree (line 71) | AncestralTree* backTrackAncestralTree(AncestralTree* lowestDescendant, A...
method AncestralTree (line 54) | AncestralTree(string name) {
function AncestralTree (line 84) | AncestralTree* getYoungestCommonAncestor(AncestralTree* topAncestor, Anc...
method AncestralTree (line 54) | AncestralTree(string name) {
function main (line 94) | int main() {
FILE: Graphs/youngest_common_ancestor.go
type AncestralTree (line 47) | type AncestralTree struct
function GetYoungestCommonAncestor (line 53) | func GetYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo...
function getDescendantDepth (line 69) | func getDescendantDepth(descendant, topAncestor *AncestralTree) int {
function backTrackAncestralTree (line 79) | func backTrackAncestralTree(lowestDescendant, higherDescendant *Ancestra...
function main (line 96) | func main() {
FILE: Graphs/youngest_common_ancestor.java
class AncestralTree (line 43) | class AncestralTree {
method AncestralTree (line 47) | public AncestralTree(String name) {
class Main (line 53) | public class Main {
method getDescendantDepth (line 55) | public static int getDescendantDepth(AncestralTree descendant, Ancestr...
method backTrackAncestralTree (line 65) | public static AncestralTree backTrackAncestralTree(AncestralTree lowes...
method getYoungestCommonAncestor (line 78) | public static AncestralTree getYoungestCommonAncestor(AncestralTree to...
method main (line 88) | public static void main(String[] args) {
FILE: Graphs/youngest_common_ancestor.js
class AncestralTree (line 43) | class AncestralTree {
method constructor (line 44) | constructor(name) {
function getDescendantDepth (line 51) | function getDescendantDepth(descendant, topAncestor) {
function backTrackAncestralTree (line 61) | function backTrackAncestralTree(lowestDescendant, higherDescendant, diff) {
function getYoungestCommonAncestor (line 74) | function getYoungestCommonAncestor(topAncestor, descendantOne, descendan...
FILE: Graphs/youngest_common_ancestor.py
class AncestralTree (line 42) | class AncestralTree:
method __init__ (line 43) | def __init__(self, name):
function get_descendant_depth (line 48) | def get_descendant_depth(descendant, top_ancestor):
function back_track_ancestral_tree (line 56) | def back_track_ancestral_tree(lowest_descendant, higher_descendant, diff):
function get_youngest_common_ancestor (line 66) | def get_youngest_common_ancestor(top_ancestor, descendant_one, descendan...
FILE: Greedy/coin_change.go
function coinChangeGreedy (line 21) | func coinChangeGreedy(coins []int, target int) int {
function main (line 32) | func main() {
FILE: Greedy/coin_change.java
class CoinChange (line 13) | public class CoinChange {
method minCoins (line 22) | public static int minCoins(int[] coins, int n) {
method main (line 45) | public static void main(String[] args) {
FILE: Greedy/coin_change.js
function coinChangeGreedy (line 2) | function coinChangeGreedy(s, l) {
FILE: Greedy/coin_change.py
function coinChangeGreedy (line 99) | def coinChangeGreedy(s:int, l:list[int]):
function coinChangeGreedySorted (line 116) | def coinChangeGreedySorted(s:int, l:list[int]):
FILE: Greedy/task_assignment.cpp
function getTaskDurationToIndices (line 60) | unordered_map<int, vector<int>> getTaskDurationToIndices(vector<int>& ta...
function TaskAssignment (line 73) | vector<vector<int>> TaskAssignment(int k, vector<int>& tasks) {
FILE: Greedy/task_assignment.go
function TaskAssignment (line 56) | func TaskAssignment(k int, tasks []int) [][]int {
function getTaskDurationToIndices (line 85) | func getTaskDurationToIndices(tasks []int) map[int][]int {
FILE: Greedy/task_assignment.java
class TaskAssignment (line 58) | public class TaskAssignment {
method taskAssignment (line 60) | public static int[][] taskAssignment(int k, int[] tasks) {
method getTaskDurationToIndices (line 87) | private static Map<Integer, List<Integer>> getTaskDurationToIndices(in...
method main (line 100) | public static void main(String[] args) {
FILE: Greedy/task_assignment.js
function taskAssignment (line 52) | function taskAssignment(k, tasks) {
function getTaskDurationToIndices (line 79) | function getTaskDurationToIndices(tasks) {
FILE: Greedy/task_assignment.py
function task_assignment (line 53) | def task_assignment(k, tasks):
function get_task_duration_to_indices (line 76) | def get_task_duration_to_indices(tasks):
FILE: Hash Table/Bloomfilter.cpp
class BloomFilter (line 6) | class BloomFilter {
method BloomFilter (line 14) | BloomFilter(int size, std::vector<std::function<size_t(const std::stri...
method add (line 18) | void add(const std::string& element) {
method contains (line 26) | bool contains(const std::string& element) {
function hash1 (line 38) | size_t hash1(const std::string& str) {
function hash2 (line 43) | size_t hash2(const std::string& str) {
function main (line 51) | int main() {
FILE: Hash Table/Convert an array to reduced form using hashing.cpp
function main (line 19) | int main()
FILE: Hash Table/Count_Pairs_of_Points_With_Distance_k.py
function count_pairs (line 7) | def count_pairs(coordinates, k):
FILE: Hash Table/HashTable.java
class HashTable (line 46) | public class HashTable {
class Node (line 51) | class Node {
method Node (line 57) | Node(String key, int value) {
method HashTable (line 64) | public HashTable() {
method printTable (line 69) | public void printTable() {
method hash (line 81) | public int hash(String key) {
method set (line 92) | public void set(String key, int value) {
method get (line 107) | public int get(String key) {
method keys (line 120) | public ArrayList<String> keys() {
FILE: Hash Table/Longest_substring_without_repeating_characters.py
class Solution (line 26) | class Solution:
method lengthOfLongestSubstring (line 30) | def lengthOfLongestSubstring(self, s: str) -> int:
method lengthOfLongestSubstring (line 47) | def lengthOfLongestSubstring(self, s: str) -> int:
FILE: Hash Table/Partition.java
class PalindromePartitioning (line 4) | public class PalindromePartitioning {
method partition (line 5) | public static List<List<String>> partition(String s) {
method backtrack (line 12) | private static void backtrack(List<List<String>> result, List<String> ...
method isPalindrome (line 27) | private static boolean isPalindrome(String s, int start, int end) {
method main (line 38) | public static void main(String[] args) {
FILE: Hash Table/Partition_string.py
function is_palindrome (line 1) | def is_palindrome(s):
function min_partition (line 4) | def min_partition(s):
FILE: Hash Table/add_first_missing_positive.cpp
function firstMissingPositive (line 20) | int firstMissingPositive(std::vector<int>& nums) {
function main (line 55) | int main() {
FILE: Hash Table/add_first_missing_positive.java
class AddFirstMissingPositive (line 20) | public class AddFirstMissingPositive{
method firstMissingPositive (line 21) | public int firstMissingPositive(int[] nums) {
FILE: Hash Table/find_optimal_partition_of_string.cpp
function main (line 30) | int main(){
FILE: Hash Table/find_optimal_partition_of_string.go
function min (line 19) | func min(x, y int) int {
function isPalindrome (line 26) | func isPalindrome(s string, i, j int) bool {
function minCut (line 37) | func minCut(s string) int {
function main (line 68) | func main() {
FILE: Hash Table/first_duplicate_value.go
function FirstDuplicateValue (line 32) | func FirstDuplicateValue(array []int) int {
function main (line 43) | func main() {
FILE: Hash Table/first_missing_positve.go
function firstMissingPositive (line 49) | func firstMissingPositive(nums []int) int {
FILE: Hash Table/first_missing_positve.js
function firstMissingPositive (line 55) | function firstMissingPositive(nums) {
FILE: Hash Table/first_missing_positve.py
function firstMissingPositive (line 42) | def firstMissingPositive(nums):
FILE: Hash Table/first_non_repeated_character.go
function FirstNonRepeatingCharacter (line 29) | func FirstNonRepeatingCharacter(str string) int {
function main (line 50) | func main() {
FILE: Hash Table/first_repeated_character.go
function FirstRepeatedCCharacter (line 9) | func FirstRepeatedCCharacter(word string) byte {
function main (line 31) | func main() {
FILE: Hash Table/four_number_sum.java
class FourNumberSum (line 20) | public class FourNumberSum {
method main (line 21) | public static void main(String[] args) {
method solve (line 31) | public static List<Integer[]> solve(int[] array, int targetSum) {
FILE: Hash Table/frequency_of_elements.java
class FrequencyOfElements (line 61) | public class FrequencyOfElements {
method main (line 62) | public static void main(String[] args) {
method solve (line 70) | public static int[] solve(int[] nums, int[] queries) {
FILE: Hash Table/group_anagrams.cpp
function groupAnagrams (line 33) | vector<vector<string>> groupAnagrams(vector<string>& strs) {
function main (line 51) | int main() {
FILE: Hash Table/group_anagrams.go
function groupAnagrams (line 37) | func groupAnagrams(strs []string) [][]string {
function sortString (line 61) | func sortString(s string) string {
function main (line 66) | func main() {
FILE: Hash Table/group_anagrams.java
class group_anagrams (line 25) | public class group_anagrams{
method groupAnagrams (line 27) | public List<List<String>> groupAnagrams(String[] strs) {
method main (line 51) | public static void main(String[] args) {
FILE: Hash Table/group_anagrams.js
function groupAnagrams (line 30) | function groupAnagrams(strs) {
FILE: Hash Table/group_anagrams.py
function groupAnagrams (line 28) | def groupAnagrams(strs):
FILE: Hash Table/integer_to_roman.cpp
function string (line 16) | string intToRoman(int num) {
function main (line 41) | int main() {
FILE: Hash Table/integer_to_roman.go
function intToRoman (line 16) | func intToRoman(num int) string {
function main (line 33) | func main() {
FILE: Hash Table/integer_to_roman.java
method intToRoman (line 14) | public static String intToRoman(int num) {
FILE: Hash Table/integer_to_roman.js
function intToRoman (line 8) | function intToRoman(num) {
FILE: Hash Table/integer_to_roman.py
function intToRoman (line 16) | def intToRoman(num: int) -> str:
FILE: Hash Table/remove_duplicates.go
function RemoveDuplicates (line 10) | func RemoveDuplicates(word string) string {
function main (line 25) | func main() {
FILE: Hash Table/roman_to_integer.cpp
class Solution (line 48) | class Solution {
method romanToInt (line 50) | int romanToInt(string s) {
FILE: Hash Table/roman_to_integer.go
function romanToInt (line 24) | func romanToInt(s string) int {
function main (line 60) | func main() {
FILE: Hash Table/roman_to_integer.java
class Solution (line 2) | class Solution {
method romanToInt (line 3) | public int romanToInt(String s) {
FILE: Hash Table/roman_to_integer.py
function roman_to_int (line 15) | def roman_to_int(s: str) -> int:
FILE: Hash Table/sum_of_unique_elements.java
class Solution (line 31) | class Solution {
method sumOfUnique (line 32) | public int sumOfUnique(int[] nums) {
class SumOfUniqueElements (line 50) | class SumOfUniqueElements {
method main (line 51) | public static void main(String[] args) {
FILE: Hash Table/three_number_sum.java
class ThreeNumberSum (line 20) | public class ThreeNumberSum {
method main (line 22) | public static void main(String[] args){
method solve (line 28) | public static List<Integer[]> solve(int[] array, int targetSum) {
FILE: Hash Table/two_sum.cpp
function twoNumberSum (line 14) | std::vector<int> twoNumberSum(std::vector<int>& nums, int target) {
function main (line 37) | int main() {
FILE: Hash Table/two_sum.go
function TwoNUmberSumBruteForce (line 19) | func TwoNUmberSumBruteForce(array []int, target int) []int {
function TwoNumberSumTwoPointerMethod (line 40) | func TwoNumberSumTwoPointerMethod(array []int, target int) []int {
function TwoNumberSum (line 66) | func TwoNumberSum(array []int, target int) []int {
function main (line 89) | func main() {
FILE: Hash Table/two_sum.java
class TwoNumberSum (line 12) | public class TwoNumberSum {
method main (line 14) | public static void main(String[] args) {
method TwoSumBruteForce (line 22) | public static int[] TwoSumBruteForce(int[] array, int targetSum) {
method TwoSumBySorting (line 36) | public static int[] TwoSumBySorting(int[] array, int targetSum) {
method TwoSumOptimal (line 54) | public static int[] TwoSumOptimal(int[] array, int targetSum) {
FILE: Hash Table/two_sum.js
function twoNumberSum (line 10) | function twoNumberSum(nums, target) {
FILE: Hash Table/two_sum.py
class Solution (line 13) | class Solution:
method twoSum (line 14) | def twoSum(self, nums: List[int], target: int) -> List[int]:
method twoSum (line 25) | def twoSum(self, nums: List[int], target: int) -> List[int]:
class Solution (line 24) | class Solution:
method twoSum (line 14) | def twoSum(self, nums: List[int], target: int) -> List[int]:
method twoSum (line 25) | def twoSum(self, nums: List[int], target: int) -> List[int]:
FILE: Hash Table/zero_sum_subarray.cpp
function zeroSumSubarray (line 28) | vector<int> zeroSumSubarray(vector<int>& nums) {
function main (line 47) | int main() {
FILE: Hash Table/zero_sum_subarray.go
function ZeroSumSubarray (line 26) | func ZeroSumSubarray(nums []int) bool {
function main (line 39) | func main() {
FILE: Hash Table/zero_sum_subarray.java
class ZeroSumSubarray (line 11) | public class ZeroSumSubarray {
method hasZeroSumSubarray (line 13) | public static boolean hasZeroSumSubarray(int[] nums) {
method main (line 26) | public static void main(String[] args) {
FILE: Hash Table/zero_sum_subarray.js
function hasZeroSumSubarray (line 21) | function hasZeroSumSubarray(nums) {
FILE: Hash Table/zero_sum_subarray.py
function zero_sum_subarray (line 22) | def zero_sum_subarray(nums):
FILE: Heaps/heap.cpp
class MinHeap (line 44) | class MinHeap {
method buildHeap (line 48) | void buildHeap(std::vector<int>& array) {
method siftDown (line 55) | void siftDown(int currentIndex, int endIndex) {
method siftUp (line 78) | void siftUp() {
method peek (line 95) | int peek() {
method remove (line 102) | int remove() {
method insert (line 111) | void insert(int value) {
method swap (line 116) | void swap(int i, int j) {
method length (line 122) | int length() {
function MinHeap (line 127) | MinHeap* newMinHeap(std::vector<int>& array) {
method buildHeap (line 48) | void buildHeap(std::vector<int>& array) {
method siftDown (line 55) | void siftDown(int currentIndex, int endIndex) {
method siftUp (line 78) | void siftUp() {
method peek (line 95) | int peek() {
method remove (line 102) | int remove() {
method insert (line 111) | void insert(int value) {
method swap (line 116) | void swap(int i, int j) {
method length (line 122) | int length() {
FILE: Heaps/heap.go
type MinHeap (line 45) | type MinHeap
method BuildHeap (line 58) | func (h *MinHeap) BuildHeap(array []int) {
method siftDown (line 68) | func (h *MinHeap) siftDown(currentIndex, endIndex int) {
method siftUp (line 90) | func (h *MinHeap) siftUp() {
method Peek (line 106) | func (h MinHeap) Peek() int {
method Remove (line 114) | func (h *MinHeap) Remove() int {
method Insert (line 124) | func (h *MinHeap) Insert(value int) {
method swap (line 130) | func (h MinHeap) swap(i, j int) {
method length (line 135) | func (h MinHeap) length() int {
function NewMinHeap (line 48) | func NewMinHeap(array []int) *MinHeap {
FILE: Heaps/heap.java
class MinHeap (line 44) | public class MinHeap {
method MinHeap (line 48) | public MinHeap(int[] array) {
method buildHeap (line 54) | private void buildHeap() {
method siftDown (line 61) | private void siftDown(int currentIndex) {
method siftUp (line 84) | private void siftUp() {
method peek (line 101) | public int peek() {
method remove (line 108) | public int remove() {
method insert (line 116) | public void insert(int value) {
method swap (line 125) | private void swap(int i, int j) {
method length (line 131) | public int length() {
class Main (line 136) | public class Main {
method main (line 137) | public static void main(String[] args) {
FILE: Heaps/heap.js
class MinHeap (line 42) | class MinHeap {
method constructor (line 43) | constructor(array) {
method buildHeap (line 49) | buildHeap() {
method siftDown (line 56) | siftDown(currentIndex) {
method siftUp (line 79) | siftUp() {
method peek (line 96) | peek() {
method remove (line 103) | remove() {
method insert (line 112) | insert(value) {
method swap (line 118) | swap(i, j) {
method length (line 122) | length() {
FILE: Heaps/heap.py
class MinHeap (line 42) | class MinHeap:
method __init__ (line 43) | def __init__(self):
method build_heap (line 46) | def build_heap(self, array):
method sift_down (line 52) | def sift_down(self, current_idx, end_idx):
method sift_up (line 70) | def sift_up(self):
method peek (line 83) | def peek(self):
method remove (line 88) | def remove(self):
method insert (line 95) | def insert(self, value):
method swap (line 99) | def swap(self, i, j):
method length (line 102) | def length(self):
function new_min_heap (line 106) | def new_min_heap(array):
FILE: Heaps/k_closest.py
class Solution (line 1) | class Solution:
method kClosest (line 2) | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
FILE: Linked List/Intersection_LL.cpp
class Solution (line 9) | class Solution {
method ListNode (line 11) | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
FILE: Linked List/LFU_Cache.cpp
class LFUCache (line 27) | class LFUCache {
method LFUCache (line 35) | LFUCache(int capacity) {
method get (line 41) | int get(int key) {
method put (line 56) | void put(int key, int value) {
FILE: Linked List/Linked_List_Component.java
class Solution (line 40) | class Solution {
method numComponents (line 41) | public int numComponents(ListNode head, int[] nums) {
FILE: Linked List/MiddleOfLinkedList.java
class Solution (line 36) | class Solution {
method middleNode (line 37) | public ListNode middleNode(ListNode head) {
FILE: Linked List/MiddleofLL.py
class ListNode (line 1) | class ListNode:
method __init__ (line 2) | def __init__(self, value=0, next=None):
function find_middle (line 6) | def find_middle(head):
FILE: Linked List/RemoveKthNodeFromEnd.java
class Solution (line 63) | class Solution {
method calcLength (line 65) | public int calcLength(ListNode head) {
method removeNthFromEnd (line 74) | public ListNode removeNthFromEnd(ListNode head, int n) {
FILE: Linked List/Remove_nth_node_from_end.java
class Solution (line 36) | class Solution {
method removeNthFromEnd (line 37) | public ListNode removeNthFromEnd(ListNode head, int n) {
method size (line 64) | int size(ListNode temp) {
FILE: Linked List/add_two_numbers.cpp
class Solution (line 11) | class Solution
method ListNode (line 14) | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
method ListNode (line 54) | ListNode *solve(ListNode *&head1, ListNode *&head2)
FILE: Linked List/delete_kth_node.js
class Node (line 17) | class Node {
method constructor (line 18) | constructor(value) {
function removeKthFromEnd (line 23) | function removeKthFromEnd(head, k) {
FILE: Linked List/double_linked_list.go
type Node (line 19) | type Node struct
type LinkedList (line 26) | type LinkedList struct
method AddNode (line 32) | func (list *LinkedList) AddNode(data int) {
method PrintList (line 54) | func (list *LinkedList) PrintList() {
function main (line 65) | func main() {
FILE: Linked List/doubly_linked_list.cpp
class Node (line 68) | class Node {
method Node (line 73) | Node(int d) {
function PrintForward (line 81) | void PrintForward(Node* head) {
function PrintBackward (line 90) | void PrintBackward(Node* tail) {
function main (line 98) | int main() {
FILE: Linked List/doubly_linked_list.java
class Node (line 3) | class Node {
method Node (line 8) | public Node(int data) {
class DoublyLinkedList (line 15) | class DoublyLinkedList {
method DoublyLinkedList (line 18) | public DoublyLinkedList() {
method insert (line 23) | public void insert(int data) {
method delete (line 44) | public void delete(int data) {
method display (line 76) | public void display() {
class Main (line 88) | public class Main {
method main (line 89) | public static void main(String[] args) {
FILE: Linked List/doubly_linked_list.js
class Node (line 1) | class Node {
method constructor (line 2) | constructor(val) {
class DoublyLinkedList (line 9) | class DoublyLinkedList {
method constructor (line 10) | constructor() {
method insertAtTail (line 16) | insertAtTail(val) {
method insertAtHead (line 31) | insertAtHead(val) {
method deleteAtTail (line 46) | deleteAtTail() {
method deleteAtHead (line 60) | deleteAtHead() {
method print (line 74) | print() {
method getLength (line 93) | getLength() {
method getAtIdx (line 97) | getAtIdx(idx) {
method putAtIdx (line 113) | putAtIdx(val, idx) {
method deleteAtIdx (line 139) | deleteAtIdx(idx) {
method search (line 155) | search(val) {
method toArray (line 169) | toArray() {
FILE: Linked List/floyds_cycle_detection.cpp
class Node (line 18) | class Node {
method Node (line 23) | Node(int data)
class Linkedlist (line 32) | class Linkedlist {
method insert (line 35) | void insert(int value)
method detectLoop (line 48) | bool detectLoop()
function main (line 66) | int main()
FILE: Linked List/floyds_cycle_detection.go
type Node (line 31) | type Node struct
function hasCycle (line 38) | func hasCycle(head *Node) bool {
function main (line 57) | func main() {
FILE: Linked List/floyds_cycle_detection.java
class GFG (line 17) | class GFG{
class Node (line 19) | static class Node {
method Node (line 23) | Node(int data)
class Linkedlist (line 32) | static class Linkedlist {
method insert (line 34) | void insert(int value)
method detectLoop (line 47) | boolean detectLoop()
method main (line 65) | public static void main(String[] args)
FILE: Linked List/intersection_of_two_linked_lists.cpp
class Solution (line 33) | class Solution {
method ListNode (line 35) | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
FILE: Linked List/liniked_list_sort_list.cpp
class Solution (line 32) | class Solution {
method ListNode (line 34) | ListNode* compute_midpoint(ListNode* head){
method ListNode (line 46) | ListNode* merge_two_lists(ListNode* A, ListNode* B){
method ListNode (line 62) | ListNode* sortList(ListNode* head) {
FILE: Linked List/linked_list.go
type node (line 9) | type node struct
type linkedlist (line 14) | type linkedlist struct
method PushBack (line 20) | func (ll *linkedlist) PushBack(n *node) {
method Front (line 34) | func (ll linkedlist) Front() (int, error) {
method Back (line 41) | func (ll linkedlist) Back() (int, error) {
method DeleteFromFront (line 48) | func (ll *linkedlist) DeleteFromFront() {
method DeleteFromBack (line 57) | func (ll *linkedlist) DeleteFromBack() {
method Display (line 74) | func (ll linkedlist) Display() {
function main (line 81) | func main() {
FILE: Linked List/linked_list.js
class Node (line 16) | class Node {
method constructor (line 17) | constructor(val) {
class LinkedList (line 23) | class LinkedList {
method constructor (line 24) | constructor() {
method insertAtTail (line 30) | insertAtTail(val) {
method insertAtHead (line 44) | insertAtHead(val) {
method print (line 58) | print() {
method deleteAtTail (line 73) | deleteAtTail() {
method deleteAtHead (line 91) | deleteAtHead() {
method getLength (line 102) | getLength() {
method getAtIdx (line 106) | getAtIdx (idx) {
method putAtIdx (line 122) | putAtIdx (val, idx) {
method deleteAtIdx (line 148) | deleteAtIdx (idx) {
method search (line 167) | search (val) {
method toArray (line 184) | toArray () {
method reverse (line 198) | reverse () {
FILE: Linked List/linked_list.py
class Node (line 15) | class Node:
method __init__ (line 16) | def __init__(self, data):
class LinkedList (line 22) | class LinkedList:
method __init__ (line 23) | def __init__(self):
method insert_at_beginning (line 28) | def insert_at_beginning(self, data):
method insert_at_end (line 39) | def insert_at_end(self, data):
method delete_node (line 57) | def delete_node(self, data):
method print_list (line 76) | def print_list(self):
FILE: Linked List/linked_list_add_two_numbers.py
class Solution (line 37) | class Solution:
method addTwoNumbers (line 38) | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]...
FILE: Linked List/linked_list_compute_middle.cpp
class Node (line 16) | class Node
method Node (line 22) | Node()
method Node (line 27) | Node(int data)
function Node (line 34) | Node *middleNode(Node *head)
method Node (line 22) | Node()
method Node (line 27) | Node(int data)
function main (line 55) | int main()
FILE: Linked List/linked_list_compute_middle.java
class ListNode (line 5) | class ListNode {
method ListNode (line 9) | ListNode(int val) {
class FindMiddleLinkedList (line 15) | class FindMiddleLinkedList {
method findMiddle (line 16) | public ListNode findMiddle(ListNode head) {
method main (line 31) | public static void main(String[] args) {
FILE: Linked List/linked_list_delete_at_any_pos.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function length (line 15) | int length(node* head){
function insert_at_head (line 23) | void insert_at_head(node *&head, int data){
function insert_at_tail (line 28) | void insert_at_tail(node *&head, int data){
function insert_at_anypos (line 40) | void insert_at_anypos(node *&head, int data, int pos){
function delete_at_head (line 57) | void delete_at_head(node *&head){
function delete_at_tail (line 65) | void delete_at_tail(node *&head){
function delete_at_any_pos (line 75) | void delete_at_any_pos(node *&head, int pos){
function print_linked_list (line 94) | void print_linked_list(node *head){
function main (line 100) | int main(){
FILE: Linked List/linked_list_delete_at_head.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_head (line 15) | void insert_at_head(node *&head, int data){
function delete_at_head (line 20) | void delete_at_head(node *&head){
function print_linked_list (line 28) | void print_linked_list(node *head){
function main (line 34) | int main(){
FILE: Linked List/linked_list_delete_at_tail.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function delete_at_tail (line 28) | void delete_at_tail(node *&head){
function print_linked_list (line 38) | void print_linked_list(node *head){
function main (line 44) | int main(){
FILE: Linked List/linked_list_delete_node.go
function deleteNode (line 13) | func deleteNode(node *ListNode) {
FILE: Linked List/linked_list_even_or_odd.go
type node (line 12) | type node struct
type LinkedList (line 17) | type LinkedList struct
method IsLengthEven (line 23) | func (ll *LinkedList) IsLengthEven() bool {
FILE: Linked List/linked_list_find_length.cpp
class node (line 6) | class node{
method node (line 11) | node(int d){
function length (line 16) | int length(node* head){
function insert_at_head (line 24) | void insert_at_head(node *&head, int data){
function print_linked_list (line 29) | void print_linked_list(node *head){
function main (line 35) | int main(){
FILE: Linked List/linked_list_insert_at_any_pos.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function length (line 15) | int length(node* head){
function insert_at_head (line 23) | void insert_at_head(node *&head, int data){
function insert_at_tail (line 28) | void insert_at_tail(node *&head, int data){
function insert_at_anypos (line 40) | void insert_at_anypos(node *&head, int data, int pos){
function print_linked_list (line 57) | void print_linked_list(node *head){
function main (line 63) | int main(){
FILE: Linked List/linked_list_insert_at_head.cpp
class node (line 6) | class node{
method node (line 11) | node(int d){
function insert_at_head (line 16) | void insert_at_head(node *&head, int data){
function print_linked_list (line 21) | void print_linked_list(node *head){
function main (line 27) | int main(){
FILE: Linked List/linked_list_insert_at_tail.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 28) | void print_linked_list(node *head){
function main (line 34) | int main(){
FILE: Linked List/linked_list_kth_from_end.go
function kthFromEnd (line 22) | func kthFromEnd(head *ListNode, n int) *ListNode {
FILE: Linked List/linked_list_kth_node_from_end.cpp
class node (line 5) | class node{
method node (line 9) | node(int d){
function insert_at_tail (line 14) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 26) | void print_linked_list(node *head){
function makeLinkedList (line 32) | void makeLinkedList(node *&head){
function node (line 40) | node* kth_node_from_end(node *head, int k){
method node (line 9) | node(int d){
function main (line 55) | int main(){
FILE: Linked List/linked_list_linear_search.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function linear_search (line 15) | bool linear_search(node *head, int key){
function insert_at_head (line 30) | void insert_at_head(node *&head, int data){
function print_linked_list (line 35) | void print_linked_list(node *head){
function main (line 41) | int main(){
FILE: Linked List/linked_list_merge_k_sorted_lists.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 28) | void print_linked_list(node *head){
function makeLinkedList (line 34) | void makeLinkedList(node *&head){
function istream (line 42) | istream& operator>>(istream &is, node *&head){
function ostream (line 46) | ostream& operator<<(ostream &os, node *&head){
function node (line 50) | node* merge_two_lists(node *a, node *b){
method node (line 10) | node(int d){
function node (line 68) | node* merge_k_lists(node *arr[], int last){
method node (line 10) | node(int d){
function main (line 81) | int main(){
FILE: Linked List/linked_list_merge_two_sorted_linked_list.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 28) | void print_linked_list(node *head){
function makeLinkedList (line 34) | void makeLinkedList(node *&head){
function istream (line 42) | istream& operator>>(istream &is, node *&head){
function ostream (line 46) | ostream& operator<<(ostream &os, node *&head){
function node (line 50) | node* merge_two_lists(node *a, node *b){
method node (line 10) | node(int d){
function main (line 68) | int main(){
FILE: Linked List/linked_list_mergesort_an_unsorted_list.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 15) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 27) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function node (line 41) | node* compute_midpoint(node *head){
method node (line 10) | node(int d){
function istream (line 53) | istream& operator>>(istream &is, node *&head){
function ostream (line 57) | ostream& operator<<(ostream &os, node *&head){
function node (line 61) | node* merge_two_lists(node *a, node *b){
method node (line 10) | node(int d){
function node (line 79) | node* mergeSort(node* head){
method node (line 10) | node(int d){
function main (line 92) | int main(){
FILE: Linked List/linked_list_middle.go
function middleNode (line 30) | func middleNode(head *ListNode) *ListNode {
FILE: Linked List/linked_list_odd_even.cpp
class node (line 5) | class node{
method node (line 9) | node(int d){
function insert_at_tail (line 14) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 26) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function node (line 41) | node* oddEvenLinkedList(node *head){
method node (line 9) | node(int d){
function main (line 57) | int main(){
FILE: Linked List/linked_list_pallindrome.cpp
class Solution (line 41) | class Solution {
method isPalindrome (line 43) | bool isPalindrome(ListNode* head) {
FILE: Linked List/linked_list_recursive_search.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function recursive_search (line 15) | bool recursive_search(node *head, int key){
function insert_at_head (line 26) | void insert_at_head(node *&head, int data){
function print_linked_list (line 31) | void print_linked_list(node *head){
function main (line 37) | int main(){
FILE: Linked List/linked_list_remove_dups.cpp
class Node (line 5) | class Node{
method Node (line 10) | Node(int d){
function insert_at_tail (line 15) | void insert_at_tail(Node *&head, int data){
function print_linked_list (line 27) | void print_linked_list(Node *head){
function make_linked_list (line 33) | void make_linked_list(Node *&head){
function remove_duplicates (line 41) | void remove_duplicates(Node *&head){
function remove_duplicates_without_buffer (line 59) | void remove_duplicates_without_buffer(Node *&head){
function main (line 77) | int main(){
FILE: Linked List/linked_list_remove_kth_node_from_end.py
class node (line 9) | class node:
method __init__ (line 10) | def __init__(self,v=0,n=None):
function create_list (line 16) | def create_list(n):
function print_list (line 26) | def print_list(head):
function __remove_node (line 32) | def __remove_node(prev,curr):
function recursive (line 35) | def recursive(head, n):
function iterative (line 61) | def iterative(head,k):
FILE: Linked List/linked_list_remove_nth_node_from_end.cpp
class Solution (line 46) | class Solution {
method ListNode (line 48) | ListNode* removeNthFromEnd(ListNode* head, int n) {
FILE: Linked List/linked_list_remove_nth_node_from_end.py
class Solution (line 1) | class Solution:
method removeNthFromEnd (line 2) | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Option...
FILE: Linked List/linked_list_reverse.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 15) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 27) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function reverse_linked_list (line 41) | void reverse_linked_list(node *&head){
function main (line 53) | int main(){
FILE: Linked List/linked_list_reverse_recursive.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 15) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 27) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function node (line 42) | node* recursive_reverse(node *head){
method node (line 10) | node(int d){
function main (line 52) | int main(){
FILE: Linked List/linked_list_sum_lists.cpp
class Node (line 7) | class Node{
method Node (line 12) | Node(int d){
function insert_at_head (line 17) | void insert_at_head(Node *&head, int data){
function print_linked_list (line 22) | void print_linked_list(Node *head){
function make_linked_list (line 28) | void make_linked_list(Node *&head){
function Node (line 36) | Node* add_lists(Node *l1, Node *l2, int carry){
method Node (line 12) | Node(int d){
function main (line 57) | int main(){
FILE: Linked List/linked_list_swap_nodes_in_pair.cpp
class node (line 5) | class node{
method node (line 9) | node(int d){
function insert_at_tail (line 14) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 26) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function node (line 41) | node* swapNodesInPairRecursive(node *head){
method node (line 9) | node(int d){
function main (line 51) | int main(){
FILE: Linked List/linked_list_swap_nodes_in_pair_iterative.cpp
class node (line 5) | class node{
method node (line 9) | node(int d){
function insert_at_tail (line 14) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 26) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function node (line 42) | node* swapNodesInPairIterative(node *head){
method node (line 9) | node(int d){
function main (line 62) | int main(){
FILE: Linked List/linked_list_take_input.cpp
class node (line 5) | class node{
method node (line 9) | node(int d){
function insert_at_tail (line 14) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 26) | void print_linked_list(node *head){
function makeLinkedList (line 33) | void makeLinkedList(node *&head){
function main (line 42) | int main(){
FILE: Linked List/linked_list_take_input_as_array_operator_overloading.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 28) | void print_linked_list(node *head){
function makeLinkedList (line 34) | void makeLinkedList(node *&head){
function istream (line 42) | istream& operator>>(istream &is, node *&head){
function ostream (line 46) | ostream& operator<<(ostream &os, node *&head){
function main (line 50) | int main(){
FILE: Linked List/linked_list_take_input_operator_overloading.cpp
class node (line 5) | class node{
method node (line 10) | node(int d){
function insert_at_tail (line 16) | void insert_at_tail(node *&head, int data){
function print_linked_list (line 28) | void print_linked_list(node *head){
function makeLinkedList (line 34) | void makeLinkedList(node *&head){
function istream (line 42) | istream& operator>>(istream &is, node *&head){
function ostream (line 46) | ostream& operator<<(ostream &os, node *&head){
function main (line 50) | int main(){
FILE: Linked List/recursive and iterative in singly linkedlist.py
class ListNode (line 46) | class ListNode:
method __init__ (line 47) | def __init__(self, val=0, next=None):
function create_linked_list (line 51) | def create_linked_list():
function reverse_linked_list_iterative (line 71) | def reverse_linked_list_iterative(head):
function reverse_linked_list_recursive (line 83) | def reverse_linked_list_recursive(head):
function reverse_linked_list (line 93) | def reverse_linked_list(head, method='iterative'):
FILE: Linked List/reverse_linked_list.go
type ListNode (line 22) | type ListNode struct
function ReverseListIteratively (line 28) | func ReverseListIteratively(head *ListNode) *ListNode {
function ReverseListRecursively (line 43) | func ReverseListRecursively(head *ListNode) *ListNode {
function main (line 55) | func main() {
FILE: Linked List/reverse_linked_list.java
class Solution (line 36) | class Solution {
method reverseList (line 37) | public ListNode reverseList(ListNode head) {
FILE: Linked List/singly_linked_list.cpp
type Node (line 31) | struct Node
method Node (line 37) | Node(int val = 0) : data(val), next(nullptr) {}
method Node (line 39) | Node(int val, Node *tempNext) : data(val), next(tempNext) {}
class LinkedList (line 42) | class LinkedList
method LinkedList (line 49) | LinkedList() : head(nullptr)
method insert (line 54) | void insert(int val)
method search (line 74) | bool search(int val)
method remove (line 86) | void remove(int val)
method display (line 118) | void display()
function main (line 130) | int main()
FILE: Linked List/singly_linked_list.go
type node (line 25) | type node struct
type linkedList (line 31) | type linkedList struct
method IsEmpty (line 48) | func (l *linkedList) IsEmpty() bool {
method insertAtTail (line 53) | func (l *linkedList) insertAtTail(val interface{}) {
method insertAtHead (line 70) | func (l *linkedList) insertAtHead(val interface{}) {
method print (line 89) | func (l *linkedList) print() {
method deleteAtTail (line 106) | func (l *linkedList) deleteAtTail() {
method deleteAtHead (line 133) | func (l *linkedList) deleteAtHead() {
method getLength (line 151) | func (l *linkedList) getLength() int {
method getAtIdx (line 156) | func (l *linkedList) getAtIdx(idx int) (interface{}, error) {
method replaceAtIdx (line 171) | func (l *linkedList) replaceAtIdx(val interface{}, idx int) error {
method deleteAtIdx (line 186) | func (l *linkedList) deleteAtIdx(idx int) error {
method search (line 203) | func (l *linkedList) search(val interface{}) (int, error) {
method toArray (line 216) | func (l *linkedList) toArray() []interface{} {
method reverse (line 229) | func (l *linkedList) reverse() error {
function newNode (line 38) | func newNode(val interface{}) *node {
function newLinkedList (line 43) | func newLinkedList() *linkedList {
function reverseListRecursive (line 238) | func reverseListRecursive(head *node) *node {
function main (line 251) | func main() {
FILE: Linked List/singly_linked_list.java
class Node (line 18) | class Node {
method Node (line 22) | Node(int x) // parameterized constructor
class Main (line 29) | class Main
method insertStart (line 31) | static Node insertStart(Node head, int data)
method delete (line 44) | public static Node delete(Node head)
method display (line 58) | static void display(Node node) {
method main (line 68) | public static void main(String args[])
FILE: Linked List/singly_linked_list.py
class Node (line 5) | class Node:
method __init__ (line 6) | def __init__(self, data):
class LinkedList (line 10) | class LinkedList:
method __init__ (line 11) | def __init__(self):
method append (line 14) | def append(self, data):
method prepend (line 24) | def prepend(self, data):
method delete_node (line 29) | def delete_node(self, data):
method print_list (line 42) | def print_list(self):
FILE: Linked List/sll.go
type ListNode (line 20) | type ListNode struct
type LinkedList (line 25) | type LinkedList struct
method Display (line 30) | func (ll *LinkedList) Display() error {
method Length (line 44) | func (ll *LinkedList) Length() int {
method InsertAtBeginning (line 55) | func (ll *LinkedList) InsertAtBeginning(data interface{}) {
method InsertAtEnd (line 71) | func (ll *LinkedList) InsertAtEnd(data interface{}) {
method InsertAtAnyPos (line 91) | func (ll *LinkedList) InsertAtAnyPos(data interface{}, position int) e...
method DeleteFirst (line 118) | func (ll *LinkedList) DeleteFirst() (interface{}, error) {
method DeleteLast (line 131) | func (ll *LinkedList) DeleteLast() (interface{}, error) {
method DeleteFromAnyPos (line 155) | func (ll *LinkedList) DeleteFromAnyPos(position int) (interface{}, err...
FILE: Linked List/sort_linked_list.cpp
class Solution (line 15) | class Solution {
method ListNode (line 17) | ListNode* compute_midpoint(ListNode* head){
method ListNode (line 29) | ListNode* merge_two_lists(ListNode* A, ListNode* B){
method ListNode (line 45) | ListNode* sortList(ListNode* head) {
FILE: Math/Basic_operations.py
function divide (line 1) | def divide(dividend, divisor):
FILE: Math/Factorial.cpp
function factorial (line 22) | unsigned long long factorial(int num) {
function main (line 32) | int main() {
FILE: Math/Factorial.go
function factorial (line 25) | func factorial(n int) int {
function main (line 32) | func main() {
FILE: Math/Factorial.java
class Factorial (line 19) | public class Factorial {
method factorial (line 21) | public static int factorial(int n) {
method main (line 31) | public static void main(String[] args) {
FILE: Math/Factorial.py
function factorial (line 16) | def factorial(num):
FILE: Math/Hamming_distance.py
class Solution (line 22) | class Solution:
method totalHammingDistance (line 23) | def totalHammingDistance(self, nums: List[int]) -> int:
FILE: Math/Hammingdistance.cpp
class Solution (line 3) | class Solution {
method totalHammingDistance (line 5) | int totalHammingDistance(std::vector<int>& nums) {
FILE: Math/K_closest.cpp
class Solution (line 33) | class Solution {
method kClosest (line 35) | vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
function main (line 64) | int main() {
FILE: Math/K_closest_points_to_origin.java
class Solution (line 28) | class Solution {
method kClosest (line 29) | public int[][] kClosest(int[][] points, int k) {
class SortBySmallerDistanceComparator (line 70) | class SortBySmallerDistanceComparator implements Comparator<Pair<Doubl...
method compare (line 72) | @Override
FILE: Math/K_closest_points_to_origin.py
class Solution (line 27) | class Solution:
method kClosest (line 28) | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
FILE: Math/Number_of_Substrings_With_Only_1s.cpp
class Solution (line 34) | class Solution {
method numSub (line 37) | int numSub(string s) {
FILE: Math/PowXn.go
function Pow (line 24) | func Pow(x float64, n int) float64 {
function main (line 34) | func main() {
FILE: Math/PowXn.java
class Solution (line 28) | class Solution {
method myPow (line 29) | public double myPow(double x, int n) {
class PowXn (line 47) | class PowXn {
method main (line 48) | public static void main(String[] args) {
FILE: Math/PowXn.py
function power (line 18) | def power(x, n):
FILE: Math/Reverse_Integer.cpp
function reverse (line 24) | int reverse(int x) {
FILE: Math/Sum_four.cpp
function fourSum (line 7) | vector<vector<int>> fourSum(vector<int>& nums, int target) {
function main (line 61) | int main() {
FILE: Math/circle.cpp
class Solution (line 1) | class Solution {
method if (line 15) | if (isInsideCircle(pointX, pointY, centerX, centerY, radius)) {
function boolean (line 24) | boolean isInsideCircle(int x, int y, int centerX, int centerY, int radiu...
FILE: Math/count_numbers_with_unique_digits.java
class Solution (line 41) | class Solution {
method countNumbersWithUniqueDigits (line 43) | public int countNumbersWithUniqueDigits(int n) {
FILE: Math/count_primes.cpp
class Solution (line 21) | class Solution {
method countPrimes (line 23) | int countPrimes(int n) {
FILE: Math/count_primes.java
class Solution (line 27) | class Solution {
method countPrimes (line 29) | int countPrimes(int n) {
FILE: Math/count_unique_digits.cpp
class Solution (line 14) | class Solution {
method countNumbersWithUniqueDigits (line 23) | int countNumbersWithUniqueDigits(int n) {
FILE: Math/count_unique_digits.go
function countNumbersWithUniqueDigits (line 21) | func countNumbersWithUniqueDigits(n int) int {
function main (line 46) | func main() {
FILE: Math/factorial.py
function factorial (line 16) | def factorial(num):
FILE: Math/factorial_iterative.js
function factorialIterative (line 2) | function factorialIterative(number) {
FILE: Math/find_longest_increasing_subsequence.cpp
class Solution (line 32) | class Solution{
method lengthOfLIS (line 34) | int lengthOfLIS(vector<int> &nums)
FILE: Math/hamming_distance.cpp
class Solution (line 27) | class Solution {
method totalHammingDistance (line 29) | int totalHammingDistance(vector<int>& nums) {
function main (line 45) | int main() {
FILE: Math/is_power_of_two.js
function isPowerOfTwo (line 4) | function isPowerOfTwo(inputNumber) {
function isPowerOfTwoConst (line 21) | function isPowerOfTwoConst(inputNumber) {
function isPowerOfTwoConst (line 33) | function isPowerOfTwoConst(inputNumber) {
FILE: Math/is_prime.js
function isPrime (line 3) | function isPrime(input) {
function isPrimeLogn (line 30) | function isPrimeLogn(input) {
FILE: Math/k_closest_points_to_origin.cpp
class Solution (line 16) | class Solution {
method kClosest (line 18) | vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
FILE: Math/modular_expo_itera.cpp
function modular_expo (line 9) | int modular_expo(int x, int n, int mod){
function main (line 23) | int main(){
FILE: Math/modular_expo_recursive.cpp
function modular_expo (line 9) | int modular_expo(int x, int n, int mod){
function main (line 20) | int main(){
FILE: Math/num_points_inside_a_circle.cpp
class Solution (line 33) | class Solution
method countPoints (line 36) | vector<int> countPoints(vector<vector<int>> &points, vector<vector<int...
FILE: Math/num_points_inside_a_circle.py
class Solution (line 29) | class Solution:
method countPoints (line 30) | def countPoints(self, points: list[list[int]], queries: list[list[int]...
FILE: Math/num_steps_reduce_to_zero.Go
function numberOfSteps (line 32) | func numberOfSteps(num int) int {
FILE: Math/num_steps_reduce_to_zero.cpp
class Solution (line 32) | class Solution {
method numberOfSteps (line 34) | int numberOfSteps(int num) {
FILE: Math/num_steps_reduce_to_zero.java
class Solution (line 32) | class Solution {
method numberOfSteps (line 33) | public int numberOfSteps(int num) {
FILE: Math/num_steps_reduce_to_zero.py
class Solution (line 32) | class Solution(object):
method numberOfSteps (line 33) | def numberOfSteps(self, num):
FILE: Math/op.js
function divide (line 1) | function divide(dividend, divisor) {
FILE: Math/palindrome_number.java
class Solution (line 24) | class Solution {
method isPalindrome (line 25) | public boolean isPalindrome(int x) {
method reverse (line 37) | public int reverse(int n){
FILE: Math/pallindrome_number.cpp
class Solution (line 26) | class Solution {
method isPalindrome (line 28) | bool isPalindrome(int x) {
FILE: Math/pallindrome_number.py
class Solution (line 25) | class Solution:
method isPalindrome (line 26) | def isPalindrome(self, x: int) -> bool:
FILE: Math/powXn.cpp
class Solution (line 34) | class Solution {
method pow (line 36) | double pow(double x, int n)
method myPow (line 45) | double myPow(double x, int n) {
FILE: Math/powXn.js
function pow (line 4) | function pow(x, n) {
FILE: Math/prime_factorization.cpp
function prime_factor (line 12) | void prime_factor(int n){
function main (line 39) | int main(){
FILE: Math/shuffle_an_array.cpp
class Solution (line 32) | class Solution {
method Solution (line 37) | Solution(vector<int>& nums) {
method reset (line 46) | vector<int> reset() {
method shuffle (line 51) | vector<int> shuffle() {
FILE: Math/shuffle_an_array.py
class Solution (line 5) | class Solution:
method __init__ (line 7) | def __init__(self, nums: List[int]):
method reset (line 12) | def reset(self) -> List[int]:
method shuffle (line 16) | def shuffle(self) -> List[int]:
FILE: Math/sieve_of_eratosthenes.cpp
function seive_of_ero (line 16) | void seive_of_ero(int n){
function main (line 28) | int main(){
FILE: Math/substrings_with_1s.py
function numSub (line 18) | def numSub(self, s: str) -> int:
FILE: Math/unique_digits.py
class Solution (line 16) | class Solution:
method countNumbersWithUniqueDigits (line 17) | def countNumbersWithUniqueDigits(self, n: int) -> int:
FILE: Math/unique_integers_that_sum_up_to_0.cpp
class Solution (line 21) | class Solution {
method sumZero (line 23) | vector<int> sumZero(int n) {
FILE: Misc/tictactoe.java
class TicTacToe (line 39) | public class TicTacToe {
method TicTacToe (line 45) | public TicTacToe() {
method clearBoard (line 48) | public void clearBoard() {
method putMark (line 55) | public void putMark(int i, int j) throws IllegalArgumentException {
method isWin (line 64) | public boolean isWin(int mark) {
method winner (line 75) | public int winner() {
method toString (line 84) | public String toString() {
method main (line 100) | public static void main(String[] args) {
FILE: Patterns/CompleteSquare.java
class CompleteSquare (line 15) | public class CompleteSquare {
method main (line 17) | public static void main(String[] args) {
FILE: Patterns/HollowPattern.cpp
function printHollowPattern (line 28) | void printHollowPattern(int n) {
function main (line 45) | int main() {
FILE: Patterns/HollowPattern.go
function printHollowPattern (line 30) | func printHollowPattern(n int) {
function main (line 47) | func main() {
FILE: Patterns/HollowPattern.java
class HollowPattern (line 28) | public class HollowPattern {
method printHollowPattern (line 29) | public static void printHollowPattern(int n) {
method main (line 46) | public static void main(String[] args) {
FILE: Patterns/HollowPattern.py
function print_hollow_pattern (line 31) | def print_hollow_pattern(n):
FILE: Patterns/Ladder_Pattern.java
class LadderPattern (line 20) | public class LadderPattern {
method main (line 21) | public static void main(String[] args) {
method printSideRail (line 36) | public static void printSideRail() {
method printStep (line 41) | public static void printStep(int stepNumber) {
FILE: Patterns/ReverseRightTrianglePattern.java
class ReverseRightTrianglePattern (line 19) | public class ReverseRightTrianglePattern {
method main (line 21) | public static void main(String[] args) {
method pattern (line 26) | public static void pattern(int size) {
FILE: Patterns/RightPascalTriangle.java
class RightPascalTriangle (line 21) | public class RightPascalTriangle {
method main (line 23) | public static void main(String[] args) {
method pattern (line 28) | public static void pattern(int size) {
FILE: Patterns/StarDiamond.java
class StarDiamond (line 16) | public class StarDiamond {
method main (line 18) | public static void main(String[] args) {
method pattern (line 23) | public static void pattern(int size) {
FILE: Patterns/diamond_pattern.cpp
function printDiamondPattern (line 35) | void printDiamondPattern(int n) {
function main (line 67) | int main() {
FILE: Patterns/diamond_pattern.go
function printSpaces (line 39) | func printSpaces(num int) {
function printStars (line 45) | func printStars(num int) {
function printDiamondPattern (line 51) | func printDiamondPattern(n int) {
function main (line 67) | func main() {
FILE: Patterns/diamond_pattern.java
class DiamondPattern (line 25) | public class DiamondPattern {
method main (line 27) | public static void main(String[] args) {
method printDiamondPattern (line 32) | public static void printDiamondPattern(int n) {
FILE: Patterns/diamond_pattern.py
function print_diamond_pattern (line 24) | def print_diamond_pattern(n):
FILE: Patterns/numerical_pattern.java
class NumericalPattern (line 35) | public class NumericalPattern {
method printPattern (line 36) | public static void printPattern(int n) {
method main (line 45) | public static void main(String[] args) {
FILE: Patterns/triangular_pattern.java
class triangular_pattern (line 26) | public class triangular_pattern {
method main (line 27) | public static void main(String[] args) {
FILE: Patterns/triangular_pattern.py
function print_triangular_pattern (line 28) | def print_triangular_pattern(n):
FILE: Priority Queues/In_Place_HeapSort.cpp
function heapSort (line 44) | void heapSort(int arr[], int n)
function main (line 119) | int main()
FILE: Priority Queues/buy_the_ticket.cpp
function buyTicket (line 70) | int buyTicket(int *arr, int n, int k)
function main (line 118) | int main()
FILE: Priority Queues/check_max_heap.cpp
function isMaxHeap (line 41) | bool isMaxHeap(int arr[], int n)
function main (line 65) | int main()
FILE: Priority Queues/kth_largest_element.cpp
function kthLargest (line 51) | int kthLargest(int *arr, int n, int k)
function main (line 78) | int main()
FILE: Priority Queues/kth_smallest_element.cpp
function kSmallest (line 50) | vector<int> kSmallest(int arr[], int n, int k)
function main (line 83) | int main()
FILE: Priority Queues/merge_k_sorted_arrays.cpp
function mergeKSortedArrays (line 51) | vector<int> mergeKSortedArrays(vector<vector<int> *> input)
function main (line 94) | int main()
FILE: Priority Queues/running_median.cpp
function findMedian (line 71) | void findMedian(int *arr, int n)
function main (line 129) | int main()
FILE: Queue/queue.cpp
class Queue (line 16) | class Queue {
method Queue (line 21) | Queue() {
method isFull (line 26) | bool isFull() {
method isEmpty (line 30) | bool isEmpty() {
method enqueue (line 34) | void enqueue(int x) {
method dequeue (line 48) | void dequeue() {
method peek (line 61) | int peek() {
method print (line 69) | void print() {
function main (line 82) | int main() {
FILE: Queue/queue.go
type Queue (line 21) | type Queue struct
method IsEmpty (line 34) | func (q *Queue) IsEmpty() bool {
method Enqueue (line 39) | func (q *Queue) Enqueue(val int) {
method Dequeue (line 52) | func (q *Queue) Dequeue() (int, error) {
function NewQueue (line 28) | func NewQueue() *Queue {
function main (line 75) | func main() {
FILE: Queue/queue.java
class Queue (line 10) | public class Queue {
method Queue (line 17) | public Queue(int size) {
method enqueue (line 25) | public void enqueue(int item) {
method dequeue (line 38) | public int dequeue() {
method isEmpty (line 52) | public boolean isEmpty() {
method isFull (line 56) | public boolean isFull() {
method size (line 60) | public int size() {
method Queue (line 81) | public Queue() {
class Node (line 87) | private static class Node<T> {
method Node (line 91) | public Node(T data) {
method enqueue (line 97) | public void enqueue(T item) {
method dequeue (line 108) | public T dequeue() {
method isEmpty (line 122) | public boolean isEmpty() {
method size (line 126) | public int size() {
class Queue (line 76) | public class Queue<T> {
method Queue (line 17) | public Queue(int size) {
method enqueue (line 25) | public void enqueue(int item) {
method dequeue (line 38) | public int dequeue() {
method isEmpty (line 52) | public boolean isEmpty() {
method isFull (line 56) | public boolean isFull() {
method size (line 60) | public int size() {
method Queue (line 81) | public Queue() {
class Node (line 87) | private static class Node<T> {
method Node (line 91) | public Node(T data) {
method enqueue (line 97) | public void enqueue(T item) {
method dequeue (line 108) | public T dequeue() {
method isEmpty (line 122) | public boolean isEmpty() {
method size (line 126) | public int size() {
FILE: Queue/queue.js
class Queue (line 10) | class Queue {
method constructor (line 11) | constructor() {
method enqueue (line 15) | enqueue(element) {
method dequeue (line 19) | dequeue() {
method front (line 26) | front() {
method isEmpty (line 33) | isEmpty() {
method printQueue (line 37) | printQueue() {
method constructor (line 62) | constructor() {
method enqueue (line 68) | enqueue(data) {
method dequeue (line 80) | dequeue() {
method isEmpty (line 93) | isEmpty() {
method getFront (line 97) | getFront() {
method printQueue (line 101) | printQueue() {
class Node (line 54) | class Node {
method constructor (line 55) | constructor(data) {
class Queue (line 61) | class Queue {
method constructor (line 11) | constructor() {
method enqueue (line 15) | enqueue(element) {
method dequeue (line 19) | dequeue() {
method front (line 26) | front() {
method isEmpty (line 33) | isEmpty() {
method printQueue (line 37) | printQueue() {
method constructor (line 62) | constructor() {
method enqueue (line 68) | enqueue(data) {
method dequeue (line 80) | dequeue() {
method isEmpty (line 93) | isEmpty() {
method getFront (line 97) | getFront() {
method printQueue (line 101) | printQueue() {
FILE: Queue/queue.py
class Queue (line 12) | class Queue:
method __init__ (line 13) | def __init__(self):
method is_empty (line 19) | def is_empty(self):
method enqueue (line 25) | def enqueue(self, item):
method dequeue (line 31) | def dequeue(self):
method peek (line 40) | def peek(self):
method size (line 49) | def size(self):
FILE: Queue/queue_using_stacks.go
type MyQueue (line 1) | type MyQueue struct
method Push (line 12) | func (this *MyQueue) Push(x int) {
method Pop (line 17) | func (this *MyQueue) Pop() int {
method Peek (line 27) | func (this *MyQueue) Peek() int {
method Empty (line 35) | func (this *MyQueue) Empty() bool {
method moveElements (line 40) | func (this *MyQueue) moveElements() {
function Constructor (line 7) | func Constructor() MyQueue {
FILE: Queue/queues_using_stacks.py
class Queue (line 25) | class Queue:
method __init__ (line 26) | def __init__(self):
method enqueue (line 31) | def enqueue(self, val):
method dequeue (line 35) | def dequeue(self):
FILE: Queue/stack_using_queue.cpp
class Queue_As_stack (line 54) | class Queue_As_stack {
method PUSH (line 56) | void PUSH(int d) {
method POP (line 79) | void POP()
method TOP (line 85) | int TOP()
method DISPLAY (line 90) | void DISPLAY()
method EMPTY (line 101) | bool EMPTY()
function main (line 113) | int main()
FILE: Recursion/calculatextopowern.cpp
function power1 (line 9) | int power1(int x, int n){
function power (line 16) | int power(int x, int n){
function main (line 26) | int main(){
FILE: Recursion/count_digits.cpp
function count_digits (line 7) | int count_digits(int n){
function main (line 14) | int main(){
FILE: Recursion/count_digits.go
function CountDigits (line 8) | func CountDigits(n int) int {
function main (line 17) | func main() {
FILE: Recursion/count_zeros.cpp
function count_zeros (line 6) | int count_zeros(int n){
function main (line 17) | int main(){
FILE: Recursion/count_zeros.go
function CountZeroes (line 8) | func CountZeroes(n int) int {
function main (line 23) | func main() {
FILE: Recursion/factorial.cpp
function factorial (line 6) | int factorial(int n){
function main (line 14) | int main(){
FILE: Recursion/factorial.go
function Factorial (line 9) | func Factorial(n int) int {
function main (line 16) | func main() {
FILE: Recursion/factorial.js
function recursiveFactorial (line 4) | function recursiveFactorial(number) {
FILE: Recursion/fibonacci.cpp
function fib (line 14) | int fib(int n){
function main (line 19) | int main(){
FILE: Recursion/fibonacci.go
function Fibonacci (line 16) | func Fibonacci(n int) int {
function main (line 23) | func main() {
FILE: Recursion/fibonacci_memoization.cpp
function fib (line 13) | int fib(int n){
function main (line 19) | int main(){
FILE: Recursion/fibonacci_memoization.go
function Fibonacci (line 16) | func Fibonacci(n int) int {
function GetNthFib (line 24) | func GetNthFib(n int) int {
function main (line 39) | func main() {
FILE: Recursion/geometric_sum.cpp
function g_sum (line 3) | double g_sum(int m){
function main (line 9) | int main(){
FILE: Recursion/is_array_sorted.cpp
function is_sorted (line 8) | bool is_sorted(int A[], int m){
function main (line 16) | int main(){
FILE: Recursion/is_array_sorted.go
function isSorted (line 8) | func isSorted(A []int) bool {
function main (line 22) | func main() {
FILE: Recursion/is_element_present.cpp
function is_element_present (line 8) | bool is_element_present(int A[], int m, int key){
function is_element_present2 (line 15) | bool is_element_present2(int A[], int m, int key, int i){
function main (line 22) | int main(){
FILE: Recursion/modular_exponentiation.cpp
function mod (line 10) | int mod(int x, int n, int m){
function main (line 19) | int main(){
FILE: Recursion/multiplication.cpp
function multiply (line 6) | int multiply(int n, int m){
function main (line 12) | int main(){
FILE: Recursion/powerset.cpp
function powerset (line 45) | vector<vector<int>> powerset(vector<int>& array, int index) {
function Powerset (line 73) | vector<vector<int>> Powerset(vector<int>& array) {
function powerset (line 79) | vector<vector<int>> powerset(vector<int>& array) {
FILE: Recursion/powerset.go
function Powerset (line 44) | func Powerset(array []int) [][]int {
function powerset (line 49) | func powerset(array []int, index int) [][]int {
function PowersetIterative (line 78) | func PowersetIterative(array []int) [][]int {
FILE: Recursion/powerset.java
class Main (line 44) | class Main {
method powerset (line 46) | public static List<List<Integer>> powerset(int[] array, int index) {
method powerset (line 76) | public static List<List<Integer>> powerset(int[] array) {
method main (line 81) | public static void main(String[] args) {
class Powerset (line 94) | public class Powerset {
method powerset (line 95) | public static List<List<Integer>> powerset(int[] array) {
method main (line 122) | public static void main(String[] args) {
FILE: Recursion/powerset.js
function powerset (line 41) | function powerset(array, index) {
function getPowerSet (line 67) | function getPowerSet(array) {
function powersetIterative (line 82) | function powersetIterative(array) {
FILE: Recursion/powerset.py
function powerset (line 41) | def powerset(array):
function Powerset (line 66) | def Powerset(array):
function powersetIterative (line 72) | def powersetIterative(array):
FILE: Recursion/print_numbers.cpp
function print (line 6) | void print(int n){
function main (line 12) | int main(){
FILE: Recursion/recursive_bubble_sort.cpp
function bubble_sort (line 16) | void bubble_sort(int *A, int len){
function main (line 26) | int main(){
FILE: Recursion/reverse_print.go
function print (line 6) | func print(n int) int {
function main (line 14) | func main() {
FILE: Recursion/tower_of_hannoi.cpp
function towerOfHanoi (line 14) | void towerOfHanoi(int numDisks, char fromPeg, char toPeg, char auxPeg) {
function main (line 24) | int main() {
FILE: Recursion/tower_of_hannoi.java
class TowerOfHanoi (line 17) | public class TowerOfHanoi {
method main (line 18) | public static void main(String[] args) {
method solveHanoi (line 28) | public static void solveHanoi(int n, char fromRod, char toRod, char au...
FILE: Recursion/tower_of_hannoi.js
function towerOfHanoi (line 12) | function towerOfHanoi(numDisks, fromPeg, toPeg, auxPeg) {
FILE: Recursion/tower_of_hannoi.py
function TowerOfHanoi (line 14) | def TowerOfHanoi(n, A,B,C):
FILE: Recursion/tower_of_hanoi.go
function TowerOfHanoiHelper (line 16) | func TowerOfHanoiHelper(n int, from, to, temp string) {
function TowersOfHanoi (line 34) | func TowersOfHanoi(n int) {
function main (line 37) | func main() {
FILE: Recursion/valid_palindrome_2.py
class Solution (line 13) | class Solution:
method subPalindrome (line 14) | def subPalindrome(self,s,low,high,count):
method validPalindrome (line 24) | def validPalindrome(self, s: str) -> bool:
FILE: Scheduling Algortihms/fcfs.c
type process (line 49) | typedef struct
function main (line 59) | int main() {
FILE: Scheduling Algortihms/sjf.c
type process (line 54) | typedef struct
function main (line 64) | int main() {
FILE: Scheduling Algortihms/srtf.c
type process (line 67) | typedef struct
function main (line 77) | int main() {
FILE: Scheduling/fcfs.c
type process (line 49) | typedef struct
function main (line 59) | int main() {
FILE: Scheduling/sjf.c
type process (line 54) | typedef struct
function main (line 64) | int main() {
FILE: Scheduling/srtf.c
type process (line 67) | typedef struct
function main (line 77) | int main() {
FILE: Searching/linear_search_string.cpp
function main (line 4) | int main(){
FILE: Searching/semordnilap.go
function Semordnilap (line 16) | func Semordnilap(words []string) [][]string {
function reverse (line 37) | func reverse(s string) string {
FILE: Searching/separate_0s_and_1s.go
function SeparateZerosAndOnes (line 9) | func SeparateZerosAndOnes(Arr []int) []int {
function main (line 29) | func main() {
FILE: Searching/separate_even_odd.go
function SeparateEvenAndOdd (line 9) | func SeparateEvenAndOdd(Arr []int) []int {
function main (line 29) | func main() {
FILE: Sliding Window/find_max.go
function printKMax (line 30) | func printKMax(arr []int, N int, K int) {
function main (line 47) | func main() {
FILE: Sliding Window/fruits_into_basket.cpp
function totalFruit (line 45) | int totalFruit(vector<int>& fruits) {
function main (line 71) | int main() {
FILE: Sliding Window/fruits_into_basket.go
function totalFruit (line 43) | func totalFruit(fruits []int) int {
function main (line 71) | func main() {
FILE: Sliding Window/fruits_into_basket.java
class Solution (line 39) | class Solution {
method totalFruit (line 40) | public int totalFruit(int[] fruits) {
FILE: Sliding Window/fruits_into_basket.py
class Solution (line 39) | class Solution:
method totalFruit (line 40) | def totalFruit(self, fruits):
FILE: Sliding Window/longest_repeated_character_replacement.cpp
class Solution (line 36) | class Solution {
method characterReplacement (line 38) | int characterReplacement(std::string s, int k) {
FILE: Sliding Window/longest_repeated_character_replacement.go
function characterReplacement (line 32) | func characterReplacement(s string, k int) int {
function maxInt (line 59) | func maxInt(a, b int) int {
FILE: Sliding Window/longest_repeated_character_replacement.java
class Solution (line 32) | class Solution {
method characterReplacement (line 33) | public int characterReplacement(String s, int k) {
FILE: Sliding Window/longest_repeated_character_replacement.js
class Solution (line 32) | class Solution {
method characterReplacement (line 33) | characterReplacement(s, k) {
FILE: Sliding Window/longest_repeated_character_replacement.py
class Solution (line 32) | class Solution:
method characterReplacement (line 33) | def characterReplacement(self, s: str, k: int) -> int:
FILE: Sliding Window/longest_substring_with_k_distinct_chars.go
function longestSubstringWithKDistinctChars (line 11) | func longestSubstringWithKDistinctChars(s string, k int) int {
function max (line 40) | func max(a, b int) int {
function main (line 47) | func main() {
FILE: Sliding Window/longest_substring_with_k_distinct_chars.java
class LongestSubstringWithKDistinctChars (line 6) | public class LongestSubstringWithKDistinctChars {
method longestSubstringWithKDistinctChars (line 7) | public int longestSubstringWithKDistinctChars(String s, int k) {
method main (line 37) | public static void main(String[] args) {
FILE: Sliding Window/longest_substring_with_k_distinct_chars.js
function longestSubstringWithKDistinctChars (line 5) | function longestSubstringWithKDistinctChars(s, k) {
function max (line 35) | function max(a, b) {
FILE: Sliding Window/longest_substring_with_k_distinct_chars.py
function longestSubstringWithKDistinctChars (line 5) | def longestSubstringWithKDistinctChars(s, k):
function max (line 30) | def max(a, b):
FILE: Sliding Window/longest_substring_without_repeating_characters.go
function LengthOfLongestSubstring1 (line 35) | func LengthOfLongestSubstring1(s string) int {
function max (line 47) | func max(a, b int) int {
function check (line 54) | func check(s string, start int, end int) bool {
function LengthOfLongestSubstring2 (line 67) | func LengthOfLongestSubstring2(s string) int {
FILE: Sliding Window/max_eraser_value.go
function maximumUniqueSubarray (line 48) | func maximumUniqueSubarray(nums []int) int {
function main (line 78) | func main() {
FILE: Sliding Window/max_eraser_value.java
class Solution (line 44) | class Solution {
method maximumUniqueSubarray (line 45) | public int maximumUniqueSubarray(int[] nums) {
FILE: Sliding Window/sliding_window_max.java
class SlidingWindowMax (line 6) | public class SlidingWindowMax {
method findMaxSlidingWindow (line 7) | public static int[] findMaxSlidingWindow(int[] nums, int windowSize) {
method main (line 40) | public static void main(String[] args) {
FILE: Sliding Window/sliding_window_max.js
function findMaxSlidingWindow (line 4) | function findMaxSlidingWindow(nums, windowSize) {
FILE: Sliding Window/sliding_window_max.py
function slidingWindowMax (line 5) | def slidingWindowMax(arr,windowSize) -> list[int]:
FILE: Sliding Window/subaray_sum_equals_k.cpp
function subarraySum (line 61) | int subarraySum(std::vector<int>& nums, int k) {
function main (line 95) | int main() {
FILE: Sliding Window/subaray_sum_equals_k.go
function subarraySum (line 57) | func subarraySum(nums []int, k int) int {
FILE: Sliding Window/subaray_sum_equals_k.java
method subarraySum (line 57) | public int subarraySum(int[] nums, int k) {
FILE: Sliding Window/subaray_sum_equals_k.js
function subarraySum (line 57) | function subarraySum(nums, k) {
FILE: Sliding Window/subaray_sum_equals_k.py
function subarraySum (line 58) | def subarraySum(nums, k):
FILE: Sliding Window/subarray_product_less_than_k.cpp
class Solution (line 22) | class Solution {
method numSubarrayProductLessThanK (line 24) | int numSubarrayProductLessThanK(std::vector<int>& nums, int k) {
FILE: Sliding Window/subarray_product_less_than_k.go
function numSubarrayProductLessThanK (line 20) | func numSubarrayProductLessThanK(nums []int, k int) int {
FILE: Sliding Window/subarray_product_less_than_k.java
class Solution (line 19) | class Solution {
method numSubarrayProductLessThanK (line 20) | public int numSubarrayProductLessThanK(int[] nums, int k) {
FILE: Sliding Window/subarray_product_less_than_k.py
class Solution (line 21) | class Solution:
method numSubarrayProductLessThanK (line 22) | def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
FILE: Stacks/Stack_with_max_API.cpp
class MaxStack (line 9) | class MaxStack {
method push (line 15) | void push(int val) {
method pop (line 24) | void pop() {
method top (line 33) | int top() {
method max (line 37) | int max() {
method empty (line 41) | bool empty() {
FILE: Stacks/Stacks_using_queues.py
class Stack (line 29) | class Stack:
method __init__ (line 30) | def __init__(self): #The Stack class is defined with a con...
method push (line 33) | def push(self, x: int) -> None:
method pop (line 39) | def pop(self) -> int:
method top (line 42) | def top(self) -> int: #The top method returns the element ...
method empty (line 45) | def empty(self) -> bool: #The empty method returns True if t...
FILE: Stacks/balanced_parenthesis.go
type Stack (line 10) | type Stack struct
method Init (line 17) | func (stack *Stack) Init(capacity uint) *Stack {
method Size (line 31) | func (stack *Stack) Size() uint {
method IsFull (line 37) | func (stack *Stack) IsFull() bool {
method IsEmpty (line 44) | func (stack *Stack) IsEmpty() bool {
method Resize (line 51) | func (stack *Stack) Resize() {
method Push (line 66) | func (stack *Stack) Push(data interface{}) error {
method Pop (line 78) | func (stack *Stack) Pop() (interface{}, error) {
method Peek (line 93) | func (stack *Stack) Peek() (interface{}, error) {
method Drain (line 104) | func (stack *Stack) Drain() {
function NewStack (line 25) | func NewStack(capacity uint) *Stack {
type Pair (line 109) | type Pair struct
function IsValid (line 126) | func IsValid(s string) bool {
function main (line 146) | func main() {
FILE: Stacks/is_palindrome.go
function IsPalindrome (line 5) | func IsPalindrome(s string) bool {
FILE: Stacks/next_greater_element.go
function NextGreaterElement (line 53) | func NextGreaterElement(array []int) []int {
FILE: Stacks/next_greater_element.java
class NextGreaterElement (line 51) | public class NextGreaterElement {
method nextGreaterElement (line 52) | public int[] nextGreaterElement(int[] array) {
FILE: Stacks/next_greater_element.js
function nextGreaterElement (line 49) | function nextGreaterElement(array) {
FILE: Stacks/next_greater_element.py
function next_greater_element (line 49) | def next_greater_element(array):
FILE: Stacks/queue using stack.go
type Queue (line 7) | type Queue struct
method Enqueue (line 13) | func (q *Queue) Enqueue(value int) {
method Dequeue (line 18) | func (q *Queue) Dequeue() int {
function main (line 40) | func main() {
FILE: Stacks/queue using stack.java
class MyQueue (line 51) | class MyQueue
method push (line 56) | public void push(int x)
method pop (line 69) | public int pop()
method peek (line 74) | public int peek()
method empty (line 79) | public boolean empty()
method main (line 83) | public static void main(String[] args)
FILE: Stacks/queue using stack.js
class Queue (line 2) | class Queue {
method constructor (line 3) | constructor() {
method enqueue (line 8) | enqueue(value) {
method dequeue (line 13) | dequeue() {
FILE: Stacks/queue using stack.py
class Queue (line 2) | class Queue:
method __init__ (line 3) | def __init__(self):
method enqueue (line 7) | def enqueue(self, value):
method dequeue (line 11) | def dequeue(self):
FILE: Stacks/queue_using_stacks.cpp
type Queue (line 24) | struct Queue {
method enQueue (line 28) | void enQueue(int x)
method deQueue (line 34) | int deQueue()
function main (line 62) | int main()
FILE: Stacks/reverse_polish_notation.cpp
class Solution (line 44) | class Solution {
method evalRPN (line 46) | int evalRPN(vector<string>& tokens) {
FILE: Stacks/stack.cpp
class Stack (line 15) | class Stack {
method Stack (line 20) | Stack() {
method push (line 25) | void push(int x) {
method pop (line 34) | int pop() {
method peek (line 45) | int peek() {
method isEmpty (line 54) | bool isEmpty() {
function main (line 59) | int main() {
FILE: Stacks/stack.go
type Stack (line 8) | type Stack
method IsEmpty (line 11) | func (s *Stack) IsEmpty() bool {
method Push (line 16) | func (s *Stack) Push(str string) {
method Pop (line 21) | func (s *Stack) Pop() (string, bool) {
function main (line 31) | func main() {
FILE: Stacks/stack.java
class Stack (line 8) | public class Stack<T> {
method Stack (line 15) | public Stack(int capacity) {
method push (line 23) | public void push(T element) {
method pop (line 36) | public T pop() {
method peek (line 51) | public T peek() {
method isEmpty (line 62) | public boolean isEmpty() {
method size (line 67) | public int size() {
FILE: Stacks/stack.js
class Stack (line 14) | class Stack {
method constructor (line 15) | constructor() {
method push (line 20) | push(element) {
method pop (line 25) | pop() {
method peek (line 32) | peek() {
method isEmpty (line 39) | isEmpty() {
method printStack (line 44) | printStack() {
FILE: Stacks/stack.py
class Stack (line 13) | class Stack:
method __init__ (line 17) | def __init__(self):
method is_empty (line 23) | def is_empty(self):
method push (line 32) | def push(self, item):
method pop (line 41) | def pop(self):
method peek (line 55) | def peek(self):
method size (line 69) | def size(self):
FILE: Stacks/stack_array_based.go
type Stack (line 11) | type Stack struct
method Init (line 18) | func (stack *Stack) Init(capacity uint) *Stack {
method IsFull (line 32) | func (stack *Stack) IsFull() bool {
method IsEmpty (line 39) | func (stack *Stack) IsEmpty() bool {
method Size (line 46) | func (stack *Stack) Size() uint {
method Push (line 53) | func (stack *Stack) Push(data interface{}) error {
method Pop (line 65) | func (stack *Stack) Pop() (interface{}, error) {
method Peek (line 77) | func (stack *Stack) Peek() (interface{}, error) {
method Drain (line 88) | func (stack *Stack) Drain() {
function NewStack (line 26) | func NewStack(capacity uint) *Stack {
function main (line 93) | func main() {
FILE: Stacks/stack_dynamic_array.go
type Stack (line 13) | type Stack struct
method Init (line 20) | func (stack *Stack) Init(capacity uint) *Stack {
method Size (line 34) | func (stack *Stack) Size() uint {
method IsFull (line 40) | func (stack *Stack) IsFull() bool {
method IsEmpty (line 47) | func (stack *Stack) IsEmpty() bool {
method Resize (line 54) | func (stack *Stack) Resize() {
method Push (line 69) | func (stack *Stack) Push(data interface{}) error {
method Pop (line 81) | func (stack *Stack) Pop() (interface{}, error) {
method Peek (line 96) | func (stack *Stack) Peek() (interface{}, error) {
method Drain (line 107) | func (stack *Stack) Drain() {
function NewStack (line 28) | func NewStack(capacity uint) *Stack {
function IsOperator (line 113) | func IsOperator(c uint8) bool {
function IsOperand (line 117) | func IsOperand(c uint8) bool {
function GetOperatorWeight (line 121) | func GetOperatorWeight(op string) int {
function ToPostfix (line 129) | func ToPostfix(s string) string {
function HasHigherPrecedence (line 156) | func HasHigherPrecedence(op1 string, op2 string) bool {
function main (line 162) | func main() {
FILE: Stacks/stack_linked_list.go
type Stack (line 5) | type Stack struct
method Length (line 16) | func (s *Stack) Length() int {
method Push (line 23) | func (s *Stack) Push(data interface{}) {
method IsEmpty (line 31) | func (s *Stack) IsEmpty() bool {
method IsFull (line 37) | func (s *Stack) IsFull() bool {
method Pop (line 43) | func (s *Stack) Pop() (data interface{}) {
method Peek (line 55) | func (s *Stack) Peek() (data interface{}) {
type ListNode (line 10) | type ListNode struct
function main (line 64) | func main() {
FILE: Stacks/stack_using_queue.cpp
class StackUsingQueues (line 5) | class StackUsingQueues {
method StackUsingQueues (line 7) | StackUsingQueues() {}
method push (line 10) | void push(int x) {
method pop (line 16) | int pop() {
method top (line 41) | int top() {
method isEmpty (line 55) | bool isEmpty() {
function main (line 64) | int main() {
FILE: Stacks/stack_using_queue.go
type Stack (line 10) | type Stack struct
method Push (line 24) | func (s *Stack) Push(value int) {
method Pop (line 30) | func (s *Stack) Pop() int {
method Top (line 48) | func (s *Stack) Top() int {
method IsEmpty (line 59) | func (s *Stack) IsEmpty() bool {
function NewStack (line 16) | func NewStack() *Stack {
function main (line 63) | func main() {
FILE: Stacks/stack_using_queue.java
class StackUsingQueues (line 5) | public class StackUsingQueues {
method StackUsingQueues (line 9) | public StackUsingQueues() {
method push (line 14) | public void push(int value) {
method pop (line 19) | public int pop() {
method top (line 40) | public int top() {
method isEmpty (line 53) | public boolean isEmpty() {
method main (line 57) | public static void main(String[] args) {
FILE: Stacks/stack_using_queue.js
class StackUsingQueues (line 2) | class StackUsingQueues {
method constructor (line 3) | constructor() {
method push (line 9) | push(x) {
method pop (line 15) | pop() {
method top (line 35) | top() {
method isEmpty (line 49) | isEmpty() {
FILE: Stacks/stack_using_queue.py
class MyStack (line 41) | class MyStack:
method __init__ (line 43) | def __init__(self):
method push (line 49) | def push(self, x: int) -> None:
method pop (line 56) | def pop(self) -> int:
method top (line 62) | def top(self) -> int:
method empty (line 68) | def empty(self) -> bool:
FILE: Stacks/stacks_API.cpp
class Stack (line 18) | class Stack {
method Stack (line 24) | Stack() : sequenceNumber(0) {}
method push (line 26) | void push(int value) {
method pop (line 30) | int pop() {
method top (line 40) | int top() const {
method empty (line 48) | bool empty() const {
function main (line 53) | int main() {
FILE: Stacks/stacks_using_queues.java
class StackUsingQueues (line 26) | public class StackUsingQueues {
method push (line 35) | public void push(int x) {
method pop (line 41) | public int pop() {
method peek (line 57) | public int peek() {
method isEmpty (line 62) | public boolean isEmpty() {
method main (line 67) | public static void main(String[] args) {
FILE: Stacks/stacks_with_queues.cpp
class MyStack (line 20) | class MyStack {
method MyStack (line 26) | MyStack() {
method push (line 30) | void push(int x) {
method pop (line 44) | int pop() {
method top (line 54) | int top() {
method empty (line 62) | bool empty() {
FILE: Stacks/stacks_with_queues.py
class Stack (line 26) | class Stack:
method __init__ (line 31) | def __init__(self):
method push (line 38) | def push(self, item):
method pop (line 52) | def pop(self):
method top (line 62) | def top(self):
method is_empty (line 72) | def is_empty(self):
method size (line 78) | def size(self):
FILE: Stacks/valid_parentheses.cpp
class Solution (line 29) | class Solution {
method Are_pair (line 31) | bool Are_pair(char opening, char closing){
method isValid (line 37) | bool isValid(string s) {
FILE: Strings/Dp_plaindrome.py
function find_min_insertion_steps (line 1) | def find_min_insertion_steps(s):
FILE: Strings/KMP.go
function computeLPSArray (line 8) | func computeLPSArray(pattern string) []int {
function KMPSearch (line 33) | func KMPSearch(text, pattern string) []int {
function main (line 64) | func main() {
FILE: Strings/Longest_palindromic_substring.py
class Solution (line 17) | class Solution:
method __init__ (line 23) | def __init__(self):
method CheckLeftRight (line 26) | def CheckLeftRight(self, s, index, value):
method longestPalindrome (line 37) | def longestPalindrome(self, s: str) -> str:
FILE: Strings/MaxConcatenatedstr.java
class Solution (line 1) | class Solution {
method solve (line 2) | public:
method maxLength (line 44) | int maxLength(vector<string>& arr) {
FILE: Strings/Min_palindrome.js
function minInsertionStepsToPalindrome (line 1) | function minInsertionStepsToPalindrome(str) {
FILE: Strings/check panagram.java
class Abhay (line 23) | class Abhay {
method isLetter (line 28) | static boolean isLetter(char ch)
method allLetter (line 39) | static boolean allLetter(String str,
method main (line 79) | public static void main(String args[])
FILE: Strings/check_anagrams.java
class CheckAnagrams (line 44) | public class CheckAnagrams {
method main (line 45) | public static void main(String[] args) {
method solve (line 53) | public static int solve(String string1, String string2) {
FILE: Strings/check_palindrome.cpp
function palindrome_checker (line 9) | int palindrome_checker(string str) // palindrome checker function
function main (line 25) | int main()
FILE: Strings/check_permutations.cpp
function check_permutations (line 7) | bool check_permutations(string a, string b){
function main (line 25) | int main(){
FILE: Strings/count_occurances.java
class CountOccurrences (line 47) | public class CountOccurrences {
method main (line 48) | public static void main(String[] args) {
method solve (line 54) | public static int solve(String string) {
FILE: Strings/group_anagrams.cpp
function sortWord (line 33) | std::string sortWord(const std::string& word) {
function GroupAnagrams (line 40) | std::vector<std::vector<std::string>> GroupAnagrams(const std::vector<st...
function main (line 64) | int main() {
FILE: Strings/group_anagrams.go
function GroupAnagrams (line 31) | func GroupAnagrams(words []string) [][]string {
function sortWord (line 54) | func sortWord(word string) string {
FILE: Strings/group_anagrams.java
class GroupAnagrams (line 32) | public class GroupAnagrams {
method groupAnagrams (line 33) | public List<List<String>> groupAnagrams(String[] words) {
method sortWord (line 58) | private String sortWord(String word) {
method main (line 69) | public static void main(String[] args) {
FILE: Strings/group_anagrams.js
function sortWord (line 26) | function sortWord(word) {
function groupAnagrams (line 31) | function groupAnagrams(words) {
FILE: Strings/group_anagrams.py
function sortWord (line 29) | def sortWord(word: str) -> str:
function GroupAnagrams (line 33) | def GroupAnagrams(words: List[str]) -> List[List[str]]:
FILE: Strings/is_pallindrome.cpp
function isPalindrome (line 32) | bool isPalindrome(string str) {
function main (line 46) | int main() {
FILE: Strings/is_pallindrome.go
function IsPalindrome (line 13) | func IsPalindrome(str string) bool {
function main (line 28) | func main() {
FILE: Strings/is_pallindrome.java
method isPalindrome (line 28) | public static boolean isPalindrome(String str) {
FILE: Strings/is_pallindrome.js
function isPalindrome (line 25) | function isPalindrome(str) {
FILE: Strings/is_pallindrome.py
function is_palindrome (line 17) | def is_palindrome(s: str) -> bool:
FILE: Strings/is_unique.cpp
function isUniqueUsingBitVector (line 19) | bool isUniqueUsingBitVector(const std::string& s) {
function main (line 32) | int main() {
FILE: Strings/is_unique.go
function is_unique_normal (line 12) | func is_unique_normal(s string) bool {
function IsUniqueUsingBitVector (line 28) | func IsUniqueUsingBitVector(s string) bool {
function main (line 40) | func main() {
FILE: Strings/is_unique.java
class Main (line 15) | public class Main {
method isUniqueUsingBitVector (line 16) | public static boolean isUniqueUsingBitVector(String s) {
method main (line 29) | public static void main(String[] args) {
FILE: Strings/is_unique.js
function isUniqueUsingBitVector (line 17) | function isUniqueUsingBitVector(s) {
FILE: Strings/is_unique.py
function is_unique_using_bit_vector (line 13) | def is_unique_using_bit_vector(s):
FILE: Strings/length_of_longest_substring.java
class Solution (line 23) | class Solution {
method lengthOfLongestSubstring (line 24) | public int lengthOfLongestSubstring(String s) {
FILE: Strings/longest palindromic substring.java
class Solution (line 35) | class Solution {
method longestPalindrome (line 39) | public String longestPalindrome(String s) {
method expandPalindrome (line 53) | public void expandPalindrome(char[] s, int j, int k) {
method main (line 64) | public static void main(String[] args) {
FILE: Strings/longest_common_prefix.cpp
class Solution (line 30) | class Solution {
method string (line 32) | string longestCommonPrefix(vector<string>& strs) {
FILE: Strings/longest_string.cpp
class Solution (line 12) | class Solution {
method longestPalindrome (line 20) | std::string longestPalindrome(std::string s) {
FILE: Strings/one_edit.cpp
function OneEdit (line 47) | bool OneEdit(string stringOne, string stringTwo) {
function main (line 77) | int main() {
FILE: Strings/one_edit.go
function OneEdit (line 45) | func OneEdit(stringOne string, stringTwo string) bool {
function abs (line 75) | func abs(a int) int {
function min (line 82) | func min(a, b int) int {
FILE: Strings/one_edit.java
class Main (line 43) | public class Main {
method main (line 44) | public static void main(String[] args) {
method isOneEdit (line 55) | public static boolean isOneEdit(String stringOne, String stringTwo) {
FILE: Strings/one_edit.js
function isOneEdit (line 43) | function isOneEdit(stringOne, stringTwo) {
FILE: Strings/one_edit.py
function OneEdit (line 42) | def OneEdit(stringOne, stringTwo):
function abs (line 67) | def abs(a):
function min (line 72) | def min(a, b):
FILE: Strings/plaindrome_str.cpp
function isPalindrome (line 6) | bool isPalindrome(string s, int start, int end) {
function partitionPalindrome (line 17) | vector<vector<string>> partitionPalindrome(string s) {
function backtrack (line 26) | void backtrack(string s, int start, vector<string>& current, vector<vect...
function main (line 41) | int main() {
FILE: Strings/reverse_string.go
function reverse (line 8) | func reverse(s string) string {
function main (line 19) | func main() {
FILE: Strings/reverse_words_in_a_string.cpp
class Solution (line 25) | class Solution {
method string (line 27) | string reverseWords(string s) {
FILE: Strings/reverse_words_in_a_string.go
function reverseWords (line 15) | func reverseWords(sentence string) string {
function strRev (line 53) | func strRev(str []byte, startRev int, endRev int) []byte {
function main (line 96) | func main() {
function ReverseWordsNew (line 114) | func ReverseWordsNew(s string) string {
function trimHelper (line 143) | func trimHelper(s string) string {
function revHelper (line 150) | func revHelper(s []byte, start int, end int) []byte {
FILE: Strings/reverse_words_in_a_string.js
function reverseString (line 8) | function reverseString(inputString) {
FILE: Strings/reverse_words_in_string.java
class ReverseWordsInString (line 25) | public class ReverseWordsInString {
method main (line 26) | public static void main(String[] args) {
method solve (line 32) | public static String solve(String string) {
method trimSpaces (line 52) | public static StringBuilder trimSpaces(String string) {
method reverse (line 74) | public static void reverse(StringBuilder stringBuilder, int leftIdx, i...
method reverseEachWord (line 81) | public static void reverseEachWord(StringBuilder stringBuilder) {
FILE: Strings/valid_pallindrome2.cpp
class Solution (line 13) | class Solution {
method validate (line 15) | bool validate(string s, int start, int end){
method validPalindrome (line 29) | bool validPalindrome(string s) {
FILE: Strings/valid_pallindrome2.go
function isPalindromeWithRemoval (line 19) | func isPalindromeWithRemoval(s string) bool {
function isPalindrome (line 47) | func isPalindrome(s string) bool {
FILE: Strings/valid_pallindrome2.java
method isPalindromeWithRemoval (line 15) | public static boolean isPalindromeWithRemoval(String s) {
method isPalindrome (line 42) | public static boolean isPalindrome(String s) {
FILE: Strings/valid_pallindrome2.js
function validPalindrome (line 24) | function validPalindrome(s) {
function isPalindrome (line 59) | function isPalindrome(s) {
FILE: Strings/valid_pallindrome2.py
function valid_palindrome (line 25) | def valid_palindrome(s: str) -> bool:
FILE: Strings/well_formed_parentheses.cpp
class Solution (line 15) | class Solution {
method solve (line 19) | void solve(string s,int count)
method generateParenthesis (line 29) | vector<string> generateParenthesis(int n) {
FILE: Strings/well_formed_parentheses.java
class Solution (line 25) | class Solution {
method generateParenthesis (line 28) | public List<String> generateParenthesis(int n) {
method isValid (line 94) | public boolean isValid(String s) {
FILE: Strings/zigzag_conversion.cpp
class Solution (line 35) | class Solution {
method string (line 37) | string convert(string s, int numRows) {
FILE: Trees/AVL/avl.go
type AVLTreeNode (line 8) | type AVLTreeNode struct
function Height (line 17) | func Height(node *AVLTreeNode) int {
function SingleLeftRotate (line 27) | func SingleLeftRotate(X *AVLTreeNode) *AVLTreeNode {
function SingleRightRotate (line 43) | func SingleRightRotate(X *AVLTreeNode) *AVLTreeNode {
function DoubleRotateRightLeft (line 57) | func DoubleRotateRightLeft(Z *AVLTreeNode) *AVLTreeNode {
function DoubleRotateLeftRight (line 63) | func DoubleRotateLeftRight(Z *AVLTreeNode) *AVLTreeNode {
function main (line 68) | func main() {
FILE: Trees/Binary Search Trees/Kth_Largest_Value_In_BST.py
class Node (line 16) | class Node:
method __init__ (line 18) | def __init__(self, val):
function kthLargestUtil (line 24) | def kthLargestUtil(root, k, c):
function kthLargest (line 46) | def kthLargest(root, k):
function insert (line 56) | def insert(node, key):
FILE: Trees/Binary Search Trees/Kth_largest_BST.cpp
class Node (line 66) | class Node{
method Node (line 76) | Node(int item){
class BinaryTree (line 93) | class BinaryTree{
method traverseRL (line 102) | void traverseRL(Node* node, int k){
method BinaryTree (line 123) | BinaryTree(int root_data){
method Node (line 128) | Node* insertNode(Node* node, int data){ //insert a new node on the rig...
method Node (line 141) | Node* getKthLargest(int k){ //get the kth largest data node
function main (line 155) | int main() {
FILE: Trees/Binary Search Trees/Kth_largest_BST.java
class Node (line 4) | class Node {
method Node (line 8) | Node(int data) {
class BST (line 17) | class BST {
method BST (line 20) | BST() {
method kthLargest (line 34) | public int kthLargest(int k) {
method kthLargestHelper (line 42) | private void kthLargestHelper(Node node, List<Integer> result, int k) {
method insert (line 58) | public void insert(int data) {
method insertHelper (line 68) | private Node insertHelper(Node node, int data) {
class KthLargestBST (line 85) | public class KthLargestBST {
method main (line 86) | public static void main(String[] args) {
FILE: Trees/Binary Search Trees/Kth_largest_BST.js
class Node (line 4) | class Node {
method constructor (line 5) | constructor(value) {
class BST (line 15) | class BST {
method constructor (line 16) | constructor() {
method insert (line 24) | insert(value) {
method insertNode (line 51) | insertNode(node, newNode) {
method findKthLargest (line 72) | findKthLargest(k) {
method inOrderTraversal (line 92) | inOrderTraversal(node, values) {
FILE: Trees/Binary Search Trees/Validate_BST.cpp
type Node (line 33) | struct Node {
type Node (line 36) | struct Node
method Node (line 38) | Node(int data)
function validate (line 46) | bool validate(Node* root,long long int min , long long int max){
function isValidBST (line 64) | bool isValidBST(Node* root) {
function main (line 72) | int main()
FILE: Trees/Binary Search Trees/Validate_BST.java
class validateBST (line 6) | class validateBST {
class Node (line 7) | public static class Node {
method Node (line 11) | public Node(int data) {
method isBST (line 20) | static Boolean isBST(Node root) {
method main (line 38) | public static void main(String[] args) {
FILE: Trees/Binary Search Trees/Validate_BST.js
class Node (line 37) | class Node {
method constructor (line 38) | constructor(data) {
function isBST (line 46) | function isBST(root) {
FILE: Trees/Binary Search Trees/Validate_BST.py
class Node (line 37) | class Node:
method __init__ (line 38) | def __init__(self, data):
function is_bst (line 45) | def is_bst(root):
FILE: Trees/Binary Search Trees/bst.go
type BSTNode (line 26) | type BSTNode struct
function ConstructBST (line 33) | func ConstructBST(n, k int) *BSTNode {
function Insert (line 42) | func Insert(root *BSTNode, data int) *BSTNode {
function SearchElementRecursive (line 59) | func SearchElementRecursive(root *BSTNode, data int) *BSTNode {
function SearchElementNonRecursive (line 76) | func SearchElementNonRecursive(root *BSTNode, data int) *BSTNode {
function FindMinRecursive (line 96) | func FindMinRecursive(root *BSTNode) *BSTNode {
function FindMinNonRecursive (line 110) | func FindMinNonRecursive(root *BSTNode) *BSTNode {
function FindMaxRecursive (line 124) | func FindMaxRecursive(root *BSTNode) *BSTNode {
function FindMaxNonRecursive (line 138) | func FindMaxNonRecursive(root *BSTNode) *BSTNode {
function DeleteMin (line 147) | func DeleteMin(root *BSTNode) *BSTNode{
function DeleteFromBST (line 157) | func DeleteFromBST(root *BSTNode, data int) *BSTNode {
function PreOrder (line 207) | func PreOrder(root *BSTNode) {
function InOrder (line 216) | func InOrder(root *BSTNode) {
function IsBST (line 226) | func IsBST(root *BSTNode) bool {
function IsBSTOptimal (line 247) | func IsBSTOptimal(root *BSTNode, min, max int) bool {
function IsBSTInorder (line 263) | func IsBSTInorder(root *BSTNode, prev *int) bool {
function Helper (line 283) | func Helper(Arr []int, low int, high int) *BSTNode {
function ConvertSortedArrayToBST (line 301) | func ConvertSortedArrayToBST(Arr []int) *BSTNode {
function kthSmallest (line 309) | func kthSmallest(root *BSTNode, k int) *BSTNode {
function helperKthSmallest (line 317) | func helperKthSmallest(root *BSTNode, k int, counter *int) *BSTNode {
function FloorInBST (line 337) | func FloorInBST(root *BSTNode, key int) *BSTNode {
function CeilInBST (line 359) | func CeilInBST(root *BSTNode, key int) *BSTNode {
function RangePrintBST (line 379) | func RangePrintBST(root *BSTNode, start int, end int) {
function RangePrintQueueBST (line 401) | func RangePrintQueueBST(root *BSTNode, start, end int) {
function CountTrees (line 435) | func CountTrees(n int) int {
function main (line 451) | func main() {
FILE: Trees/Binary Search Trees/find_closest_value.cpp
class BST (line 32) | class BST {
method BST (line 38) | BST(int val) {
method findClosestValue (line 44) | int findClosestValue(int target) {
method findClosestValueHelper (line 50) | int findClosestValueHelper(int target, int closest) {
function main (line 70) | int main() {
FILE: Trees/Binary Search Trees/find_closest_value.go
type BST (line 32) | type BST struct
method FindClosestValue (line 39) | func (tree *BST) FindClosestValue(target int) int {
method findClosestValue (line 44) | func (tree *BST) findClosestValue(target, closest int) int {
function absDiff (line 58) | func absDiff(a, b int) int {
FILE: Trees/Binary Search Trees/find_closest_value.js
class BST (line 30) | class BST {
method constructor (line 31) | constructor(value) {
method findClosestValue (line 37) | findClosestValue(target) {
method _findClosestValueHelper (line 42) | _findClosestValueHelper(target, closest) {
FILE: Trees/Binary Search Trees/find_closest_value.py
class BST (line 30) | class BST:
method __init__ (line 31) | def __init__(self, value):
method find_closest_value (line 36) | def find_closest_value(self, target):
method _find_closest_value_helper (line 40) | def _find_closest_value_helper(self, target, closest):
FILE: Trees/Binary Search Trees/insert_into_bst.cpp
class Node (line 18) | class Node{
method Node (line 24) | Node(int x){
function bfs (line 30) | void bfs(Node* root){
function Node (line 56) | Node* insert_into_binary_search_tree(Node* root, int data){
method Node (line 24) | Node(int x){
function Node (line 68) | Node* build_binary_search_tree(){
method Node (line 24) | Node(int x){
function inorder (line 78) | void inorder(Node*root){
function pre_order (line 85) | void pre_order(Node*root){
function post_order (line 92) | void post_order(Node*root){
function main (line 99) | int main(){
FILE: Trees/Binary Search Trees/kth_largest.go
type BST (line 6) | type BST struct
function FindKthLargestValueInBst (line 13) | func FindKthLargestValueInBst(tree *BST, k int) int {
function inOrderTraverse (line 19) | func inOrderTraverse(tree *BST, sortedValues *[]int) {
type treeInfo (line 76) | type treeInfo struct
function FindKthLargestValueInBst2 (line 82) | func FindKthLargestValueInBst2(tree *BST, k int) int {
function reverseInOrderTraverse (line 90) | func reverseInOrderTraverse(tree *BST, k int, treeInfo *treeInfo) {
FILE: Trees/Binary Search Trees/min_height_BST.cpp
type TreeNode (line 87) | struct TreeNode {
method TreeNode (line 92) | TreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
function TreeNode (line 95) | TreeNode* minHeightBST(std::vector<int>& array) {
method TreeNode (line 92) | TreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
function TreeNode (line 100) | TreeNode* constructMinHeightBST(std::vector<int>& array, TreeNode* bst, ...
method TreeNode (line 92) | TreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
class BST (line 120) | class BST {
method BST (line 126) | BST(int x) : value(x), left(nullptr), right(nullptr) {}
method insert (line 128) | void insert(int value) {
function main (line 145) | int main() {
function deleteTree (line 157) | void deleteTree(TreeNode* root) {
FILE: Trees/Binary Search Trees/min_height_BST.go
function MinHeightBST (line 86) | func MinHeightBST(array []int) *BST {
function constructMinHeightBST (line 91) | func constructMinHeightBST(array []int, bst *BST, start int, end int) *B...
type BST (line 109) | type BST struct
method Insert (line 116) | func (tree *BST) Insert(value int) *BST {
FILE: Trees/Binary Search Trees/min_height_BST.java
class JuiceBottling (line 84) | public class JuiceBottling {
method juiceBottling (line 86) | public static int[] juiceBottling(int[] prices) {
method main (line 118) | public static void main(String[] args) {
FILE: Trees/Binary Search Trees/min_height_BST.js
class TreeNode (line 84) | class TreeNode {
method constructor (line 85) | constructor(value) {
function minHeightBST (line 93) | function minHeightBST(array) {
function constructMinHeightBST (line 99) | function constructMinHeightBST(array, bst, start, end) {
class BST (line 120) | class BST {
method constructor (line 121) | constructor(value) {
method insert (line 127) | insert(value) {
FILE: Trees/Binary Search Trees/min_height_BST.py
class TreeNode (line 82) | class TreeNode:
method __init__ (line 83) | def __init__(self, value):
function min_height_bst (line 88) | def min_height_bst(array):
function construct_min_height_bst (line 92) | def construct_min_height_bst(array, bst, start, end):
class BST (line 109) | class BST:
method __init__ (line 110) | def __init__(self, value):
method insert (line 115) | def insert(self, value):
FILE: Trees/Binary Search Trees/reconstruct_bst.cpp
type TreeNode (line 51) | struct TreeNode {
method TreeNode (line 55) | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
class TreeInfo (line 59) | class TreeInfo {
method TreeInfo (line 62) | TreeInfo(int idx) : rootIdx(idx) {}
function TreeNode (line 66) | TreeNode* reconstructBst(std::vector<int>& preOrderTraversalValues) {
method TreeNode (line 55) | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
function TreeNode (line 75) | TreeNode* reconstructBstFromRange(int lowerBound, int upperBound, std::v...
method TreeNode (line 55) | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
function deleteBst (line 107) | void deleteBst(TreeNode* root) {
function main (line 116) | int main() {
FILE: Trees/Binary Search Trees/reconstruct_bst.go
type BST (line 83) | type BST struct
function ReconstructBst (line 91) | func ReconstructBst(preOrderTraversalValues []int) *BST {
type treeInfo (line 122) | type treeInfo struct
function ReconstructBst2 (line 127) | func ReconstructBst2(preOrderTraversalValues []int) *BST {
function reconstructBSTFromRange (line 136) | func reconstructBSTFromRange(lowerBound, upperBound int, preOrderTravers...
FILE: Trees/Binary Search Trees/reconstruct_bst.java
class TreeNode (line 46) | class TreeNode {
method TreeNode (line 51) | TreeNode(int x) {
class TreeInfo (line 58) | class TreeInfo {
method TreeInfo (line 61) | TreeInfo(int idx) {
class ReconstructBST (line 66) | public class ReconstructBST {
method reconstructBst (line 68) | public static TreeNode reconstructBst(int[] preOrderTraversalValues) {
method reconstructBstFromRange (line 76) | private static TreeNode reconstructBstFromRange(int lowerBound, int up...
method main (line 107) | public static void main(String[] args) {
FILE: Trees/Binary Search Trees/reconstruct_bst.js
class TreeNode (line 26) | class TreeNode {
method constructor (line 31) | constructor(value) {
function constructBST (line 43) | function constructBST(preorder) {
function printInOrder (line 78) | function printInOrder(node) {
FILE: Trees/Binary Search Trees/reconstruct_bst.py
class TreeNode (line 46) | class TreeNode:
method __init__ (line 47) | def __init__(self, val):
class TreeInfo (line 52) | class TreeInfo:
method __init__ (line 53) | def __init__(self, root_idx):
function reconstruct_bst (line 56) | def reconstruct_bst(pre_order_traversal_values):
function reconstruct_bst_from_range (line 63) | def reconstruct_bst_from_range(lower_bound, upper_bound, pre_order_trave...
FILE: Trees/Binary Search Trees/search.cpp
class Node (line 19) | class Node{
method Node (line 25) | Node(int x){
function bfs (line 31) | void bfs(Node* root){
function Node (line 57) | Node* insert_into_binary_search_tree(Node* root, int data){
method Node (line 25) | Node(int x){
function Node (line 69) | Node* build_binary_search_tree(){
method Node (line 25) | Node(int x){
function search_in_BST (line 79) | bool search_in_BST(Node* root, int value_to_be_searched){
function main (line 91) | int main(){
FILE: Trees/Binary Search Trees/validate_bst.go
type BST (line 41) | type BST struct
method ValidateBst (line 49) | func (tree *BST) ValidateBst() bool {
method validateBST (line 56) | func (tree *BST) validateBST(min, max int) bool {
FILE: Trees/Binary Trees/Trie.js
class Trie (line 38) | class Trie {
method constructor (line 39) | constructor() {
method insert (line 43) | insert(word) {
method search (line 47) | search(word) {
method startsWith (line 51) | startsWith(prefix) {
class Node (line 56) | class Node {
method constructor (line 57) | constructor() {
method insert (line 63) | insert(word, id
Condensed preview — 894 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (2,600K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"chars": 595,
"preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your fea"
},
{
"path": ".gitignore",
"chars": 19,
"preview": ".vscode\n.idea\n*.exe"
},
{
"path": "2D Arrays (Matrix)/2D_sorted.go",
"chars": 606,
"preview": "func searchMatrix(matrix [][]int, target int) bool {\n if len(matrix) == 0 || len(matrix[0]) == 0 {\n return fal"
},
{
"path": "2D Arrays (Matrix)/2D_sorted_array.java",
"chars": 2898,
"preview": "/*\n\nThe algorithm starts by initializing two pointers, left and right, which represent the start and end indices of the "
},
{
"path": "2D Arrays (Matrix)/binary_search.cpp",
"chars": 1282,
"preview": "/*\n You are given an m x n integer matrix matrix with the following two properties:\n\n Each row is sorted in non-de"
},
{
"path": "2D Arrays (Matrix)/count_negatives_in_sorted_matrix.cpp",
"chars": 950,
"preview": "/*\n Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the numbe"
},
{
"path": "2D Arrays (Matrix)/matrix_diagonal_sum.cpp",
"chars": 1153,
"preview": "/*\n Given a square matrix mat, return the sum of the matrix diagonals.\n\n Only include the sum of all the elements "
},
{
"path": "2D Arrays (Matrix)/matrix_wave_print.cpp",
"chars": 758,
"preview": "// Prints a matrix in wave form \n#include<bits/stdc++.h>\nusing namespace std;\nvoid wave_print(int Mat[][10], int R, int "
},
{
"path": "2D Arrays (Matrix)/rotate_matrix.cpp",
"chars": 2293,
"preview": "// Rotate clockwise and anti-clockwise\n/*\nThis implementation first defines two functions, rotateClockwise and rotateCou"
},
{
"path": "2D Arrays (Matrix)/rotate_matrix.go",
"chars": 1869,
"preview": "// Rotate clockwise and anti-clockwise\n/*\n\tThe rotateClockwise function takes an image array as input and returns the im"
},
{
"path": "2D Arrays (Matrix)/rotate_matrix.java",
"chars": 2289,
"preview": "// Rotate clockwise and anti-clockwise\n/*\n This program takes a 2D array (matrix) and performs two types of 90-degree"
},
{
"path": "2D Arrays (Matrix)/rotate_matrix.js",
"chars": 2131,
"preview": "// Rotate clockwise and anti-clockwise\n/*\n Here, we first get the number of rows and columns in the matrix. Then, for"
},
{
"path": "2D Arrays (Matrix)/rotate_matrix.py",
"chars": 1673,
"preview": "# Rotate clockwise and anti-clockwise\n'''\n The rotate_clockwise() function takes a matrix as input and returns the ma"
},
{
"path": "2D Arrays (Matrix)/search_element.cpp",
"chars": 994,
"preview": "/*\n You are given an m x n integer matrix matrix with the following two properties:\n\n Each row is sorted in non-de"
},
{
"path": "2D Arrays (Matrix)/searching_in_sorted_array.cpp",
"chars": 2833,
"preview": "/* Name : Rajeev Kumar\nGithub username : Tonystart121\nRepository name : data-structures-and-algorithms\nProblem : Searchi"
},
{
"path": "2D Arrays (Matrix)/searching_in_sorted_array.java",
"chars": 1997,
"preview": "\n/* Issue 271\nAuthor:maneesha\nDate:10/06/2023\n##Assignee:Mani1881\n\n//About:Search in 2D sorted array in Java\n//Input:\nYo"
},
{
"path": "2D Arrays (Matrix)/searching_in_sorted_array.js",
"chars": 2716,
"preview": "/*Name : Abhinav kumar\nGithub username : Abhinavcode13\nRepository name : data-structures-and-algorithms\nProblem : Search"
},
{
"path": "2D Arrays (Matrix)/searching_in_sorted_array.py",
"chars": 2698,
"preview": "'''\nDate:28/6/23\nAbout:Search in 2D sorted array in Python\n\nInput:\nYou are given an m x n integer matrix matrix with the"
},
{
"path": "2D Arrays (Matrix)/set_matrix_0.cpp",
"chars": 2782,
"preview": "/*\nProblem:\nYou are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you n"
},
{
"path": "2D Arrays (Matrix)/set_matrix_0.go",
"chars": 2452,
"preview": "/*\nProblem:\nYou are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you n"
},
{
"path": "2D Arrays (Matrix)/set_matrix_0.java",
"chars": 5754,
"preview": "/* SET MATRIX ZERO - JAVA LANGUAGE\n Problem Link1 : https://leetcode.com/problems/set-matrix-zeroes/\n Problem Link2 "
},
{
"path": "2D Arrays (Matrix)/spiral_traverse.cpp",
"chars": 3989,
"preview": "/*\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and\n\treturns a"
},
{
"path": "2D Arrays (Matrix)/spiral_traverse.go",
"chars": 3678,
"preview": "/*\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and\n\treturns a"
},
{
"path": "2D Arrays (Matrix)/spiral_traverse.java",
"chars": 5788,
"preview": "/*\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and\n\treturns a"
},
{
"path": "2D Arrays (Matrix)/spiral_traverse.py",
"chars": 4850,
"preview": "##### LEETCODE 54. Spiral Matrix ####\n\n##### INPUT OUTPUT #####\n\n# Given an m x n matrix, return all elements of the mat"
},
{
"path": "2D Arrays (Matrix)/zigzag_traversal.cpp",
"chars": 5237,
"preview": "/*\n\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)\n\tand returns "
},
{
"path": "2D Arrays (Matrix)/zigzag_traversal.go",
"chars": 4741,
"preview": "/*\n\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)\n\tand returns "
},
{
"path": "2D Arrays (Matrix)/zigzag_traversal.java",
"chars": 5845,
"preview": "/*\n\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)\n\tand returns "
},
{
"path": "2D Arrays (Matrix)/zigzag_traversal.js",
"chars": 4850,
"preview": "/*\n\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)\n\tand returns "
},
{
"path": "2D Arrays (Matrix)/zigzag_traversal.py",
"chars": 4977,
"preview": "'''\n\n\tWrite a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m)\n\tand returns"
},
{
"path": "Arrays/Jobassign.cpp",
"chars": 2712,
"preview": "#include <stdio.h>\n#include <limits.h>\n\n#define N 4 // Number of workers and tasks\n\nvoid hungarianAlgorithm(int costMatr"
},
{
"path": "Arrays/Maximum_freq.py",
"chars": 1087,
"preview": "class Solution {\n public int majorityElement(int[] nums) {\n int candidate = nums[0]; // Initialize the candida"
},
{
"path": "Arrays/Rotatedarr.cpp",
"chars": 752,
"preview": "class Solution {\npublic:\n int search(std::vector<int>& nums, int target) {\n int low = 0, high = nums.size() - "
},
{
"path": "Arrays/array_of_products.cpp",
"chars": 3812,
"preview": "/*\n\tGiven an array of integers A, find and return the product array of the same size where the ith\n\telement of the produ"
},
{
"path": "Arrays/array_of_products.go",
"chars": 3467,
"preview": "/*\n\tGiven an array of integers A, find and return the product array of the same size where the ith\n\telement of the produ"
},
{
"path": "Arrays/array_of_products.java",
"chars": 3726,
"preview": "/*\n\tGiven an array of integers A, find and return the product array of the same size where the ith\n\telement of the produ"
},
{
"path": "Arrays/array_of_products.js",
"chars": 3444,
"preview": "/*\n\tGiven an array of integers A, find and return the product array of the same size where the ith\n\telement of the produ"
},
{
"path": "Arrays/array_of_products.py",
"chars": 3403,
"preview": "'''\n\tGiven an array of integers A, find and return the product array of the same size where the ith\n\telement of the prod"
},
{
"path": "Arrays/ceaser_cipher.cpp",
"chars": 3721,
"preview": "/*\n Given a non-empty string of lowercase letters and a non-negative integer\n representing a key, write a function"
},
{
"path": "Arrays/ceaser_cipher.go",
"chars": 3501,
"preview": "/*\n\tGiven a non-empty string of lowercase letters and a non-negative integer\n\trepresenting a key, write a function that "
},
{
"path": "Arrays/ceaser_cipher.java",
"chars": 3832,
"preview": "/*\n Given a non-empty string of lowercase letters and a non-negative integer\n representing a key, write a function"
},
{
"path": "Arrays/ceaser_cipher.js",
"chars": 3303,
"preview": "/*\n Given a non-empty string of lowercase letters and a non-negative integer\n representing a key, write a function"
},
{
"path": "Arrays/ceaser_cipher.py",
"chars": 3166,
"preview": "'''\n Given a non-empty string of lowercase letters and a non-negative integer\n representing a key, write a functio"
},
{
"path": "Arrays/dutch_national_flag.cpp",
"chars": 3201,
"preview": "/*\n Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same co"
},
{
"path": "Arrays/dutch_national_flag.go",
"chars": 2741,
"preview": "/*\n Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same col"
},
{
"path": "Arrays/dutch_national_flag.java",
"chars": 3222,
"preview": "/*\n Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same co"
},
{
"path": "Arrays/dutch_national_flag.js",
"chars": 2822,
"preview": "/*\n Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same co"
},
{
"path": "Arrays/dutch_national_flag.py",
"chars": 2827,
"preview": "'''\n Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same c"
},
{
"path": "Arrays/find_three_largest_integers.js",
"chars": 3673,
"preview": "/*\n Write a function that takes in an array of at least three integers and,\n without sorting the input array, retu"
},
{
"path": "Arrays/find_three_largest_number.cpp",
"chars": 4636,
"preview": "/*\n Write a function that takes in an array of at least three integers and,\n without sorting the input array, returns "
},
{
"path": "Arrays/find_three_largest_numbers.go",
"chars": 3661,
"preview": "/*\n Write a function that takes in an array of at least three integers and,\n without sorting the input array, retu"
},
{
"path": "Arrays/find_three_largest_numbers.java",
"chars": 4472,
"preview": "/*\n Write a function that takes in an array of at least three integers and,\n without sorting the input array, retu"
},
{
"path": "Arrays/find_three_largest_numbers.py",
"chars": 3666,
"preview": "'''\n Write a function that takes in an array of at least three integers and,\n without sorting the input array, ret"
},
{
"path": "Arrays/first_duplicate_value.cpp",
"chars": 1172,
"preview": "/*\n\tGiven an array of integers between 1 and n, inclusive, where n is the length of the array, write a function\n\tthat re"
},
{
"path": "Arrays/first_duplicate_value.go",
"chars": 4607,
"preview": "/*\n\tGiven an array of integers between 1 and n, inclusive where n is the length of the array, write a function\n\tthat re"
},
{
"path": "Arrays/first_duplicate_value.java",
"chars": 2348,
"preview": "/* Sure, here's a brief explanation of each solution:\n\nSolution 1 (O(n) time, O(1) space):\nThis solution uses Floyd's To"
},
{
"path": "Arrays/first_duplicate_value.js",
"chars": 1768,
"preview": "/*\n\tGiven an array of integers between 1 and n, inclusive, where n is the length of the array, write a function\n\tthat re"
},
{
"path": "Arrays/first_duplicate_value.py",
"chars": 855,
"preview": "'''\nIn the code I implemented a solution using Floyd's Tortoise and Hare algorithm \nfor finding the first integer that a"
},
{
"path": "Arrays/four_sum.py",
"chars": 2962,
"preview": "'''\nauthor:maneesha\nInput:\nGiven an array nums of n integers, return an array of all the unique quadruplets [nums[a], nu"
},
{
"path": "Arrays/insert_interval.cpp",
"chars": 4145,
"preview": "/*\n\tInsert Interval\n\n\tIn this implementation, the `Interval` struct represents an interval with a start and end value.\n\t"
},
{
"path": "Arrays/insert_interval.go",
"chars": 3354,
"preview": "/*\n\tInsert Interval\n\n\tIn this implementation, the `Interval` struct represents an interval with a start and end value.\n\t"
},
{
"path": "Arrays/insert_interval.java",
"chars": 4482,
"preview": "/*\n\tInsert Interval\n\n\tIn this implementation, the `Interval` struct represents an interval with a start and end value.\n\t"
},
{
"path": "Arrays/insert_interval.js",
"chars": 3177,
"preview": "/*\n\tInsert Interval\n\n\tIn this implementation, the `Interval` struct represents an interval with a start and end value.\n\t"
},
{
"path": "Arrays/insert_interval.py",
"chars": 3207,
"preview": "'''\n Insert Interval\n\t\n In this implementation, the `Interval` struct represents an interval with a start and end "
},
{
"path": "Arrays/insert_intervals.cpp",
"chars": 1988,
"preview": "/* You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start"
},
{
"path": "Arrays/insert_intervals.go",
"chars": 4924,
"preview": "// 57. Insert Interval\n// You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, en"
},
{
"path": "Arrays/is_monotonic.cpp",
"chars": 2258,
"preview": "/*\n\tAn array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing.\n\tMath"
},
{
"path": "Arrays/is_monotonic.go",
"chars": 2069,
"preview": "/*\n\tAn array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing.\n\tMath"
},
{
"path": "Arrays/is_monotonic.java",
"chars": 2327,
"preview": "/*\n\tAn array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing.\n\tMath"
},
{
"path": "Arrays/is_monotonic.js",
"chars": 2035,
"preview": "/*\n\tAn array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing.\n\tMath"
},
{
"path": "Arrays/is_monotonic.py",
"chars": 2036,
"preview": "'''\n\tAn array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing.\n\tMat"
},
{
"path": "Arrays/longest_peak.cpp",
"chars": 3596,
"preview": "/*\n \tWrite a function that takes in an array of integers and returns the length of the longest peak in the array.\n\tA pe"
},
{
"path": "Arrays/longest_peak.go",
"chars": 3587,
"preview": "/*\n \tWrite a function that takes in an array of integers and returns the length of the longest peak in the array.\n\tA pe"
},
{
"path": "Arrays/longest_peak.java",
"chars": 2395,
"preview": "/*\n \tWrite a function that takes in an array of integers and returns the length of the longest peak in the array.\n\tA pe"
},
{
"path": "Arrays/longest_peak.js",
"chars": 3597,
"preview": "/*\n \tWrite a function that takes in an array of integers and returns the length of the longest peak in the array.\n\tA pe"
},
{
"path": "Arrays/longest_peak.py",
"chars": 4541,
"preview": "'''\n Write a function that takes in an array of integers and returns the length of the longest peak in the array.\n\tA "
},
{
"path": "Arrays/majority_element.go",
"chars": 3195,
"preview": "/*\nGiven an array nums of size n, return the majority element.\n\nThe majority element is the element that appears more th"
},
{
"path": "Arrays/majority_element.java",
"chars": 806,
"preview": "/*\n Majority Element\n Given an array nums of size n, return the majority element.\n The majority element is the "
},
{
"path": "Arrays/maximum_subarray_sum.cpp",
"chars": 3330,
"preview": "// Maximum Subarray\n/*\n\tThe maxSubarraySum function takes an integer slice arr as input and returns the maximum subarray"
},
{
"path": "Arrays/maximum_subarray_sum.go",
"chars": 3419,
"preview": "// Maximum Subarray\n/*\n\tThe maxSubarraySum function takes an integer slice arr as input and returns the maximum subarray"
},
{
"path": "Arrays/maximum_subarray_sum.py",
"chars": 2211,
"preview": "'''\n The max_subarray_sum function takes an array arr as input and returns the maximum sum of a \n contiguous subar"
},
{
"path": "Arrays/merge_intervals.cpp",
"chars": 1774,
"preview": "/* Array: Merge intervals in C++ #1113\nGiven an array of intervals where intervals[i] = [starti, endi], merge all overla"
},
{
"path": "Arrays/merge_intervals.go",
"chars": 3719,
"preview": "/*\n Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,\n and return an"
},
{
"path": "Arrays/merge_intervals.java",
"chars": 2161,
"preview": "/* Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array"
},
{
"path": "Arrays/merge_intervals.js",
"chars": 2183,
"preview": "/*\n\tProblem definition:\n\t\tGiven an array of intervals where intervals[i] = [starti, endi], merge all overlapping interva"
},
{
"path": "Arrays/merge_intervals.py",
"chars": 2451,
"preview": "#Program Author : TheCodeVenturer [Niraj Modi]\n'''\n Problem definition:\n\t\tGiven an array of intervals where intervals"
},
{
"path": "Arrays/merge_sorted_array.cpp",
"chars": 2473,
"preview": "/*\nProblem Statement :- You are given two integer arrays nums1 and nums2, sorted in non-decreasing order,\nand two intege"
},
{
"path": "Arrays/merge_sorted_array.java",
"chars": 1536,
"preview": "//You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers\n// m and n, represe"
},
{
"path": "Arrays/merge_sorted_arrays.py",
"chars": 1064,
"preview": "class Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n \"\"\"\n Do "
},
{
"path": "Arrays/minimum_size_subarray_sum.java",
"chars": 2453,
"preview": "/**\n * Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray w"
},
{
"path": "Arrays/move_element_to_end.cpp",
"chars": 2095,
"preview": "/*\n\tMove Element to end\n\tSample Input : [1, 0, 3, 0, 0, 5] To move: 0\n\tOutput : [1, 3, 5, 0, 0, 0]\n\n\tThis is a function "
},
{
"path": "Arrays/move_element_to_end.go",
"chars": 2045,
"preview": "/*\n\tMove Element to end\n\tSample Input : [1, 0, 3, 0, 0, 5] To move: 0\n\tOutput : [1, 3, 5, 0, 0, 0]\n\n\tThis is a function "
},
{
"path": "Arrays/move_element_to_end.java",
"chars": 2212,
"preview": "/*\n\tMove Element to end\n\tSample Input : [1, 0, 3, 0, 0, 5] To move: 0\n\tOutput : [1, 3, 5, 0, 0, 0]\n\n\tThis is a function "
},
{
"path": "Arrays/move_element_to_end.js",
"chars": 2025,
"preview": "/*\n\tMove Element to end\n\tSample Input : [1, 0, 3, 0, 0, 5] To move: 0\n\tOutput : [1, 3, 5, 0, 0, 0]\n\n\tThis is a function "
},
{
"path": "Arrays/move_element_to_end.py",
"chars": 1969,
"preview": "'''\n\tMove 0's to end\n\tSample Input : [1, 0, 3, 0, 0, 5]\n\tOutput : [1, 3, 5, 0, 0, 0]\n\n\tThis is a function called MoveEle"
},
{
"path": "Arrays/non-overlapping intervals.cpp",
"chars": 1418,
"preview": "// Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you"
},
{
"path": "Arrays/pallindromic_permutations.cpp",
"chars": 2053,
"preview": "// Write a function to check if it is a permutation of a pallindrome\n// Program Author : Abhisek Kumar Gupta\n#include<bi"
},
{
"path": "Arrays/sign_of_the_product_of_an_array.cpp",
"chars": 3362,
"preview": "// Leetcode 1822 : Sign of the Product of an Array\n/*\nQUESTION\nThere is a function signFunc(x) that returns:\n\n1 if x is "
},
{
"path": "Arrays/smallest_difference.cpp",
"chars": 3913,
"preview": "/*\n\tWrite a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array)\n\twh"
},
{
"path": "Arrays/smallest_difference.go",
"chars": 3394,
"preview": "/*\n\tWrite a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array)\n\twh"
},
{
"path": "Arrays/smallest_difference.java",
"chars": 3899,
"preview": "/*\n\tWrite a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array)\n\twh"
},
{
"path": "Arrays/smallest_difference.js",
"chars": 3430,
"preview": "/*\n Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array)\n"
},
{
"path": "Arrays/smallest_difference.py",
"chars": 3300,
"preview": "'''\n Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array)"
},
{
"path": "Arrays/sorted_square_array,js",
"chars": 3767,
"preview": "/*\n\tWrite a function that takes in a non-empty array of integers that are sorted\n\tin ascending order and returns a new a"
},
{
"path": "Arrays/sorted_square_array.cpp",
"chars": 4037,
"preview": "/*\n\tWrite a function that takes in a non-empty array of integers that are sorted\n\tin ascending order and returns a new a"
},
{
"path": "Arrays/sorted_square_array.go",
"chars": 3660,
"preview": "/*\n\tWrite a function that takes in a non-empty array of integers that are sorted\n\tin ascending order and returns a new a"
},
{
"path": "Arrays/sorted_square_array.java",
"chars": 4156,
"preview": "/*\n\tWrite a function that takes in a non-empty array of integers that are sorted\n\tin ascending order and returns a new a"
},
{
"path": "Arrays/sorted_square_array.py",
"chars": 3826,
"preview": "'''\n Write a function that takes in a non-empty array of integers that are sorted\n in ascending order and returns "
},
{
"path": "Arrays/string_halves.cpp",
"chars": 1312,
"preview": "/*\nYou are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first h"
},
{
"path": "Arrays/three_largest_no.py",
"chars": 1516,
"preview": "\n\n\"\"\"\nWrite a function that takes in an array of at least three integers and, \nwithout sorting the input array, returns "
},
{
"path": "Arrays/total_hamming_distance.cpp",
"chars": 4266,
"preview": "/* \n\nIntroduction:\n\n This documentation provides a detailed explanation of the problem statement, algorithm, and impl"
},
{
"path": "Arrays/tournament_winner.go",
"chars": 3118,
"preview": "/*\n There's an algorithms tournament taking place in which teams of programmers\n compete against each other to solve a"
},
{
"path": "Arrays/triplet_sum.cpp",
"chars": 3308,
"preview": "/*\nGiven an array of integers, nums, and an integer value, target,\ndetermine if there are any three integers in nums who"
},
{
"path": "Arrays/triplet_sum.go",
"chars": 2139,
"preview": "/*\nGiven an array of integers, nums, and an integer value, target,\ndetermine if there are any three integers in nums who"
},
{
"path": "Arrays/triplet_sum.java",
"chars": 3501,
"preview": "/*\nGiven an array of integers, nums, and an integer value, target,\ndetermine if there are any three integers in nums who"
},
{
"path": "Arrays/triplet_sum.js",
"chars": 2002,
"preview": "/*\nGiven an array of integers, nums, and an integer value, target,\ndetermine if there are any three integers in nums who"
},
{
"path": "Arrays/triplet_sum.py",
"chars": 899,
"preview": "'''\nGiven an array of integers, nums, and an integer value, target,\ndetermine if there are any three integers in nums wh"
},
{
"path": "Arrays/urlify.go",
"chars": 1096,
"preview": "// Implement an algorithm to replace all spaces with %20, assumew we have extra buffer at the end.\n// Input : Mr Ashish "
},
{
"path": "Backtracking/Generate_Parentheses.py",
"chars": 1311,
"preview": "'''\n Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n Exam"
},
{
"path": "Backtracking/geenrate_parentheses.go",
"chars": 3272,
"preview": "// Implementation of generating all combinations of well-formed parentheses\n/*\n\tThe generateParenthesis function takes a"
},
{
"path": "Backtracking/n_queen.cpp",
"chars": 1916,
"preview": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n// Function to check if it's safe to place a queen at board"
},
{
"path": "Backtracking/n_queens.java",
"chars": 4940,
"preview": "/**\n * Problem :- N-Queens\n https://leetcode.com/problems/n-queens/description/\n \n \n Approach:-\n The approach uses back"
},
{
"path": "Backtracking/sudoko_solver.java",
"chars": 3246,
"preview": "/*Write a program to solve a Sudoku puzzle by filling the empty cells.\n\nA sudoku solution must satisfy all of the follow"
},
{
"path": "Binary Search/BinarySearchRecursive.java",
"chars": 1428,
"preview": "\n/*\n * Problem : Implement Binary Search using Recursion.\n * \n * RECURSION : Function that calls itself is called recurs"
},
{
"path": "Binary Search/binary_search.cpp",
"chars": 2475,
"preview": "/*\n The binarySearch function takes in a sorted vector of integers arr and a target value target to search for.\n T"
},
{
"path": "Binary Search/binary_search.js",
"chars": 1288,
"preview": "/**\n * Finds the first and last occurrence of a target value in a sorted array.\n *\n * @param {number[]} N - The sorted a"
},
{
"path": "Binary Search/binary_search.py",
"chars": 1753,
"preview": "\"\"\"\n Intuition:\n If you have to guess a magic number from 1-100, the best first attempt would be to guess '50'"
},
{
"path": "Binary Search/binary_search_iterative.go",
"chars": 1523,
"preview": "/*\n Write a function that takes in a sorted array of integers as well as a target\n integer. The function should use th"
},
{
"path": "Binary Search/binary_search_recursive.go",
"chars": 1532,
"preview": "/*\n\tImplelemtation of Recursive Binary Search\n\n\tIn computer science, binary search, also known as half-interval search,\n"
},
{
"path": "Binary Search/binary_serach_first_and_last_occurence.py",
"chars": 1787,
"preview": "class Solution:\n def __init__(self):\n self.start_index=-1\n self.end_index=-1\n \n ''' Time complexi"
},
{
"path": "Binary Search/first_and_last_pos.js",
"chars": 3087,
"preview": "/* \n -----------QUESTION--------------\n\nGiven an array of integers nums sorte"
},
{
"path": "Binary Search/first_and_last_pos_of_element.cpp",
"chars": 1674,
"preview": "/*\nGiven an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given targ"
},
{
"path": "Binary Search/first_and_last_position.java",
"chars": 2360,
"preview": "/*\n Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given tar"
},
{
"path": "Binary Search/first_last_pos.java",
"chars": 2289,
"preview": "/* Given a sorted array arr containing n elements with possibly duplicate elements, \nthe task is to find indexes of firs"
},
{
"path": "Binary Search/first_occurance.go",
"chars": 604,
"preview": "// Search of first occurance of element using Binary search\n// Sample Input {0, 1, 1, 4, 5} key 1\n// Output 1\n// Time co"
},
{
"path": "Binary Search/first_occurence.java",
"chars": 1554,
"preview": "/* Finding the index of the first occurence of a number in a sorted array: \nGiven a sorted array and a number x,find the"
},
{
"path": "Binary Search/first_true.cpp",
"chars": 1840,
"preview": "/*\n An array of boolean values is divided into two sections; the left section consists of all false and the \n righ"
},
{
"path": "Binary Search/first_true.go",
"chars": 1754,
"preview": "/*\n An array of boolean values is divided into two sections; the left section consists of all false and the \n righ"
},
{
"path": "Binary Search/first_true.java",
"chars": 1795,
"preview": "/*\n An array of boolean values is divided into two sections; the left section consists of all false and the \n righ"
},
{
"path": "Binary Search/first_true.js",
"chars": 1578,
"preview": "/*\n An array of boolean values is divided into two sections; the left section consists of all false and the \n righ"
},
{
"path": "Binary Search/first_true.py",
"chars": 1628,
"preview": "'''\n An array of boolean values is divided into two sections; the left section consists of all false and the \n rig"
},
{
"path": "Binary Search/floor_of_target.java",
"chars": 1239,
"preview": "/* Floor of an element in a sorted array\n You are given a sorted array nums and a target . \n Find the index of the"
},
{
"path": "Binary Search/index_position.java",
"chars": 1494,
"preview": "/* BINARY SEARCH\n Problem Statement:\n Given an array of integers nums sorted in ascending order and a target ,\n Yo"
},
{
"path": "Binary Search/infinity_array.java",
"chars": 1769,
"preview": "/*Binary Search in an Infinite array in Java\n * Given an array whose size is not fixed,find the index of the target elem"
},
{
"path": "Binary Search/last_occurance.go",
"chars": 706,
"preview": "// Search of last occurance of element using Binary search\n// Sample Input {0, 1, 1, 4, 5} key 1\n// Output 1\n// Time con"
},
{
"path": "Binary Search/median_of_two_sorted_arrays.cpp",
"chars": 4025,
"preview": "/*\nApproach: \n let nums1 = [1, 3, 4, 7, 10, 12], nums2 = [2, 3, 6, 15]\n\n In order to find the median, we need a si"
},
{
"path": "Binary Search/median_of_two_sorted_arrays.js",
"chars": 2358,
"preview": "/*\nGiven two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.\n\n "
},
{
"path": "Binary Search/minimum_in_rotated_sorted_array.cpp",
"chars": 1773,
"preview": "/*\n Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array n"
},
{
"path": "Binary Search/perfect_square.java",
"chars": 1456,
"preview": "/* finding the perfect square\nGiven a positive integer num, return true if num is a perfect square or false otherwise.\n\n"
},
{
"path": "Binary Search/search_in_rotated_sorted_array.cpp",
"chars": 2441,
"preview": "/*\n\tGiven the array nums after the possible rotation and an integer target, return the index of target if it is in nums,"
},
{
"path": "Binary Search/search_in_sorted_rotated_array.cpp",
"chars": 1868,
"preview": "/*\n There is an integer array nums sorted in ascending order (with distinct values).\n\n Prior to being passed to yo"
},
{
"path": "Binary Search/search_in_sorted_rotated_array.go",
"chars": 3052,
"preview": "/*\n\tThe code snippet represents a function `SearchInSortedMatrix` that searches for a target value in a sorted matrix an"
},
{
"path": "Binary Search/search_in_sorted_rotated_array.java",
"chars": 2328,
"preview": "/*There is an integer array nums sorted in ascending order (with distinct values).\n\nPrior to being passed to your functi"
},
{
"path": "Binary Search/search_in_sorted_rotated_array.py",
"chars": 1720,
"preview": "'''\n There is an integer array nums sorted in ascending order (with distinct values).\n\n Prior to being passed to y"
},
{
"path": "Binary Search/search_insert_position.js",
"chars": 2872,
"preview": "// https://leetcode.com/problems/search-insert-position/description/\n\n/*\n\nGiven a sorted array of distinct integers and "
},
{
"path": "Binary Search/square_root.java",
"chars": 1217,
"preview": "/* Square root of a number\nGiven a non-negative integer x, return the square root of x rounded down to the nearest integ"
},
{
"path": "Bit Manipulation/bloom_filter.cpp",
"chars": 6565,
"preview": "// Bloom Filter Implementation\r\n// Question: How does the Bloom filter work, and how is it implemented in the C++\r\n\r\n// "
},
{
"path": "Bit Manipulation/bloom_filter.py",
"chars": 4731,
"preview": "# Bloom Filter Implementation\r\n# Question: How can I implement a Bloom filter in Python?\r\n\r\n# explanation of the approa"
},
{
"path": "Bit Manipulation/count_bits.go",
"chars": 631,
"preview": "// Program to count the number of bits that are set to 1 in an integer\n// The following program tests bits one at a time"
},
{
"path": "Bit Manipulation/interesting_array.java",
"chars": 629,
"preview": "package BitManipulation;\n\nimport com.google.common.base.Stopwatch;\n\npublic class InterestingArray {\n public static vo"
},
{
"path": "Bit Manipulation/mod_array.java",
"chars": 2330,
"preview": "/**\n * You are given a large number in the form of a array A of size N where each element denotes a digit of the number."
},
{
"path": "Bit Manipulation/number_of_1_bits.java",
"chars": 1003,
"preview": "/**\n * Write a function that takes an integer and returns the number of 1 bits it has.\n *\n *\n * Problem Constraints\n * 1"
},
{
"path": "Bit Manipulation/parity_of_a_word.go",
"chars": 1055,
"preview": "// Computing the parity of a word\n// The parity of a binary word is 1 if the number of 1s in the word is odd\n// The pari"
},
{
"path": "Bit Manipulation/power_of_2.cpp",
"chars": 614,
"preview": "/*\n Given an integer n, return true if it is a power of two. Otherwise, return false.\n\n An integer n is a power of"
},
{
"path": "Bit Manipulation/reduce_to_zero.cpp",
"chars": 1144,
"preview": "/*\nGiven an integer num, return the number of steps to reduce it to zero.\n\nIn one step, if the current number is even, y"
},
{
"path": "Bit Manipulation/setbits.cpp",
"chars": 581,
"preview": "// Program to count the number of bits that are set to 1 in an integer\n// The following program tests bits one at a time"
},
{
"path": "Bit Manipulation/single_number.java",
"chars": 1291,
"preview": "/**\n * Given an array of integers A, every element appears twice except for one. Find that integer that occurs once.\n *\n"
},
{
"path": "Bit Manipulation/subarrays_with_bitwise_OR_1.java",
"chars": 1544,
"preview": "/**\n * Problem Description\n * Given an array B of length A with elements 1 or 0. Find the number of subarrays such that "
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 6230,
"preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participa"
},
{
"path": "CONTRIBUTING.md",
"chars": 4769,
"preview": "## Contributing\n\n## Fork this repository\n\nGet involved! Fork this repository by clicking on the fork button on the top o"
},
{
"path": "Dynamic Programming/best_time_to_buy_and_sell_stock.cpp",
"chars": 1382,
"preview": "// Best Time to buy and sell stock\n/*\n\tExplanation:\n\tWe start by initializing the minimum price to the maximum integer v"
},
{
"path": "Dynamic Programming/best_time_to_buy_and_sell_stock.go",
"chars": 1289,
"preview": "// Best Time to buy and sell stock\n/*\n\tExplanation:\n\tWe start by initializing the minimum price to the maximum integer v"
},
{
"path": "Dynamic Programming/best_time_to_buy_and_sell_stock.java",
"chars": 1818,
"preview": "// Best Time to buy and sell stock\n/*\n\tExplanation:\n\tWe start by initializing the minimum price to the maximum integer v"
},
{
"path": "Dynamic Programming/best_time_to_buy_and_sell_stock.js",
"chars": 1341,
"preview": "// Best Time to buy and sell stock\n/*\n\tExplanation:\n\tWe start by initializing the minimum price to the maximum integer v"
},
{
"path": "Dynamic Programming/best_time_to_buy_and_sell_stock.py",
"chars": 1702,
"preview": "# Best Time to buy and sell stock\n'''\n The function maxProfit takes a list of integers prices and returns the maximum"
},
{
"path": "Dynamic Programming/climb_stairs.cpp",
"chars": 1528,
"preview": "// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1\n// or 2 st"
},
{
"path": "Dynamic Programming/climb_stairs.go",
"chars": 1357,
"preview": "package main\n\n// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either clim"
},
{
"path": "Dynamic Programming/climb_stairs.java",
"chars": 1755,
"preview": "// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1\n// or 2 st"
},
{
"path": "Dynamic Programming/climb_stairs.js",
"chars": 1408,
"preview": "// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1\n// or 2 st"
},
{
"path": "Dynamic Programming/climb_stairs.py",
"chars": 1383,
"preview": "'''\nA child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 \\\nor 2 st"
},
{
"path": "Dynamic Programming/coin_change.cpp",
"chars": 3137,
"preview": "/*\n Coin Change Problem\n You are given an integer array coins representing coins of different denominations and an"
},
{
"path": "Dynamic Programming/coin_change.go",
"chars": 2831,
"preview": "/*\n\tCoin Change Problem\n You are given an integer array coins representing coins of different denominations and an in"
},
{
"path": "Dynamic Programming/coin_change.java",
"chars": 3813,
"preview": "/* \n Coin Change Problem\n You are given an integer array coins representing coins of different denominations and a"
},
{
"path": "Dynamic Programming/coin_change.js",
"chars": 3276,
"preview": "/*\n Coin Change Problem:-\n\n\n Question:-\n You are given an integer array coins representing coins of different d"
},
{
"path": "Dynamic Programming/coin_change.py",
"chars": 2011,
"preview": "'''\n Coin Change Problem\n You are given an integer array coins representing coins of different denominations and a"
},
{
"path": "Dynamic Programming/dice_throws.go",
"chars": 5661,
"preview": "/*\n\n You're given a set of numDice dice, each with numSides sides, and a target integer, which represents a target"
},
{
"path": "Dynamic Programming/disk_stacking.go",
"chars": 7177,
"preview": "/*\n\tYou're given a non-empty array of arrays where each subarray holds three integers and represents a disk.\n\tThese inte"
},
{
"path": "Dynamic Programming/disk_stacking.py",
"chars": 5860,
"preview": "'''\n\tYou're given a non-empty array of arrays where each subarray holds three integers and represents a disk.\n\tThese int"
},
{
"path": "Dynamic Programming/distance_of_nearest_0.cpp",
"chars": 4409,
"preview": "/*Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.\r\n\r\nThe distance between two adja"
},
{
"path": "Dynamic Programming/distance_of_nearest_0.py",
"chars": 3041,
"preview": "'''\nGiven an m x n binary matrix mat, return the distance of the nearest 0 for each cell.\nThe distance between two adjac"
},
{
"path": "Dynamic Programming/distane_of_nearest_0.go",
"chars": 2573,
"preview": "// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java\n\n// Solution\n// // This "
},
{
"path": "Dynamic Programming/distane_of_nearest_0.java",
"chars": 2939,
"preview": "// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java\n\n\n// Solution\n// // This"
},
{
"path": "Dynamic Programming/distane_of_nearest_0.js",
"chars": 2769,
"preview": "// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java\n\n\n// Solution\n// // This"
},
{
"path": "Dynamic Programming/edit_distance_dp.cpp",
"chars": 2160,
"preview": "/*\n Given two strings str1 and str2 and following three operations that can performed on str1. \n 1) Insert\n 2) "
},
{
"path": "Dynamic Programming/edit_distance_dp.go",
"chars": 1847,
"preview": "/*\n Given two strings str1 and str2 and following three operations that can performed on str1.\n 1) Insert\n 2) Remo"
},
{
"path": "Dynamic Programming/edit_distance_dp.java",
"chars": 2335,
"preview": "/*\n Given two strings str1 and str2 and following three operations that can performed on str1.\n 1) Insert\n 2) Remo"
},
{
"path": "Dynamic Programming/edit_distance_dp.js",
"chars": 1950,
"preview": "/*\n Given two strings str1 and str2 and following three operations that can performed on str1.\n 1) Insert\n 2) Remo"
},
{
"path": "Dynamic Programming/edit_distance_dp.py",
"chars": 1834,
"preview": "'''\n Given two strings str1 and str2 and following three operations that can performed on str1.\n 1) Insert\n 2) Rem"
},
{
"path": "Dynamic Programming/edit_distance_memoized.cpp",
"chars": 1379,
"preview": "/*\n Given two strings str1 and str2 and following three operations that can performed on str1. \n 1) Insert\n 2) "
},
{
"path": "Dynamic Programming/edit_distance_recursive.cpp",
"chars": 1200,
"preview": "/*\n Given two strings str1 and str2 and following three operations that can performed on str1. \n 1) Insert\n 2) "
}
]
// ... and 694 more files (download for full content)
About this extraction
This page contains the full source code of the akgmage/data-structures-and-algorithms GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 894 files (2.3 MB), approximately 654.6k tokens, and a symbol index with 2986 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.