Showing preview only (901K chars total). Download the full file or copy to clipboard to get everything.
Repository: jaychsu/algorithm
Branch: master
Commit: 91892fd64281
Files: 638
Total size: 761.9 KB
Directory structure:
gitextract_pg3fa3pn/
├── .editorconfig
├── .gitignore
├── .travis.yml
├── README.md
├── bin/
│ ├── test_javascript.js
│ └── test_python.py
├── codewars/
│ ├── delete_occurrences_of_an_element_if_it_occurs_more_than_n_times.js
│ ├── double_cola.js
│ ├── iq_test.js
│ ├── is_a_number_prime.js
│ ├── multiply.js
│ ├── rectangle_into_squares.js
│ ├── reverse_words.js
│ ├── simple_encryption_1_alternating_split.js
│ ├── sudoku_solution_validator.js
│ ├── take_a_ten_minute_walk.js
│ ├── tribonacci_sequence.js
│ ├── unique_in_order.js
│ └── who_likes_it.js
├── leetcode/
│ ├── 101_symmetric_tree.py
│ ├── 105_construct_binary_tree_from_preorder_and_inorder_traversal.py
│ ├── 108_convert_sorted_array_to_binary_search_tree.py
│ ├── 112_path_sum.py
│ ├── 113_path_sum_ii.py
│ ├── 116_populating_next_right_pointers_in_each_node.py
│ ├── 117_populating_next_right_pointers_in_each_node_ii.py
│ ├── 118_pascal_s_triangle.py
│ ├── 11_container_with_most_water.py
│ ├── 124_binary_tree_maximum_path_sum.py
│ ├── 134_gas_station.py
│ ├── 136_single_number.py
│ ├── 149_max_points_on_a_line.py
│ ├── 14_longest_common_prefix.py
│ ├── 150_evaluate_reverse_polish_notation.py
│ ├── 157_read_n_characters_given_read4.py
│ ├── 160_intersection_of_two_linked_lists.py
│ ├── 165_compare_version_numbers.py
│ ├── 166_fraction_to_recurring_decimal.py
│ ├── 169_majority_element.py
│ ├── 171_excel_sheet_column_number.py
│ ├── 172_factorial_trailing_zeroes.py
│ ├── 174_dungeon_game.py
│ ├── 179_largest_number.py
│ ├── 17_letter_combinations_of_a_phone_number.py
│ ├── 190_reverse_bits.py
│ ├── 191_number_of_1_bits.py
│ ├── 19_remove_nth_node_from_end_of_list.py
│ ├── 202_happy_number.py
│ ├── 204_count_primes.py
│ ├── 208_implement_trie_prefix_tree.py
│ ├── 20_valid_parentheses.py
│ ├── 215_kth_largest_element_in_an_array.py
│ ├── 217_contains_duplicate.py
│ ├── 218_the_skyline_problem.py
│ ├── 224_basic_calculator.py
│ ├── 227_basic_calculator_ii.py
│ ├── 229_majority_element_ii.py
│ ├── 22_generate_parentheses.py
│ ├── 230_kth_smallest_element_in_a_bst.py
│ ├── 234_palindrome_linked_list.py
│ ├── 235_lowest_common_ancestor_of_a_binary_search_tree.py
│ ├── 236_lowest_common_ancestor_of_a_binary_tree.py
│ ├── 237_delete_node_in_a_linked_list.py
│ ├── 242_valid_anagram.py
│ ├── 269_alien_dictionary.py
│ ├── 277_find_the_celebrity.py
│ ├── 280_wiggle_sort.py
│ ├── 282_expression_add_operators.py
│ ├── 285_inorder_successor_in_bst.py
│ ├── 288_unique_word_abbreviation.py
│ ├── 289_game_of_life.py
│ ├── 295_find_median_from_data_stream.py
│ ├── 299_bulls_and_cows.py
│ ├── 303_range_sum_query_immutable.py
│ ├── 304_range_sum_query_2d_immutable.py
│ ├── 307_range_sum_query_mutable.py
│ ├── 308_range_sum_query_2d_mutable.py
│ ├── 30_substring_with_concatenation_of_all_words.py
│ ├── 315_count_of_smaller_numbers_after_self.py
│ ├── 323_number_of_connected_components_in_an_undirected_graph.py
│ ├── 324_wiggle_sort_ii.py
│ ├── 326_power_of_three.py
│ ├── 329_longest_increasing_path_in_a_matrix.py
│ ├── 334_increasing_triplet_subsequence.py
│ ├── 33_search_in_rotated_sorted_array.py
│ ├── 340_longest_substring_with_at_most_k_distinct_characters.py
│ ├── 344_reverse_string.py
│ ├── 347_top_k_frequent_elements.py
│ ├── 348_design_tic_tac_toe.py
│ ├── 353_design_snake_game.py
│ ├── 36_valid_sudoku.py
│ ├── 377_combination_sum_iv.py
│ ├── 378_kth_smallest_element_in_a_sorted_matrix.py
│ ├── 37_sudoku_solver.py
│ ├── 380_insert_delete_getrandom_o1.py
│ ├── 381_insert_delete_getrandom_o1_duplicates_allowed.py
│ ├── 382_linked_list_random_node.py
│ ├── 384_shuffle_an_array.py
│ ├── 386_lexicographical_numbers.py
│ ├── 387_first_unique_character_in_a_string.py
│ ├── 388_longest_absolute_file_path.py
│ ├── 389_find_the_difference.py
│ ├── 38_count_and_say.py
│ ├── 390_elimination_game.py
│ ├── 391_perfect_rectangle.py
│ ├── 395_longest_substring_with_at_least_k_repeating_characters.py
│ ├── 398_random_pick_index.py
│ ├── 399_evaluate_division.py
│ ├── 406_queue_reconstruction_by_height.py
│ ├── 416_partition_equal_subset_sum.py
│ ├── 417_pacific_atlantic_water_flow.py
│ ├── 41_first_missing_positive.py
│ ├── 437_path_sum_iii.py
│ ├── 454_4sum_ii.py
│ ├── 461_hamming_distance.py
│ ├── 480_sliding_window_median.py
│ ├── 486_predict_the_winner.py
│ ├── 48_rotate_image.py
│ ├── 490_the_maze.py
│ ├── 494_target_sum.py
│ ├── 499_the_maze_iii.py
│ ├── 505_the_maze_ii.py
│ ├── 518_coin_change_2.py
│ ├── 51_n_queens.py
│ ├── 524_longest_word_in_dictionary_through_deleting.py
│ ├── 52_n_queens_ii.py
│ ├── 530_minimum_absolute_difference_in_bst.py
│ ├── 542_01_matrix.py
│ ├── 54_spiral_matrix.py
│ ├── 592_fraction_addition_and_subtraction.py
│ ├── 593_valid_square.py
│ ├── 59_spiral_matrix_ii.py
│ ├── 5_longest_palindromic_substring.py
│ ├── 616_add_bold_tag_in_string.py
│ ├── 643_maximum_average_subarray_i.py
│ ├── 66_plus_one.py
│ ├── 676_implement_magic_dictionary.py
│ ├── 679_24_game.py
│ ├── 681_next_closest_time.py
│ ├── 682_baseball_game.py
│ ├── 683_k_empty_slots.py
│ ├── 684_redundant_connection.py
│ ├── 685_redundant_connection_ii.py
│ ├── 688_knight_probability_in_chessboard.py
│ ├── 689_maximum_sum_of_3_non_overlapping_subarrays.py
│ ├── 697_degree_of_an_array.py
│ ├── 719_find_k_th_smallest_pair_distance.py
│ ├── 721_accounts_merge.py
│ ├── 734_sentence_similarity.py
│ ├── 737_sentence_similarity_ii.py
│ ├── 744_find_smallest_letter_greater_than_target.py
│ ├── 746_min_cost_climbing_stairs.py
│ ├── 747_largest_number_at_least_twice_of_others.py
│ ├── 748_shortest_completing_word.py
│ ├── 749_contain_virus.py
│ ├── 750_number_of_corner_rectangles.py
│ ├── 758_bold_words_in_string.py
│ ├── 769_max_chunks_to_make_sorted.py
│ ├── 776_split_bst.py
│ ├── 777_swap_adjacent_in_lr_string.py
│ ├── 778_swim_in_rising_water.py
│ ├── 779_k_th_symbol_in_grammar.py
│ ├── 783_minimum_distance_between_bst_nodes.py
│ ├── 784_letter_case_permutation.py
│ ├── 785_is_graph_bipartite.py
│ ├── 786_k_th_smallest_prime_fraction.py
│ ├── 787_cheapest_flights_within_k_stops.py
│ ├── 788_rotated_digits.py
│ ├── 789_escape_the_ghosts.py
│ ├── 790_domino_and_tromino_tiling.py
│ ├── 791_custom_sort_string.py
│ ├── 7_reverse_integer.py
│ ├── 81_search_in_rotated_sorted_array_ii.py
│ └── 8_string_to_integer_atoi.py
├── lintcode/
│ ├── 102_linked_list_cycle.py
│ ├── 103_linked_list_cycle_ii.py
│ ├── 104_merge_k_sorted_lists.py
│ ├── 105_copy_list_with_random_pointer.py
│ ├── 107_word_break.py
│ ├── 108_palindrome_partitioning_ii.py
│ ├── 109_triangle.py
│ ├── 10_string_permutation_ii.py
│ ├── 110_minimum_path_sum.py
│ ├── 111_climbing_stairs.py
│ ├── 114_unique_paths.py
│ ├── 115_unique_paths_ii.py
│ ├── 116_jump_game.py
│ ├── 117_jump_game_ii.py
│ ├── 118_distinct_subsequences.py
│ ├── 119_edit_distance.py
│ ├── 11_search_range_in_binary_search_tree.py
│ ├── 120_word_ladder.py
│ ├── 121_word_ladder_ii.py
│ ├── 122_largest_rectangle_in_histogram.py
│ ├── 123_word_search.py
│ ├── 124_longest_consecutive_sequence.py
│ ├── 125_backpack_ii.py
│ ├── 126_max_tree.py
│ ├── 127_topological_sorting.py
│ ├── 128_hash_function.py
│ ├── 129_rehashing.py
│ ├── 12_min_stack.py
│ ├── 130_heapify.py
│ ├── 131_building_outline.py
│ ├── 132_word_search_ii.py
│ ├── 134_lru_cache.py
│ ├── 135_combination_sum.py
│ ├── 1365_minimum_cycle_section.py
│ ├── 1366_directed_graph_loop.py
│ ├── 1367_police_distance.py
│ ├── 1368_same_number.py
│ ├── 136_palindrome_partitioning.py
│ ├── 137_clone_graph.py
│ ├── 138_subarray_sum.py
│ ├── 139_subarray_sum_closest.py
│ ├── 13_strstr.py
│ ├── 141_sqrtx.py
│ ├── 142_o1_check_power_of_2.py
│ ├── 143_sort_colors_ii.py
│ ├── 148_sort_colors.py
│ ├── 149_best_time_to_buy_and_sell_stock.py
│ ├── 14_first_position_of_target.py
│ ├── 150_best_time_to_buy_and_sell_stock_ii.py
│ ├── 151_best_time_to_buy_and_sell_stock_iii.py
│ ├── 153_combination_sum_ii.py
│ ├── 154_regular_expression_matching.py
│ ├── 155_minimum_depth_of_binary_tree.py
│ ├── 156_merge_intervals.py
│ ├── 158_two_strings_are_anagrams.py
│ ├── 159_find_minimum_in_rotated_sorted_array.py
│ ├── 15_permutations.py
│ ├── 160_find_minimum_in_rotated_sorted_array_ii.py
│ ├── 165_merge_two_sorted_lists.py
│ ├── 167_add_two_numbers.py
│ ├── 168_burst_balloons.py
│ ├── 16_permutations_ii.py
│ ├── 171_anagrams.py
│ ├── 175_invert_binary_tree.py
│ ├── 178_graph_valid_tree.py
│ ├── 17_subsets.py
│ ├── 183_wood_cut.py
│ ├── 18_subsets_ii.py
│ ├── 190_next_permutation_ii.py
│ ├── 191_maximum_product_subarray.py
│ ├── 192_wildcard_matching.py
│ ├── 196_find_the_missing_number.py
│ ├── 197_permutation_index.py
│ ├── 198_permutation_index_ii.py
│ ├── 1_a_b_problem.py
│ ├── 204_singleton.py
│ ├── 211_string_permutation.py
│ ├── 215_rate_limiter.py
│ ├── 221_add_two_numbers_ii.py
│ ├── 231_typeahead.py
│ ├── 232_tiny_url.py
│ ├── 234_webpage_crawler.py
│ ├── 236_swap_bits.py
│ ├── 242_convert_binary_tree_to_linked_lists_by_depth.py
│ ├── 243_amicable_pair
│ ├── 245_subtree.py
│ ├── 246_binary_tree_path_sum_ii.py
│ ├── 24_lfu_cache.py
│ ├── 254_drop_eggs.py
│ ├── 272_climbing_stairs_ii.py
│ ├── 28_search_a_2d_matrix.py
│ ├── 29_interleaving_string.py
│ ├── 30_insert_interval.py
│ ├── 31_partition_array.py
│ ├── 32_minimum_window_substring.py
│ ├── 35_reverse_linked_list.py
│ ├── 360_sliding_window_median.py
│ ├── 362_sliding_window_maximum.py
│ ├── 363_trapping_rain_water.py
│ ├── 364_trapping_rain_water_ii.py
│ ├── 368_expression_evaluation.py
│ ├── 36_reverse_linked_list_ii.py
│ ├── 376_binary_tree_path_sum.py
│ ├── 378_convert_binary_search_tree_to_doubly_linked_list.py
│ ├── 382_triangle_count.py
│ ├── 384_longest_substring_without_repeating_characters.py
│ ├── 386_longest_substring_with_at_most_k_distinct_characters.py
│ ├── 38_search_a_2d_matrix_ii.py
│ ├── 390_find_peak_element_ii.py
│ ├── 391_number_of_airplanes_in_the_sky.py
│ ├── 392_house_robber.py
│ ├── 393_best_time_to_buy_and_sell_stock_iv.py
│ ├── 394_coins_in_a_line.py
│ ├── 395_coins_in_a_line_ii.py
│ ├── 396_coins_in_a_line_iii.py
│ ├── 397_longest_increasing_continuous_subsequence.py
│ ├── 3_digit_counts.py
│ ├── 401_kth_smallest_number_in_sorted_matrix.py
│ ├── 402_continuous_subarray_sum.py
│ ├── 406_minimum_size_subarray_sum.py
│ ├── 40_implement_queue_by_two_stacks.py
│ ├── 414_divide_two_integers.py
│ ├── 415_valid_palindrome.py
│ ├── 417_valid_number.py
│ ├── 418_integer_to_roman.py
│ ├── 419_roman_to_integer.py
│ ├── 41_maximum_subarray.py
│ ├── 42_maximum_subarray_ii.py
│ ├── 430_scramble_string.py
│ ├── 431_connected_component_in_undirected_graph.py
│ ├── 432_find_the_weak_connected_component_in_the_directed_graph.py
│ ├── 433_number_of_islands.py
│ ├── 434_number_of_islands_ii.py
│ ├── 437_copy_books.py
│ ├── 43_maximum_subarray_iii.py
│ ├── 440_backpack_iii.py
│ ├── 442_implement_trie.py
│ ├── 443_two_sum_greater_than_target.py
│ ├── 447_search_in_a_big_sorted_array.py
│ ├── 450_reverse_nodes_in_k_group.py
│ ├── 453_flatten_binary_tree_to_linked_list.py
│ ├── 457_classical_binary_search.py
│ ├── 458_last_position_of_target.py
│ ├── 459_closest_number_in_sorted_array.py
│ ├── 45_maximum_subarray_difference.py
│ ├── 460_k_closest_numbers_in_sorted_array.py
│ ├── 461_kth_smallest_numbers_in_unsorted_array.py
│ ├── 462_total_occurrence_of_target.py
│ ├── 465_kth_smallest_sum_in_two_sorted_arrays.py
│ ├── 469_identical_binary_tree.py
│ ├── 471_top_k_frequent_words.py
│ ├── 472_binary_tree_path_sum_iii.py
│ ├── 473_add_and_search_word.py
│ ├── 474_lowest_common_ancestor_ii.py
│ ├── 475_binary_tree_maximum_path_sum_ii.py
│ ├── 479_second_max_of_array.py
│ ├── 480_binary_tree_paths.py
│ ├── 486_merge_k_sorted_arrays.py
│ ├── 494_implement_stack_by_two_queues.py
│ ├── 496_toy_factory.py
│ ├── 497_shape_factory.py
│ ├── 498_parking_lot.py
│ ├── 499_word_count.py
│ ├── 4_ugly_number_ii.py
│ ├── 500_inverted_index.py
│ ├── 501_mini_twitter.py
│ ├── 502_mini_cassandra.py
│ ├── 503_anagram_map_reduce.py
│ ├── 504_inverted_index_map_reduce.py
│ ├── 505_web_logger.py
│ ├── 509_mini_yelp.py
│ ├── 510_maximal_rectangle.py
│ ├── 512_decode_ways.py
│ ├── 513_perfect_squares.py
│ ├── 515_paint_house.py
│ ├── 516_paint_house_ii.py
│ ├── 517_ugly_number.py
│ ├── 518_super_ugly_number.py
│ ├── 519_consistent_hashing.py
│ ├── 51_previous_permutation.py
│ ├── 520_consistent_hashing_ii.py
│ ├── 521_remove_duplicate_numbers_in_array.py
│ ├── 522_tiny_url_ii.py
│ ├── 523_url_parser.py
│ ├── 525_mini_uber.py
│ ├── 526_load_balancer.py
│ ├── 527_trie_serialization.py
│ ├── 528_flatten_nested_list_iterator.py
│ ├── 529_geohash.py
│ ├── 52_next_permutation.py
│ ├── 530_geohash_ii.py
│ ├── 531_six_degrees.py
│ ├── 532_reverse_pairs.py
│ ├── 533_two_sum_closest_to_target.py
│ ├── 534_house_robber_ii.py
│ ├── 538_memcache.py
│ ├── 539_move_zeroes.py
│ ├── 53_reverse_words_in_a_string.py
│ ├── 540_zigzag_iterator.py
│ ├── 541_zigzag_iterator_ii.py
│ ├── 543_kth_largest_in_n_arrays.py
│ ├── 544_top_k_largest_numbers.py
│ ├── 545_top_k_largest_numbers_ii.py
│ ├── 547_intersection_of_two_arrays.py
│ ├── 548_intersection_of_two_arrays_ii.py
│ ├── 54_string_to_integer_ii.py
│ ├── 551_nested_list_weight_sum.py
│ ├── 552_create_maximum_number.py
│ ├── 553_bomb_enemy.py
│ ├── 555_counting_bloom_filter.py
│ ├── 556_standard_bloom_filter.py
│ ├── 559_trie_service.py
│ ├── 560_friendship_service.py
│ ├── 563_backpack_v.py
│ ├── 564_backpack_vi.py
│ ├── 565_heart_beat.py
│ ├── 566_gfs_client.py
│ ├── 56_two_sum.py
│ ├── 573_build_post_office_ii.py
│ ├── 574_build_post_office.py
│ ├── 575_expression_expand.py
│ ├── 578_lowest_common_ancestor_iii.py
│ ├── 57_3sum.py
│ ├── 582_word_break_ii.py
│ ├── 584_drop_eggs_ii.py
│ ├── 585_maximum_number_in_mountain_sequence.py
│ ├── 586_sqrtx_ii.py
│ ├── 587_two_sum_unique_pairs.py
│ ├── 589_connecting_graph.py
│ ├── 58_4sum.py
│ ├── 590_connecting_graph_ii.py
│ ├── 591_connecting_graph_iii.py
│ ├── 594_strstr_ii.py
│ ├── 595_binary_tree_longest_consecutive_sequence.py
│ ├── 596_minimum_subtree.py
│ ├── 597_subtree_with_maximum_average.py
│ ├── 598_zombie_in_matrix.py
│ ├── 599_insert_into_a_cyclic_sorted_list.py
│ ├── 59_3sum_closest.py
│ ├── 5_kth_largest_element.py
│ ├── 600_smallest_rectangle_enclosing_black_pixels.py
│ ├── 601_flatten_2d_vector.py
│ ├── 602_russian_doll_envelopes.py
│ ├── 603_largest_divisible_subset.py
│ ├── 604_window_sum.py
│ ├── 605_sequence_reconstruction.py
│ ├── 606_kth_largest_element_ii.py
│ ├── 607_two_sum_data_structure_design.py
│ ├── 608_two_sum_input_array_is_sorted.py
│ ├── 609_two_sum_less_than_or_equal_to_target.py
│ ├── 610_two_sum_difference_equals_to_target.py
│ ├── 611_knight_shortest_path.py
│ ├── 612_k_closest_points.py
│ ├── 613_high_five.py
│ ├── 614_binary_tree_longest_consecutive_sequence_ii.py
│ ├── 615_course_schedule.py
│ ├── 616_course_schedule_ii.py
│ ├── 617_maximum_average_subarray.py
│ ├── 618_search_graph_nodes.py
│ ├── 619_binary_tree_longest_consecutive_sequence_iii.py
│ ├── 61_search_for_a_range.py
│ ├── 620_maximum_subarray_iv.py
│ ├── 621_maximum_subarray_v.py
│ ├── 622_frog_jump.py
│ ├── 623_k_edit_distance.py
│ ├── 624_remove_substrings.py
│ ├── 625_partition_array_ii.py
│ ├── 630_knight_shortest_path_ii.py
│ ├── 633_find_the_duplicate_number.py
│ ├── 634_word_squares.py
│ ├── 635_boggle_game.py
│ ├── 636_132_pattern.py
│ ├── 646_first_position_unique_character.py
│ ├── 647_substring_anagrams.py
│ ├── 64_merge_sorted_array.py
│ ├── 654_sparse_matrix_multiplication.py
│ ├── 655_big_integer_addition.py
│ ├── 656_big_integer_multiplication.py
│ ├── 65_median_of_two_sorted_arrays.py
│ ├── 662_guess_number_game.py
│ ├── 664_counting_bits.py
│ ├── 667_longest_palindromic_subsequence.py
│ ├── 668_ones_and_zeroes.py
│ ├── 669_coin_change.py
│ ├── 66_binary_tree_preorder_traversal.py
│ ├── 676_decode_ways_ii.py
│ ├── 67_binary_tree_inorder_traversal.py
│ ├── 689_two_sum_bst_edtion.py
│ ├── 68_binary_tree_postorder_traversal.py
│ ├── 69_binary_tree_level_order_traversal.py
│ ├── 6_merge_two_sorted_arrays.py
│ ├── 70_binary_tree_level_order_traversal_ii.py
│ ├── 717_tree_longest_path_with_same_value.py
│ ├── 718_repeat_string.py
│ ├── 71_binary_tree_zigzag_level_order_traversal.py
│ ├── 724_minimum_partition.py
│ ├── 725_boolean_parenthesization.py
│ ├── 729_last_digit_by_factorial_divide.py
│ ├── 745_palindromic_ranges.py
│ ├── 74_first_bad_version.py
│ ├── 752_rogue_knight_sven.py
│ ├── 75_find_peak_element.py
│ ├── 76_longest_increasing_subsequence.py
│ ├── 772_group_anagrams.py
│ ├── 775_palindrome_pairs.py
│ ├── 776_strobogrammatic_number_ii.py
│ ├── 77_longest_common_subsequence.py
│ ├── 784_the_longest_common_prefix_ii.py
│ ├── 790_parser.py
│ ├── 791_merge_number.py
│ ├── 792_kth_prime_number.py
│ ├── 793_intersection_of_arrays.py
│ ├── 7_binary_tree_serialization.py
│ ├── 813_find_anagram_mappings.py
│ ├── 81_data_stream_median.py
│ ├── 823_input_stream.py
│ ├── 824_single_number_iv.py
│ ├── 826_computer_maintenance.py
│ ├── 830_string_sort.py
│ ├── 831_3sum_ii.py
│ ├── 832_count_negative_number.py
│ ├── 833_process_sequence.py
│ ├── 85_insert_node_in_a_binary_search_tree.py
│ ├── 86_binary_search_tree_iterator.py
│ ├── 87_remove_node_in_binary_search_tree.py
│ ├── 88_lowest_common_ancestor.py
│ ├── 89_k_sum.py
│ ├── 8_rotate_string.py
│ ├── 900_closest_binary_search_tree_value.py
│ ├── 901_closest_binary_search_tree_value_ii.py
│ ├── 919_meeting_rooms_ii.py
│ ├── 920_meeting_rooms.py
│ ├── 92_backpack.py
│ ├── 93_balanced_binary_tree.py
│ ├── 95_validate_binary_search_tree.py
│ ├── 96_partition_list.py
│ ├── 97_maximum_depth_of_binary_tree.py
│ ├── 98_sort_list.py
│ └── 9_fizz_buzz.py
├── other/
│ ├── anti_queue_reconstruction_by_height.py
│ ├── binary_tree_maximum_path_product.py
│ ├── candy_crush.py
│ ├── card_shuffler.py
│ ├── deep_fetch.js
│ ├── deep_fetch.test.js
│ ├── find_treasure_in_maze.py
│ ├── find_ways_in_board_game.py
│ ├── freq_iterator.py
│ ├── gcd_and_lcm.py
│ ├── get_most_popular_word.py
│ ├── guess_secret.py
│ ├── inorder_non_threaded_binary_tree_traversal.py
│ ├── is_valid_relation.py
│ ├── merge_mail.py
│ ├── reservation.py
│ ├── robot_cleaner.py
│ ├── snake_and_ladder_problem.py
│ ├── stock_stream.py
│ ├── string_abbreviation.py
│ ├── the_point_inside_polygon.py
│ ├── uneven_random_get.py
│ ├── unique_paths_with_followups.py
│ ├── unique_word_abbreviation_ii.py
│ └── upside_down_numbers.py
├── pramp/
│ ├── array_index_and_element_equality.py
│ ├── array_of_array_products.py
│ ├── award_budget_cuts.py
│ ├── bracket_match.py
│ ├── busiest_time_in_the_mall.py
│ ├── decrypt_message.py
│ ├── deletion_distance.py
│ ├── drone_flight_planner.py
│ ├── find_the_duplicates.py
│ ├── flatten_a_dictionary.py
│ ├── h_tree_construction.py
│ ├── k_messed_array_sort.py
│ ├── largest_smaller_bst_node.py
│ ├── number_of_paths.py
│ ├── pairs_with_specific_difference.py
│ ├── pancake_sort.py
│ ├── root_of_number.py
│ ├── sales_path.py
│ ├── sentence_reverse.py
│ ├── smallest_substring_of_all_characters.py
│ ├── time_planner.py
│ └── word_count_engine.py
└── topic/
├── README.md
├── _test/
│ └── python/
│ ├── __init__.py
│ └── test_base.py
├── balanced_search_tree/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ └── red_black_tree.py
├── bit_manipulation/
│ ├── README.md
│ └── python/
│ ├── __init__.py
│ ├── calculator_in_bit.py
│ └── calculator_in_bit__test.py
├── complexity_analysis.md
├── dynamic_programming/
│ └── README.md
├── graph/
│ ├── README.md
│ └── python/
│ ├── __init__.py
│ ├── union_find.py
│ └── union_find__test.py
├── hash/
│ └── python/
│ ├── __init__.py
│ ├── geohash.py
│ ├── geohash__test.py
│ ├── hashtable.py
│ └── hashtable__test.py
├── heap/
│ └── python/
│ ├── __init__.py
│ ├── binary_hash_heap.py
│ ├── binary_heap.py
│ ├── heap__test.py
│ ├── lazy_removable_heapq.py
│ └── removable_heapq.py
├── language/
│ ├── javascript/
│ │ ├── README.md
│ │ └── traversal.md
│ ├── php/
│ │ └── README.md
│ ├── python/
│ │ ├── README.md
│ │ ├── matrix.md
│ │ ├── runtime_of_builtins.md
│ │ └── traversal.md
│ └── sql/
│ └── README.md
├── linked_list/
│ ├── README.md
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── cyclic_doubly_list.py
│ ├── cyclic_list.py
│ ├── dummy_tail_doubly_list.py
│ ├── dummy_tail_list.py
│ ├── head_tail_doubly_list.py
│ ├── head_tail_list.py
│ ├── linked_list__test.py
│ ├── two_dummy_doubly_list.py
│ └── two_dummy_list.py
├── problem_set/
│ ├── subarray_sum.md
│ └── substring_with_distinct_characters.md
├── range_query/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── binary_indexed_tree.py
│ ├── interval_tree.py
│ ├── prefix_sum.py
│ ├── range_tree.py
│ └── segment_tree.py
├── searching/
│ ├── binary_search.md
│ └── python/
│ ├── __init__.py
│ └── _helper.py
├── sorting/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── merge_sort.py
│ ├── quick_sort.py
│ └── sorting__test.py
├── system_design/
│ └── latency.md
├── traversal/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── binary_tree_traversal__test.py
│ ├── iterative_traversal.py
│ ├── morris_traversal.py
│ └── recursive_traversal.py
└── tree/
├── binary_tree.md
└── python/
├── __init__.py
├── _helper.py
├── binary_tree.py
├── binary_tree__test.py
├── trie.py
└── trie__test.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_size = 2
indent_style = space
[*.py]
indent_size = 4
[*.{md,markdown}]
indent_size = 4
[Makefile]
indent_style = tab
================================================
FILE: .gitignore
================================================
__pycache__
node_modules
*-lock.json
================================================
FILE: .travis.yml
================================================
matrix:
include:
- language: python
python: "3.6"
script:
- $TRAVIS_BUILD_DIR/bin/test_python.py
- language: node_js
node_js:
- "lts/carbon"
before_script:
- npm install -g jest
script: jest --config=$TRAVIS_BUILD_DIR/bin/test_javascript.js
================================================
FILE: README.md
================================================
Algorithm
======
[](https://travis-ci.org/jaychsu/algorithm)
The challenges for algorithm contests, and summary the implementation.
## Structure
| Top-level Folder | Note |
| :--- | :--- |
| bin | commands |
| topic | implementation and summaries of algorithms and data structures |
| other | for problems met in life |
| codeforces | for [Codeforces](http://codeforces.com) |
| codejam | for [PastContests](https://code.google.com/codejam/past-contests) in [code jam](https://code.google.com/codejam) from Google |
| codelab | for [Code Lab](https://codelab.interviewbit.com) from Facebook |
| codewars | for [Codewars](https://www.codewars.com) |
| geeksforgeeks | for [GeeksforGeeks](https://www.geeksforgeeks.org) |
| hackerrank | for [HackerRank](https://www.hackerrank.com/contests) |
| leetcode | for [LeetCode](https://leetcode.com) |
| lintcode | for [LintCode](http://www.lintcode.com) |
| pramp | for [Pramp](https://www.pramp.com) |
| topcoder | for [ActiveContests](https://community.topcoder.com/longcontest/?module=ViewActiveContests), [Practices](https://community.topcoder.com/longcontest/?module=ViewPractice), and [ProblemArchives](https://community.topcoder.com/tc?module=ProblemArchive) in [Topcoder](https://www.topcoder.com) |
| Scaler | for [Scaler Topics](https://www.scaler.com/topics/) |
| InterviewBit | for [Technical Interview](https://www.interviewbit.com/technical-interview-questions/), [Data Structures and Algorithms](https://www.interviewbit.com/courses/programming/), [Contests](https://www.interviewbit.com/contests/), and [Mock Interviews](https://www.interviewbit.com/mock-interview/) |
## Testing
| Language | Command |
| :--- | :--- |
| Python | [./bin/test_python.py](./bin/test_python.py) |
| Javascript | |
================================================
FILE: bin/test_javascript.js
================================================
// TODO: wrap this file to a executable command
// [Configuring Jest](https://facebook.github.io/jest/docs/en/configuration.html)
module.exports = {
"rootDir": "..",
"testEnvironment": "node",
"testRegex": "/(other|topic)/.*(\\.|/)(test|spec)\\.jsx?$",
"verbose": true,
}
================================================
FILE: bin/test_python.py
================================================
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest
import doctest
sys.path.append(os.path.join(
os.path.dirname(__file__),
'../topic'
))
from _test.python.test_base import TaskTimer
def get_unittests(dirname):
ROOT_DIR = os.path.join(
os.path.dirname(__file__),
'../{dirname}'.format(dirname=dirname)
)
tests = []
for path, _, files in os.walk(ROOT_DIR):
if ('pycache' in path or
'python' not in path or
'__init__.py' not in files):
continue
tests.append(unittest.defaultTestLoader.discover(
path,
pattern='*__test.py',
top_level_dir=ROOT_DIR
))
return tests
def get_doctests(dirname):
ROOT_DIR = os.path.join(
os.path.dirname(__file__),
'../{dirname}'.format(dirname=dirname)
)
tests = []
sys.path.append(ROOT_DIR)
for path, _, files in os.walk(ROOT_DIR):
if 'pycache' in path:
continue
for file in files:
if (file.startswith('_') or
not file.endswith('.py')):
continue
timer = TaskTimer()
tests.append(doctest.DocTestSuite(
file[:-3],
setUp=lambda globs: timer.reset_time(),
tearDown=lambda globs: timer.print_duration()
))
sys.path.pop()
return tests
if __name__ == '__main__':
suite = unittest.TestSuite()
for tests in (
get_unittests('topic'),
get_doctests('leetcode'),
get_doctests('pramp'),
get_doctests('other'),
):
suite.addTests(tests)
unittest.TextTestRunner(verbosity=2).run(suite)
================================================
FILE: codewars/delete_occurrences_of_an_element_if_it_occurs_more_than_n_times.js
================================================
function deleteNth(nums, n) {
const freq = {}
for (let i = 0; i < nums.length; i++) {
const num = nums[i]
if (!freq.hasOwnProperty(num)) {
freq[num] = 0
}
freq[num] += 1
}
for (let i = nums.length - 1; i >= 0; i--) {
const num = nums[i]
if (freq[num] <= n) {
continue
}
nums.splice(i, 1)
freq[num] -= 1
}
return nums
}
================================================
FILE: codewars/double_cola.js
================================================
function whoIsNext(names, r) {
let total = names.length
while (r > total) {
r -= total
total *= 2
}
return names[parseInt(names.length * (r - 1) / total)]
}
================================================
FILE: codewars/iq_test.js
================================================
function iqTest(nums) {
nums = nums.split(' ').map(c => +c & 1)
for (let i = 2; i < nums.length; i++) {
if (nums[0] ^ nums[i] && nums[1] ^ nums[i]) {
return i + 1
} else if (nums[i] ^ nums[0] && nums[1] ^ nums[0]) {
return 1
} else if (nums[0] ^ nums[1] && nums[i] ^ nums[1]) {
return 2
}
}
return -1
}
================================================
FILE: codewars/is_a_number_prime.js
================================================
function isPrime(num) {
if (!num || num <= 1) return false
const factors = [2, 3, 5, 7, 9, 11, 13, 17, 19].filter(base => {
if (num <= base) return false
if (num % base === 0) return true
return false
})
return factors.length === 0
}
================================================
FILE: codewars/multiply.js
================================================
function multiply(a, b) {
return a * b
}
================================================
FILE: codewars/rectangle_into_squares.js
================================================
function sqInRect(lng, wdth) {
if (!lng || !wdth || lng === wdth) return null
const ans = []
while (lng != 1 || wdth != 1) {
if (lng > wdth) {
ans.push(wdth)
lng -= wdth
} else if (lng < wdth) {
ans.push(lng)
wdth -= lng
} else {
ans.push(lng)
break
}
}
if (lng == 1 && wdth == 1) {
ans.push(1)
}
return ans
}
================================================
FILE: codewars/reverse_words.js
================================================
function reverseWords(s) {
return s.split(' ').map(word => {
return word.split('').reverse().join('')
}).join(' ')
}
================================================
FILE: codewars/simple_encryption_1_alternating_split.js
================================================
function encrypt(text, n) {
if (!text || !n || n < 0) return text
const TEXT_SIZE = text.length
while (n--) {
const _text = []
for (let i = 1; i < TEXT_SIZE; i += 2) {
_text.push(text[i])
}
for (let i = 0; i < TEXT_SIZE; i += 2) {
_text.push(text[i])
}
text = _text.join('')
}
return text
}
function decrypt(text, n) {
if (!text || !n || n < 0) return text
const TEXT_SIZE = text.length
const HALF_TEXT_SIZE = parseInt(text.length / 2)
while (n--) {
const _text = []
for (let i = 0; i < HALF_TEXT_SIZE + 1; i++) {
if (HALF_TEXT_SIZE + i < TEXT_SIZE) {
_text.push(text[HALF_TEXT_SIZE + i])
}
if (i < HALF_TEXT_SIZE) {
_text.push(text[i])
}
}
text = _text.join('')
}
return text
}
================================================
FILE: codewars/sudoku_solution_validator.js
================================================
function validSolution(board) {
if ( !Array.isArray(board)
|| !Array.isArray(board[0])
|| board.length !== board[0].length) {
return false
}
const n = board.length
const g = Math.sqrt(n) // group counts
const cnts = new Array(n).fill(0)
let cnt = 0
let i, j, x, y
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
if (board[x][y] <= 0 || board[x][y] > n) return false
if (cnts[board[x][y] - 1] !== cnt) return false
cnts[board[x][y] - 1] += 1
}
cnt += 1
for (y = 0; y < n; y++) {
if (board[y][x] <= 0 || board[y][x] > n) return false
if (cnts[board[y][x] - 1] !== cnt) return false
cnts[board[y][x] - 1] += 1
}
cnt += 1
}
let x_from, x_to, y_from, y_to
for (i = 0; i < g; i++) {
for (j = 0; j < g; j++) {
x_from = i * g
x_to = i * g + g
y_from = j * g
y_to = j * g + g
for (x = x_from; x < x_to; x++) {
for (y = y_from; y < y_to; y++) {
if (cnts[board[x][y] - 1] !== cnt) return false
cnts[board[x][y] - 1] += 1
}
}
cnt += 1
}
}
return true
}
================================================
FILE: codewars/take_a_ten_minute_walk.js
================================================
function isValidWalk(walk) {
if (walk.length != 10) {
return false
}
let dx = 0
let dy = 0
walk.forEach(c => {
switch (c) {
case 'n':
dy++
break
case 's':
dy--
break
case 'e':
dx++
break
case 'w':
dx--
break
default:
return false
}
})
return dx === 0 && dy === 0
}
================================================
FILE: codewars/tribonacci_sequence.js
================================================
function tribonacci(signature, n) {
if (!n) return []
const ans = signature.slice()
for (let i = 3; i < n; i++) {
ans.push(ans[i - 3] + ans[i - 2] + ans[i - 1])
}
return ans.slice(0, n)
}
================================================
FILE: codewars/unique_in_order.js
================================================
function uniqueInOrder(iterable) {
if (!iterable) {
return []
}
const ans = [iterable[0]]
for (let i = 1; i < iterable.length; i++) {
if (iterable[i] != ans[ans.length - 1]) {
ans.push(iterable[i])
}
}
return ans
}
================================================
FILE: codewars/who_likes_it.js
================================================
function likes(names) {
if (!Array.isArray(names) || names.length === 0) {
return 'no one likes this'
}
switch (names.length) {
case 1:
return `${names[0]} likes this`
case 2:
return `${names[0]} and ${names[1]} like this`
case 3:
return `${names[0]}, ${names[1]} and ${names[2]} like this`
default:
return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`
}
}
================================================
FILE: leetcode/101_symmetric_tree.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.divide_conquer(root.left, root.right)
def divide_conquer(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
if not self.divide_conquer(left.left, right.right):
return False
if not self.divide_conquer(left.right, right.left):
return False
return True
================================================
FILE: leetcode/105_construct_binary_tree_from_preorder_and_inorder_traversal.py
================================================
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, P, I):
"""
:type P: List[int]
:type I: List[int]
:rtype: TreeNode
"""
if not P or not I:
return
i = I.index(P.pop(0))
node = TreeNode(I[i])
node.left = self.buildTree(P, I[:i])
node.right = self.buildTree(P, I[i + 1:])
return node
================================================
FILE: leetcode/108_convert_sorted_array_to_binary_search_tree.py
================================================
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return
i = len(nums) // 2
node = TreeNode(nums[i])
node.left = self.sortedArrayToBST(nums[:i])
node.right = self.sortedArrayToBST(nums[i + 1:])
return node
================================================
FILE: leetcode/112_path_sum.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
def hasPathSum(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: bool
"""
if not root:
return False
if not root.left and not root.right:
return root.val == target
if root.left and self.hasPathSum(root.left, target - root.val):
return True
if root.right and self.hasPathSum(root.right, target - root.val):
return True
return False
================================================
FILE: leetcode/113_path_sum_ii.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
def pathSum(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: List[List[int]]
"""
ans = []
if not root:
return ans
self.dfs(root, target, ans, [])
return ans
def dfs(self, node, remaining, ans, path):
if not node:
return
path.append(node.val)
if not node.left and not node.right and remaining == node.val:
ans.append(path[:])
else:
self.dfs(node.left, remaining - node.val, ans, path)
self.dfs(node.right, remaining - node.val, ans, path)
path.pop()
================================================
FILE: leetcode/116_populating_next_right_pointers_in_each_node.py
================================================
"""
Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
"""
class Solution:
"""
Recursion
"""
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: void
"""
if not root:
return
if root.left:
root.left.next = root.right
if root.right and root.next:
root.right.next = root.next.left
# leave to None if root.right: root.right.next = None
self.connect(root.left)
self.connect(root.right)
class Solution:
"""
Iteration
"""
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: void
"""
if not root:
return
head = root
nxt = None
# this loop only for find left
while head:
nxt = head
head = nxt.left
# this loop find for every next, do level move
while nxt:
if nxt.left:
nxt.left.next = nxt.right
if nxt.right and nxt.next:
nxt.right.next = nxt.next.left
nxt = nxt.next
================================================
FILE: leetcode/117_populating_next_right_pointers_in_each_node_ii.py
================================================
"""
Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
"""
class Solution:
"""
Recursion
1. recursion from right to left
2. first scan the nxt by level
"""
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: void
"""
if not root:
return
# scan the nxt by level
head = root.next
nxt = None
while head and not nxt:
if head.left:
nxt = head.left
elif head.right:
nxt = head.right
else:
head = head.next
if root.right:
root.right.next = nxt
nxt = root.right
if root.left:
root.left.next = nxt
self.connect(root.right)
self.connect(root.left)
class Solution:
"""
Iteration
"""
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: void
"""
if not root:
return
dummy = TreeLinkNode(0)
dummy.next = root
nxt = tail = None
while dummy.next:
tail = dummy
nxt = dummy.next
dummy.next = None
while nxt:
if nxt.left:
tail.next = nxt.left
tail = tail.next
if nxt.right:
tail.next = nxt.right
tail = tail.next
nxt = nxt.next
class Solution:
"""
Level Traversal
"""
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: void
"""
if not root:
return
queue, _queue = [root], []
while queue:
n = len(queue)
for i in range(n):
if i < n - 1:
queue[i].next = queue[i + 1]
if queue[i].left:
_queue.append(queue[i].left)
if queue[i].right:
_queue.append(queue[i].right)
queue, _queue = _queue, []
================================================
FILE: leetcode/118_pascal_s_triangle.py
================================================
class Solution:
def generate(self, num_rows):
"""
:type num_rows: int
:rtype: List[List[int]]
"""
ans = []
if not num_rows:
return ans
ans.append([1])
for i in range(1, num_rows):
path = [ans[i - 1][0]]
for j in range(1, len(ans[i - 1])):
path.append(ans[i - 1][j] + ans[i - 1][j - 1])
path.append(ans[i - 1][-1])
ans.append(path)
return ans
class Solution:
def generate(self, num_rows):
"""
:type num_rows: int
:rtype: List[List[int]]
"""
ans = []
if not num_rows:
return ans
ans.append([1])
for i in range(1, num_rows):
ans.append([
(ans[i - 1] + [0])[j] + ([0] + ans[i - 1])[j]
for j in range(len(ans[i - 1]) + 1)
])
return ans
================================================
FILE: leetcode/11_container_with_most_water.py
================================================
class Solution:
def maxArea(self, H):
"""
:type H: List[int]
:rtype: int
"""
ans = 0
if not H:
return ans
left, right = 0, len(H) - 1
while left < right:
area = min(H[left], H[right]) * (right - left)
if area > ans:
ans = area
if H[left] < H[right]:
left += 1
else:
right -= 1
return ans
================================================
FILE: leetcode/124_binary_tree_maximum_path_sum.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
ans, _ = self.divide_conquer(root)
return ans
def divide_conquer(self, node):
if not node:
return float('-inf'), 0
max_left, left = self.divide_conquer(node.left)
max_right, right = self.divide_conquer(node.right)
# 0 means discard the negative path
res = max(max_left, max_right, node.val + left + right)
path = max(node.val + left, node.val + right, 0)
return res, path
class Solution:
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.ans = float('-inf')
self.divide_conquer(root)
return self.ans
def divide_conquer(self, node):
if not node:
return 0
left = max(0, self.divide_conquer(node.left))
right = max(0, self.divide_conquer(node.right))
if node.val + left + right > self.ans:
self.ans = node.val + left + right
return node.val + max(left, right)
================================================
FILE: leetcode/134_gas_station.py
================================================
class Solution:
"""
Main Concept:
if the tank is enough, go to next, otherwise back to previous to get gas
"""
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
NOT_FOUND = -1
if not gas or not cost or len(gas) != len(cost):
return NOT_FOUND
end, start = -1, len(gas) - 1 # since its a circle, end start from `-1` means `n - 1`
tank = gas[start] - cost[start]
while start > end:
if tank >= 0:
end += 1
tank += gas[end] - cost[end]
else:
start -= 1
tank += gas[start] - cost[start]
return start if tank >= 0 else NOT_FOUND
class Solution:
"""
TLE: Simulate the process
"""
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
NOT_FOUND = -1
if not gas or not cost or len(gas) != len(cost):
return NOT_FOUND
n = len(gas)
RANGE = list(range(n))
for start in range(n):
tank = 0
is_failed = False
for mid in RANGE[start:n] + RANGE[:start]:
tank += gas[mid]
if tank < cost[mid]:
is_failed = True
break
tank -= cost[mid]
if not is_failed:
return start
return NOT_FOUND
================================================
FILE: leetcode/136_single_number.py
================================================
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
for num in nums:
ans ^= num
return ans
================================================
FILE: leetcode/149_max_points_on_a_line.py
================================================
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
def maxPoints(self, P):
"""
:type P: List[Point]
:rtype: int
"""
ans = 0
if not P:
return ans
n = len(P)
if n <= 2:
return n
for i in range(n):
S = {}
points = dups = 0
for j in range(i + 1, n):
dx = P[i].x - P[j].x
dy = P[i].y - P[j].y
if dx == 0 and dy == 0:
dups += 1
continue
gcd = self.get_gcd(dx, dy)
if gcd:
dx //= gcd
dy //= gcd
key = (dx, dy)
S[key] = S.get(key, 0) + 1
if S[key] > points:
points = S[key]
if points + dups + 1 > ans:
ans = points + dups + 1
return ans
def get_gcd(self, a, b):
if b == 0:
return a
return self.get_gcd(b, a % b)
================================================
FILE: leetcode/14_longest_common_prefix.py
================================================
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs or not strs[0]:
return ''
t = strs[0]
for i in range(len(t)):
for s in strs:
if i >= len(s) or s[i] != t[i]:
return t[:i]
return t
================================================
FILE: leetcode/150_evaluate_reverse_polish_notation.py
================================================
class Solution:
def evalRPN(self, E):
"""
:type E: List[str]
:rtype: int
"""
if not E:
return 0
stack = []
operation = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
}
for char in E:
if char not in operation:
stack.append(int(char))
continue
b = stack.pop()
a = stack.pop()
stack.append(int(operation[char](a, b)))
return stack[0]
================================================
FILE: leetcode/157_read_n_characters_given_read4.py
================================================
"""
The read4 API is already defined for you.
@param buf, a list of characters
@return an integer
def read4(buf):
pass
"""
class Solution:
def read(self, buf, n):
"""
:type buf: List[str], Destination buffer
:type n: int, Maximum number of characters to read
:rtype: int, The number of characters read
"""
if not buf or n <= 0:
return 0
i = 0
k = 4
tmp = [0] * k
while i < n and k == 4:
k = read4(tmp)
j = 0
while i < n and j < k:
buf[j] = tmp[j]
i += 1
j += 1
return i
if __name__ == '__main__':
data = 'abcdferrdsjfklsdjfdsr'
n = len(data)
i = 0
k = 4
def read4(buf):
global i
j = 0
while i < n and j < k:
buf[j] = data[i]
i += 1
j += 1
return j
s = Solution()
res = s.read([0] * 4, 4)
print(res)
================================================
FILE: leetcode/160_intersection_of_two_linked_lists.py
================================================
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, A, B):
"""
:type A, B: ListNode
:rtype: ListNode
"""
if not A or not B:
return
X, Y = A, B
while X and Y:
X = X.next
Y = Y.next
while X:
X = X.next
A = A.next
while Y:
Y = Y.next
B = B.next
while A is not B:
A = A.next
B = B.next
return A
================================================
FILE: leetcode/165_compare_version_numbers.py
================================================
class Solution:
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
if not version1 and not version2:
return 0
if not version1:
return -1
if not version2:
return 1
v = version1.split('.')
w = version2.split('.')
m, n = len(v), len(w)
for i in range(max(m, n)):
a = self.get_int(v[i]) if i < m else 0
b = self.get_int(w[i]) if i < n else 0
if a < b:
return -1
elif a > b:
return 1
return 0
def get_int(self, s):
if not s or not s.isdigit():
return 0
res = 0
zero = ord('0')
for c in s:
res = res * 10 + ord(c) - zero
return res
================================================
FILE: leetcode/166_fraction_to_recurring_decimal.py
================================================
class Solution:
def fractionToDecimal(self, a, b):
"""
:type a: int
:type b: int
:rtype: str
"""
if not b:
return ''
if not a:
return '0'
ans = []
if a ^ b < 0:
ans.append('-')
if a < 0:
a = -a
if b < 0:
b = -b
ans.append(str(a // b))
a %= b
if a == 0:
return ''.join(ans)
ans.append('.')
D = {a: len(ans)} # the index of first occurrence of `a`
while a:
a *= 10
ans.append(str(a // b))
a %= b
if a in D:
ans.insert(D[a], '(')
ans.append(')')
break
D[a] = len(ans)
return ''.join(ans)
================================================
FILE: leetcode/169_majority_element.py
================================================
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
ans = None
cnt = 0
for num in nums:
if cnt == 0:
ans, cnt = num, 1
elif ans == num:
cnt += 1
else:
cnt -= 1
return ans
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums.sort()
return nums[len(nums) // 2]
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
NOT_FOUND = 0
if not nums:
return NOT_FOUND
freq = {}
for a in nums:
freq[a] = freq.get(a, 0) + 1
for a, cnt in freq.items():
if cnt > len(nums) // 2:
return a
return NOT_FOUND
================================================
FILE: leetcode/171_excel_sheet_column_number.py
================================================
class Solution:
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = s.upper()
ans = 0
BASE = ord('A') - 1
for char in s:
ans = ans * 26 + ord(char) - BASE
return ans
================================================
FILE: leetcode/172_factorial_trailing_zeroes.py
================================================
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
ans = 0
if not n:
return ans
i = 5
while n // i > 0:
ans += n // i
i *= 5
return ans
================================================
FILE: leetcode/174_dungeon_game.py
================================================
class Solution:
def calculateMinimumHP(self, G):
"""
:type G: List[List[int]]
:rtype: int
"""
INFINITY = float('inf')
m, n = len(G), len(G[0])
dp = [[INFINITY] * (n + 1) for _ in range(m + 1)]
dp[m][n - 1] = 1
dp[m - 1][n] = 1
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - G[i][j]
if dp[i][j] <= 0:
dp[i][j] = 1
return dp[0][0]
================================================
FILE: leetcode/179_largest_number.py
================================================
"""
REF: https://leetcode.com/articles/largest-number/
"""
class LgSort(str):
def __lt__(a, b):
return a + b > b + a
class Solution:
def largestNumber(self, A):
"""
:type A: List[int]
:rtype: str
"""
A = ''.join(sorted(map(str, A), key=LgSort))
return '0' if A[0] == '0' else A
================================================
FILE: leetcode/17_letter_combinations_of_a_phone_number.py
================================================
class Solution:
def letterCombinations(self, s):
"""
:type s: str
:rtype: List[str]
"""
if not s:
return []
L = {
'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz',
}
queue, _queue = [], []
for d in s:
if d not in L:
return []
if not queue:
queue.extend(list(L[d]))
continue
for c in L[d]:
for _c in queue:
_queue.append(_c + c)
queue, _queue = _queue, []
queue.sort()
return queue
================================================
FILE: leetcode/190_reverse_bits.py
================================================
# Reverse bit every 4 bits
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
if not n:
return 0
# the reversed bins for i = 0 -> 15
rev = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
ans = 0
msk = 15 # 15 (10) == 1111 (2)
for i in range(8):
ans <<= 4
curr = n & msk
ans |= rev[curr]
n >>= 4
return ans
# Reverse bit every 1 bits
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
ans = 0
if not n:
return ans
for i in range(32):
ans <<= 1
ans |= n & 1
n >>= 1
return ans
================================================
FILE: leetcode/191_number_of_1_bits.py
================================================
class Solution:
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ans = 0
if not n:
return ans
while n != 0:
n = n & (n - 1)
ans += 1
return ans
================================================
FILE: leetcode/19_remove_nth_node_from_end_of_list.py
================================================
"""
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head or not n:
return head
dummy = slow = ListNode(0)
dummy.next = fast = head
while fast and n:
n -= 1
fast = fast.next
while slow and fast:
slow = slow.next
fast = fast.next
if slow and slow.next:
slow.next = slow.next.next
return dummy.next
================================================
FILE: leetcode/202_happy_number.py
================================================
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
slow = self.square_sum(n)
fast = self.square_sum(slow)
while slow != fast:
slow = self.square_sum(slow)
fast = self.square_sum(
self.square_sum(fast)
)
return True if slow == 1 else False
def square_sum(self, a):
res = b = 0
while a != 0:
b = a % 10
res += b * b
a //= 10
return res
================================================
FILE: leetcode/204_count_primes.py
================================================
"""
REF: https://discuss.leetcode.com/topic/14036/fast-python-solution
Count the number of prime numbers LESS THAN a non-negative number, n.
"""
class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
# note that 2 is prime
# but there is no prime less than 2
# so return 0 if n == 2
if not n or n < 3:
return 0
is_prime = [True] * n
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if not is_prime[i]:
continue
for j in range(i * i, n, i):
is_prime[j] = False
return sum(is_prime)
================================================
FILE: leetcode/208_implement_trie_prefix_tree.py
================================================
class TrieNode:
def __init__(self, val=None):
self.end_at = val
self.children = {}
class Trie:
def __init__(self):
self.trie = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
if not word:
return
node = self.trie
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.end_at = word
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
if not word:
return False
node = self.trie
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.end_at == word
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
if not prefix:
return False
node = self.trie
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
================================================
FILE: leetcode/20_valid_parentheses.py
================================================
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for c in s:
if c in '([{':
stack.append(c)
elif c not in ')]}':
return False
elif not stack or pairs[c] != stack.pop():
return False
return not stack
================================================
FILE: leetcode/215_kth_largest_element_in_an_array.py
================================================
from heapq import heappop, heappush
class Solution:
def findKthLargest(self, A, k):
"""
:type A: List[int]
:type k: int
:rtype: int
"""
heap = []
for a in A:
heappush(heap, a)
if len(heap) > k:
heappop(heap)
return heappop(heap)
================================================
FILE: leetcode/217_contains_duplicate.py
================================================
class Solution:
def containsDuplicate(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if not A:
return False
S = set()
for a in A:
if a in S:
return True
S.add(a)
return False
================================================
FILE: leetcode/218_the_skyline_problem.py
================================================
"""
REF: https://briangordon.github.io/2014/08/the-skyline-problem.html
"""
import heapq
class HashHeapq:
def __init__(self):
self.heap = []
self.deleted = {}
def push(self, val):
heapq.heappush(self.heap, val)
def pop(self):
if self.is_empty():
return -1
return heapq.heappop(self.heap)
def remove(self, val):
if self.is_empty():
return
if val not in self.deleted:
self.deleted[val] = 0
self.deleted[val] += 1
def top(self):
if self.is_empty():
return -1
return self.heap[0]
def is_empty(self):
while self.heap and self.deleted.get(self.heap[0]):
val = heapq.heappop(self.heap)
self.deleted[val] -= 1
return not self.heap
class Solution:
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
ans = []
if not buildings:
return ans
time = []
for x, _x, height in buildings:
time.append((x, height, True))
time.append((_x, height, False))
time.sort()
heap = HashHeapq()
for x, height, is_start in time:
if is_start:
heap.push(-height)
else:
heap.remove(-height)
max_h = -heap.top() if not heap.is_empty() else 0
if ans and ans[-1][0] == x:
ans.pop()
if ans and ans[-1][1] == max_h:
continue
ans.append([x, max_h])
return ans
================================================
FILE: leetcode/224_basic_calculator.py
================================================
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
self.OP = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
}
s = self.to_rpn(s)
if not s:
return 0
return self.eval_rpn(s)
def to_rpn(self, s):
stack, res = [], []
for i in range(len(s)):
char = s[i]
if i > 0 and s[i - 1].isdigit() and char.isdigit():
res[-1] += char
elif char.isdigit():
res.append(char)
elif char in self.OP:
while stack and stack[-1] in self.OP:
res.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
while stack:
res.append(stack.pop())
return res
def eval_rpn(self, s):
stack = []
for char in s:
if char.isdigit():
stack.append(int(char))
elif char in self.OP:
b = stack.pop()
a = stack.pop()
stack.append(self.OP[char](a, b))
return stack[0]
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = self.to_rpn(s)
if not s:
return 0
return self.eval_rpn(s)
def to_rpn(self, s):
stack, res = [], []
for i in range(len(s)):
char = s[i]
if i > 0 and s[i - 1].isdigit() and char.isdigit():
res[-1] += char
elif char.isdigit():
res.append(char)
elif char in '+-':
while stack and stack[-1] in '+-':
res.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
while stack:
res.append(stack.pop())
return res
def eval_rpn(self, s):
stack = []
for char in s:
if char.isdigit():
stack.append(int(char))
elif char in '+-':
b = stack.pop()
a = stack.pop()
if char == '+':
stack.append(a + b)
elif char == '-':
stack.append(a - b)
return stack[0]
================================================
FILE: leetcode/227_basic_calculator_ii.py
================================================
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = self.to_rpn(s, {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
})
if not s:
return 0
return self.eval_rpn(s, {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a // b,
})
def to_rpn(self, s, P):
stack, res = [], []
for i in range(len(s)):
char = s[i]
if i > 0 and s[i - 1].isdigit() and char.isdigit():
res[-1] += char
elif char.isdigit():
res.append(char)
elif char in P:
while stack and stack[-1] in P and P[char] <= P[stack[-1]]:
res.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
while stack:
res.append(stack.pop())
return res
def eval_rpn(self, s, OP):
stack = []
for char in s:
if char.isdigit():
stack.append(int(char))
elif char in OP:
b = stack.pop()
a = stack.pop()
stack.append(OP[char](a, b))
return stack[0]
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = self.to_rpn(s)
if not s:
return 0
return self.eval_rpn(s)
def to_rpn(self, s):
stack, res = [], []
for i in range(len(s)):
char = s[i]
if i > 0 and s[i - 1].isdigit() and char.isdigit():
res[-1] += char
elif char.isdigit():
res.append(char)
elif char in '+-*/':
while stack and stack[-1] in '+-*/':
if char in '*/' and stack[-1] in '+-':
break
res.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
while stack:
res.append(stack.pop())
return res
def eval_rpn(self, s):
stack = []
for char in s:
if char.isdigit():
stack.append(int(char))
elif char in '+-*/':
b = stack.pop()
a = stack.pop()
if char == '+':
stack.append(a + b)
elif char == '-':
stack.append(a - b)
elif char == '*':
stack.append(a * b)
elif char == '/':
stack.append(a // b)
return stack[0]
================================================
FILE: leetcode/229_majority_element_ii.py
================================================
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
if not nums:
return []
a1 = a2 = None
c1 = c2 = 0
for num in nums:
if a1 == num:
c1 += 1
elif a2 == num:
c2 += 1
elif c1 == 0:
a1, c1 = num, 1
elif c2 == 0:
a2, c2 = num, 1
else:
c1 -= 1
c2 -= 1
c1 = c2 = 0
for num in nums:
if num == a1:
c1 += 1
elif num == a2:
c2 += 1
for a, c in ((a1, c1), (a2, c2)):
if c > len(nums) // 3:
ans.append(a)
return ans
================================================
FILE: leetcode/22_generate_parentheses.py
================================================
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: list[str]
"""
ans = []
if not n:
return ans
self.dfs(n, 1, 0, ans, ['('])
return ans
def dfs(self, n, lcnt, rcnt, ans, path):
if len(path) == 2 * n:
ans.append(''.join(path))
return
if rcnt < lcnt:
path.append(')')
self.dfs(n, lcnt, rcnt + 1, ans, path)
path.pop()
if lcnt < n:
path.append('(')
self.dfs(n, lcnt + 1, rcnt, ans, path)
path.pop()
================================================
FILE: leetcode/230_kth_smallest_element_in_a_bst.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
k -= 1
if k == 0:
return node.val
node = node.right
================================================
FILE: leetcode/234_palindrome_linked_list.py
================================================
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
rev = None
slow = fast = head
while fast and fast.next:
fast = fast.next.next
rev, rev.next, slow = slow, rev, slow.next
if fast:
slow = slow.next
while slow and slow.val == rev.val:
slow = slow.next
rev = rev.next
return not rev
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
rev = nxt = None
slow = fast = head
while fast and fast.next:
fast = fast.next.next
nxt = slow.next
slow.next = rev
rev = slow
slow = nxt
if fast:
slow = slow.next
while slow and slow.val == rev.val:
slow = slow.next
rev = rev.next
return not rev
================================================
FILE: leetcode/235_lowest_common_ancestor_of_a_binary_search_tree.py
================================================
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while root:
if root.val > p.val and root.val > q.val:
root = root.left
elif root.val < p.val and root.val < q.val:
root = root.right
else:
return root
================================================
FILE: leetcode/236_lowest_common_ancestor_of_a_binary_tree.py
================================================
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
if left:
return left
if right:
return right
================================================
FILE: leetcode/237_delete_node_in_a_linked_list.py
================================================
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
if not node or not node.next:
return
node.val = node.next.val
node.next = node.next.next
================================================
FILE: leetcode/242_valid_anagram.py
================================================
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if s == t:
return True
if not s or not t or len(s) != len(t):
return False
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
for c in t:
if c not in freq:
return False
freq[c] -= 1
return all(v == 0 for v in freq.values())
================================================
FILE: leetcode/269_alien_dictionary.py
================================================
class Solution:
def alienOrder(self, words):
"""
:type words: list[str]
:rtype: str
"""
if not words:
return ''
ans = []
gotcha = set()
max_size = max(len(word) for word in words)
for j in range(max_size):
for word in words:
if j >= len(word):
continue
if word[j] in gotcha:
continue
ans.append(word[j])
gotcha.add(word[j])
return ''.join(ans)
class Solution:
"""
REF: https://discuss.leetcode.com/topic/28308/java-ac-solution-using-bfs/2
"""
def alienOrder(self, words):
if not words:
return ''
ans = []
edges = {}
indeg = {}
for w in words:
for c in w:
indeg[c] = 0
for i in range(len(words) - 1):
cur = words[i]
nxt = words[i + 1]
for j in range(min(len(cur), len(nxt))):
if cur[j] == nxt[j]:
continue
if cur[j] not in edges:
edges[cur[j]] = set()
if nxt[j] not in edges[cur[j]]:
edges[cur[j]].add(nxt[j])
indeg[nxt[j]] = indeg.get(nxt[j], 0) + 1
break
queue = [c for c, deg in indeg.items() if deg == 0]
for c in queue:
ans.append(c)
if c not in edges:
continue
for _c in edges[c]:
indeg[_c] -= 1
if indeg[_c] == 0:
queue.append(_c)
return ''.join(ans) if len(ans) == len(indeg) else ''
================================================
FILE: leetcode/277_find_the_celebrity.py
================================================
"""
REF: https://discuss.leetcode.com/topic/25720/java-python-o-n-calls-o-1-space-easy-to-understand-solution
"""
class Solution:
def findCelebrity(self, n):
if not n:
return -1
x = 0
for i in range(n):
if knows(x, i):
x = i
for i in range(x):
if knows(x, i):
return -1
for i in range(n):
if not knows(i, x):
return -1
return x
================================================
FILE: leetcode/280_wiggle_sort.py
================================================
class Solution:
def wiggleSort(self, nums):
"""
:type nums: list[int]
:rtype: void, Do not return anything, modify A in-place instead.
"""
if not nums:
return
for i in range(1, len(nums)):
if i & 1 == 1 and nums[i] >= nums[i - 1]:
continue
if i & 1 == 0 and nums[i] <= nums[i - 1]:
continue
nums[i], nums[i - 1] = nums[i - 1], nums[i]
================================================
FILE: leetcode/282_expression_add_operators.py
================================================
"""
Main Concept:
in product case, needs to remove product in last recursion, and adds the product in current.
"""
class Solution:
def addOperators(self, s, target):
"""
:type s: str
:type target: int
:rtype: List[str]
"""
ans = []
if not s:
return ans
self.dfs(s, 0, target, 0, 0, ans, [])
return ans
def dfs(self, s, start, target, val, multi, ans, path):
if start == len(s) and target == val:
ans.append(''.join(path))
return
if start >= len(s):
return
for i in range(start, len(s)):
if i > start and s[start] == '0':
# only allow i == start and its `0`
break
sa = s[start:i + 1]
a = int(sa)
if start == 0:
self.dfs(s, i + 1, target, a, a, ans, [sa])
continue
self.dfs(s, i + 1, target, val + a, a, ans, path + ['+', sa])
self.dfs(s, i + 1, target, val - a, -a, ans, path + ['-', sa])
self.dfs(s, i + 1, target, val - multi + multi * a, multi * a, ans, path + ['*', sa])
================================================
FILE: leetcode/285_inorder_successor_in_bst.py
================================================
"""
Definition for a binary tree node.
>>> class TreeNode:
... def __init__(self, x):
... self.val = x
... self.left = None
... self.right = None
... self.parent = None
>>> trees = []
>>> tree_infos = [
... ((
... (1, None, None, 2),
... (2, 1, None, None),
... ), '1,2'),
... ((
... (20, None, 8, 22),
... (8, 20, 4, 12),
... (22, 20, None, None),
... (4, 8, None, None),
... (12, 8, 10, 14),
... (10, 12, None, None),
... (14, 12, None, None),
... ), '4,8,10,12,14,20,22'),
... ((
... (10, None, 5, 100),
... (5, 10, None, None),
... (100, 10, 80, 120),
... (80, 100, None, None),
... (120, 100, None, None),
... ), '5,10,80,100,120'),
... ((
... (1, None, None, 2),
... (2, 1, None, 3),
... (3, 2, None, 4),
... (4, 3, None, 5),
... (5, 4, None, 6),
... (6, 5, None, 7),
... (7, 6, None, None),
... ), '1,2,3,4,5,6,7'),
... ]
>>> for info, _ in tree_infos:
... nodes = {node[0]: TreeNode(node[0]) for node in info}
...
... for val, parent, left, right in info:
... if parent:
... nodes[val].parent = nodes[parent]
... if left:
... nodes[val].left = nodes[left]
... if right:
... nodes[val].right = nodes[right]
...
... trees.append(nodes[info[0][0]])
>>> gotcha = []
>>> for _in, _out in (
... ((trees[0], trees[0]), trees[0].right),
... ((trees[1], trees[1].left.right.right), trees[1]),
... ):
... for s in (Solution(), Solution2(), Solution3(), Solution4()):
... res = s.inorderSuccessor(*_in)
... if res is not _out: print(_in[0].val, res.val)
... gotcha.append(res is _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class Solution:
"""
time: O(log n) or O(h), `n` is the number of nodes and `h` is the tree height
1. if `target` has right child, then successor lies at the most-left child in right child of `target`
2. otherwise, just traverse down from root, and record `ans` when every time go left
"""
def inorderSuccessor(self, root, target):
"""
:type root: TreeNode
:type target: TreeNode
:rtype: TreeNode
"""
if not root or not target:
return
ans = None
if target.right:
ans = target.right
while ans and ans.left:
ans = ans.left
return ans
while root and target.val != root.val:
if target.val < root.val:
ans = root
root = root.left
else:
root = root.right
return ans
class Solution2:
"""
time: O(n), `n` is the number of nodes
just do inorder traverse
"""
def inorderSuccessor(self, root, target):
"""
:type root: TreeNode
:type target: TreeNode
:rtype: TreeNode
"""
if not root or not target:
return
stack = []
node = root
got_target = False
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if got_target:
return node
if node.val == target.val:
got_target = True
node = node.right
class Solution3:
"""
* every node has `parent` pointer
time: O(log n) or O(h), `n` is the number of nodes and `h` is the tree height
1. if `target` has right child, then successor lies at the most-left child in right child of `target`
2. otherwise, just traverse top to root
"""
def inorderSuccessor(self, root, target):
"""
:type root: TreeNode
:type target: TreeNode
:rtype: TreeNode
"""
if not root or not target:
return
ans = None
if target.right:
ans = target.right
while ans and ans.left:
ans = ans.left
return ans
ans = target.parent
while ans and target is ans.right:
target = ans
ans = ans.parent
return ans
class Solution4:
"""
* every node has `parent` pointer
time: O(log n) or O(h), `n` is the number of nodes and `h` is the tree height
1. if `target` has right child, then successor lies at the most-left child in right child of `target`
2. otherwise, just traverse top to root
"""
def inorderSuccessor(self, root, target):
"""
:type root: TreeNode
:type target: TreeNode
:rtype: TreeNode
"""
if not root or not target:
return
if target.right:
ans = target.right
while ans and ans.left:
ans = ans.left
return ans
ans = target.parent
while ans and ans.val < target.val:
ans = ans.parent
return ans
================================================
FILE: leetcode/288_unique_word_abbreviation.py
================================================
"""
Your ValidWordAbbr object will be instantiated and called as such:
vwa = ValidWordAbbr(dictionary)
vwa.isUnique("word")
vwa.isUnique("anotherWord")
Testing:
>>> s = ValidWordAbbr(['deer', 'door', 'cake', 'card'])
>>> all((
... s.isUnique('dear') is False,
... s.isUnique('cart') is True,
... s.isUnique('cane') is False,
... s.isUnique('make') is True,
... ))
True
"""
class ValidWordAbbr:
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.abbrs = {}
for word in dictionary:
abbr = self.abbreviation(word)
self.abbrs[abbr] = word
def isUnique(self, word):
"""
check if a word is unique.
:type word: str
:rtype: bool
"""
abbr = self.abbreviation(word)
return abbr not in self.abbrs
def abbreviation(self, word):
if len(word) < 3:
return word
cnt = len(word) - 2
return '{}{}{}'.format(
word[0],
str(cnt),
word[-1]
)
================================================
FILE: leetcode/289_game_of_life.py
================================================
"""
REF: https://leetcode.com/problems/game-of-life/discuss/73223
lives < 2 => 1 -> 0
lives == 2 or 3 => 1 -> 1
lives > 3 => 1 -> 0
lives == 3 => 0 -> 1
"""
class Solution:
"""
Use bits to save the status in next round
"""
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
m, n = len(board), len(board[0])
for x in range(m):
for y in range(n):
lives = self.get_live_neibs(board, x, y)
if board[x][y] == 1 and lives in (2, 3):
board[x][y] = 3
elif board[x][y] == 0 and lives == 3:
board[x][y] = 2
for x in range(m):
for y in range(n):
board[x][y] >>= 1
def get_live_neibs(self, board, x, y):
cnt = 0
m, n = len(board), len(board[0])
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
continue
_x = x + dx
_y = y + dy
if not (0 <= _x < m and 0 <= _y < n):
continue
cnt += board[_x][_y] & 1
return cnt
class Solution:
"""
Not in-place solution
"""
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
m, n = len(board), len(board[0])
ans = [[0] * n for _ in range(m)]
for x in range(m):
for y in range(n):
lives = self.get_live_neibs(board, x, y)
ans[x][y] = board[x][y]
if board[x][y] == 1 and lives < 2:
ans[x][y] = 0
elif board[x][y] == 1 and lives in (2, 3):
ans[x][y] = 1
elif board[x][y] == 1 and lives > 3:
ans[x][y] = 0
elif board[x][y] == 0 and lives == 3:
ans[x][y] = 1
# return ans
# hacking for in-place
for x in range(m):
board[x][:] = ans[x][:]
def get_live_neibs(self, board, x, y):
cnt = 0
m, n = len(board), len(board[0])
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
continue
_x = x + dx
_y = y + dy
if not (
0 <= _x < m and
0 <= _y < n and
board[_x][_y] == 1
):
continue
cnt += 1
return cnt
================================================
FILE: leetcode/295_find_median_from_data_stream.py
================================================
"""
Your MedianFinder object will be instantiated and called as such:
obj = MedianFinder()
obj.addNum(num)
param_2 = obj.findMedian()
"""
import heapq
class MedianFinder:
def __init__(self):
self.minheap = []
self.maxheap = []
def addNum(self, num):
"""
:type num: int
:rtype: void
"""
if self.minheap and num < self.minheap[0]:
heapq.heappush(self.maxheap, -num)
else:
heapq.heappush(self.minheap, num)
def findMedian(self):
"""
:rtype: float
"""
if not self.minheap:
return 0.0
# to handle odd case, it make sure `minheap` has one more child than `maxheap`
while len(self.minheap) > len(self.maxheap) + 1:
heapq.heappush(self.maxheap, - heapq.heappop(self.minheap))
# to handle even case, it make sure `minheap` and `maxheap` are same size
while len(self.maxheap) > len(self.minheap):
heapq.heappush(self.minheap, - heapq.heappop(self.maxheap))
if len(self.minheap) > len(self.maxheap):
return self.minheap[0] * 1.0
# since the child in maxheap is negative
return (self.minheap[0] - self.maxheap[0]) / 2.0
================================================
FILE: leetcode/299_bulls_and_cows.py
================================================
class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
if not secret or not guess or len(secret) != len(guess):
return ''
TMPL = '{}A{}B'
bulls = 0
cows = 0
cnts = [0] * 10
for i in range(len(secret)):
s = ord(secret[i]) - ord('0')
g = ord(guess[i]) - ord('0')
if s == g:
bulls += 1
continue
cnts[s] += 1
cnts[g] -= 1
if cnts[s] <= 0:
cows += 1
if cnts[g] >= 0:
cows += 1
return TMPL.format(bulls, cows)
class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
if not secret or not guess or len(secret) != len(guess):
return ''
TMPL = '{}A{}B'
bulls = 0
cows = 0
cnt_s = [0] * 10
cnt_g = [0] * 10
for i in range(len(secret)):
if secret[i] == guess[i]:
bulls += 1
else:
cnt_s[int(secret[i])] += 1
cnt_g[int(guess[i])] += 1
for i in range(10):
cows += min(cnt_s[i], cnt_g[i])
return TMPL.format(bulls, cows)
================================================
FILE: leetcode/303_range_sum_query_immutable.py
================================================
"""
Your NumArray object will be instantiated and called as such:
obj = NumArray(nums)
param_1 = obj.sumRange(i,j)
"""
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
"""
if not nums:
return
n = len(nums)
self.prefix_sum = [0] * (n + 1)
for i in range(1, n + 1):
self.prefix_sum[i] = self.prefix_sum[i - 1] + nums[i - 1]
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
if (
not self.prefix_sum or
i < 0 or
j + 1 >= len(self.prefix_sum)
):
return 0
return self.prefix_sum[j + 1] - self.prefix_sum[i]
================================================
FILE: leetcode/304_range_sum_query_2d_immutable.py
================================================
"""
Your NumMatrix object will be instantiated and called as such:
obj = NumMatrix(matrix)
param_1 = obj.sumRegion(x1, y1, x2, y2)
"""
class NumMatrix:
def __init__(self, matrix):
"""
:type matrix: List[List[int]]
"""
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
self.prefix_sum = [[0] * (n + 1) for _ in range(m + 1)]
for x in range(1, m + 1):
for y in range(1, n + 1):
self.prefix_sum[x][y] = sum((
self.prefix_sum[x - 1][y],
self.prefix_sum[x][y - 1],
- self.prefix_sum[x - 1][y - 1],
matrix[x - 1][y - 1],
))
def sumRegion(self, x1, y1, x2, y2):
"""
:type x1: int
:type y1: int
:type x2: int
:type y2: int
:rtype: int
"""
if not all((
self.prefix_sum,
self.prefix_sum[0],
0 <= x1 < len(self.prefix_sum),
0 <= x2 + 1 < len(self.prefix_sum),
0 <= y1 < len(self.prefix_sum[0]),
0 <= y2 + 1 < len(self.prefix_sum[0]),
)):
return 0
return sum((
self.prefix_sum[x2 + 1][y2 + 1],
- self.prefix_sum[x2 + 1][y1],
- self.prefix_sum[x1][y2 + 1],
self.prefix_sum[x1][y1],
))
================================================
FILE: leetcode/307_range_sum_query_mutable.py
================================================
"""
REF: https://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was-it-thought-a
REF: http://www.cnblogs.com/grandyang/p/4985506.html
Your NumArray object will be instantiated and called as such:
obj = NumArray(nums)
obj.update(i,val)
param_2 = obj.sumRange(i,j)
"""
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
"""
if not nums:
return
n = len(nums)
self.bits = [0] * (n + 1) # bits
self.incr = [0] * (n + 1) # increments
for i in range(n):
self.update(i, nums[i])
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: void
It must increase `i` here, since this api is public,
so look from outside, the `i` is just the index of `nums`
"""
j = i + 1
delta = val - self.incr[j]
self.incr[j] = val
while j < len(self.incr):
self.bits[j] += delta
j += (j & -j)
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.sum(j + 1) - self.sum(i)
def sum(self, i):
res = 0
j = i
while j > 0:
res += self.bits[j]
j -= (j & -j)
return res
================================================
FILE: leetcode/308_range_sum_query_2d_mutable.py
================================================
"""
Your NumMatrix object will be instantiated and called as such:
obj = NumMatrix(matrix)
obj.update(x,y,val)
param_1 = obj.sumRegion(x1,y1,x2,y2)
"""
class NumMatrix:
def __init__(self, matrix):
"""
:type matrix: List[List[int]]
"""
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
self.bits = [[0] * (n + 1) for _ in range(m + 1)] # bits
self.incr = [[0] * (n + 1) for _ in range(m + 1)] # increments
for x in range(m):
for y in range(n):
self.update(x, y, matrix[x][y])
def update(self, x, y, val):
"""
:type x: int
:type y: int
:type val: int
:rtype: void
"""
i = x + 1
j = y + 1
delta = val - self.incr[i][j]
self.incr[i][j] = val
m, n = len(self.incr), len(self.incr[0])
while i < m:
j = y + 1
while j < n:
self.bits[i][j] += delta
j += (j & -j)
i += (i & -i)
def sumRegion(self, x1, y1, x2, y2):
"""
:type x1: int
:type y1: int
:type x2: int
:type y2: int
:rtype: int
"""
return sum((
self.sum(x2 + 1, y2 + 1),
- self.sum(x1, y2 + 1),
- self.sum(x2 + 1, y1),
self.sum(x1, y1),
))
def sum(self, x, y):
res = 0
i = x
j = y
while i > 0:
j = y
while j > 0:
res += self.bits[i][j]
j -= (j & -j)
i -= (i & -i)
return res
================================================
FILE: leetcode/30_substring_with_concatenation_of_all_words.py
================================================
class Solution:
def findSubstring(self, s, S):
"""
:type s: str
:type S: List[str]
:rtype: List[int]
"""
ans = []
if not s or not S or len(s) < len(S) * len(S[0]):
return ans
n, m, k = len(s), len(S), len(S[0])
F = {}
for c in S:
F[c] = F.get(c, 0) + 1
for start in range(k):
_F = {}
cnt = 0
left = start
for right in range(start, n - k + 1, k):
sr = s[right:right + k]
if sr not in F:
_F = {}
cnt = 0
left = right + k
continue
_F[sr] = _F.get(sr, 0) + 1
if _F[sr] <= F[sr]:
cnt += 1
while _F[sr] > F[sr]:
sl = s[left:left + k]
if _F[sl] == F[sl]:
cnt -= 1
_F[sl] -= 1
left += k
if cnt == m:
ans.append(left)
sl = s[left:left + k]
cnt -= 1
_F[sl] -= 1
left += k
return ans
================================================
FILE: leetcode/315_count_of_smaller_numbers_after_self.py
================================================
class Solution:
"""
REF: https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76657/
"""
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
n = len(nums)
ans = [0] * n
cands = sorted(set(nums))
v2i = {cands[i]: i for i in range(len(cands))}
self.bits = [0] * (len(v2i) + 1)
for i in range(n - 1, -1, -1):
j = v2i[nums[i]]
ans[i] = self.sum(j)
self.update(j)
return ans
def update(self, i):
i += 1
while i < len(self.bits):
self.bits[i] += 1
i += (i & -i)
def sum(self, i):
res = 0
while i > 0:
res += self.bits[i]
i -= (i & -i)
return res
class Solution:
"""
Brute Force: TLE
"""
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
if not nums:
return ans
n = len(nums)
for i in range(n):
ans.append(0)
for j in range(i, n):
if nums[j] < nums[i]:
ans[-1] += 1
return ans
================================================
FILE: leetcode/323_number_of_connected_components_in_an_undirected_graph.py
================================================
"""
Testing:
>>> gotcha = []
>>> for s in (Solution(), Solution2()):
... for _in, _out in (
... ((5, [[0, 1], [1, 2], [3, 4]]), 2),
... ((5, [[0, 1], [1, 2], [2, 3], [3, 4]]), 1),
... ):
... res = s.countComponents(*_in)
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class Solution:
"""
Union Find
"""
def countComponents(self, n, edges):
"""
:type n: int
:type edges: list[int]
:rtype: int
"""
if not n or not edges:
return 0
nodes = [i for i in range(n)]
ans = n
for a, b in edges:
if self.union(nodes, a, b):
ans -= 1
return ans
def union(self, nodes, a, b):
_a = self.find(nodes, a)
_b = self.find(nodes, b)
if _a == _b:
return False
nodes[_b] = _a
return True
def find(self, nodes, a):
if a not in nodes:
nodes[a] = a
return a
if nodes[a] == a:
return a
nodes[a] = self.find(nodes[a])
return nodes[a]
class Solution2:
"""
DFS
"""
def countComponents(self, n, edges):
"""
:type n: int
:type edges: list[int]
:rtype: int
"""
ans = 0
if not n or not edges:
return ans
adj = {}
for i in range(n):
adj[i] = set()
for a, b in edges:
adj[a].add(b)
adj[b].add(a)
visited = set()
for i in range(n):
if i in visited:
continue
ans += 1
self.dfs(i, adj, visited)
return ans
def dfs(self, a, adj, visited):
if a not in adj:
return
visited.add(a)
for b in adj[a]:
if b in visited:
continue
self.dfs(b, adj, visited)
================================================
FILE: leetcode/324_wiggle_sort_ii.py
================================================
"""
Follow Up: https://discuss.leetcode.com/topic/32929/o-n-o-1-after-median-virtual-indexing
"""
class Solution:
def wiggleSort(self, A):
"""
:type A: List[int]
:rtype: void Do not return anything, modify A in-place instead.
"""
if not A:
return
n = len(A)
S = sorted(A)
for i in range(1, n, 2):
A[i] = S.pop()
for i in range(0, n, 2):
A[i] = S.pop()
================================================
FILE: leetcode/326_power_of_three.py
================================================
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if not n:
return False
for i in (81, 27, 9, 3):
while n % i == 0:
n //= i
return n == 1
================================================
FILE: leetcode/329_longest_increasing_path_in_a_matrix.py
================================================
class Solution:
def longestIncreasingPath(self, G):
"""
:type G: List[List[int]]
:rtype: int
"""
if not G or not G[0]:
return 0
self.V = (
(-1, 0),
( 1, 0),
( 0, -1),
( 0, 1),
)
ans = 1
m, n = len(G), len(G[0])
memo = [[0] * n for _ in range(m)]
for x in range(m):
for y in range(n):
size = self.dfs(G, x, y, memo)
if size > ans:
ans = size
return ans
def dfs(self, G, x, y, memo):
if memo[x][y] > 0:
return memo[x][y]
res = 1
for dx, dy in self.V:
_x = x + dx
_y = y + dy
if not (0 <= _x < len(G) and 0 <= _y < len(G[0])):
continue
if G[x][y] >= G[_x][_y]:
continue
size = 1 + self.dfs(G, _x, _y, memo)
if size > res:
res = size
memo[x][y] = res
return res
================================================
FILE: leetcode/334_increasing_triplet_subsequence.py
================================================
class Solution:
def increasingTriplet(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if not A:
return False
a = b = float('inf')
for x in A:
if x <= a:
a = x
elif x <= b:
b = x
else:
return True
return False
================================================
FILE: leetcode/33_search_in_rotated_sorted_array.py
================================================
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
NOT_FOUND = -1
if not nums:
return NOT_FOUND
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < nums[0]:
if nums[mid] < target <= nums[right]:
left = mid
else:
right = mid
else:
if nums[left] <= target < nums[mid]:
right = mid
else:
left = mid
for mid in (left, right):
if nums[mid] == target:
return mid
return NOT_FOUND
================================================
FILE: leetcode/340_longest_substring_with_at_most_k_distinct_characters.py
================================================
"""
- count chars: minimum length: `while cnt == k` to reduce window size if possible
- count chars: maximum length: `while cnt > k` to record the maximum window size
"""
import collections
class Solution:
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
ans = 0
if not s or not k or k < 0:
return ans
freqs = collections.defaultdict(int)
i = cnt = 0
for j in range(len(s)):
freqs[s[j]] += 1
if freqs[s[j]] == 1:
cnt += 1
while cnt > k:
freqs[s[i]] -= 1
if freqs[s[i]] == 0:
cnt -= 1
i += 1
ans = max(ans, j - i + 1)
return ans
================================================
FILE: leetcode/344_reverse_string.py
================================================
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return ''.join(reversed(s))
================================================
FILE: leetcode/347_top_k_frequent_elements.py
================================================
class Solution:
def topKFrequent(self, A, k):
"""
:type A: List[int]
:type k: int
:rtype: List[int]
"""
ans = []
if not A:
return ans
F = {}
for a in A:
F[a] = F.get(a, 0) + 1
for a, _ in sorted(F.items(), key=lambda x: -x[1]):
if k == 0:
break
ans.append(a)
k -= 1
return ans
================================================
FILE: leetcode/348_design_tic_tac_toe.py
================================================
class TicTacToe(object):
PLER_A = 1
PLER_B = 2
def __init__(self, n):
"""
Initialize your data structure here.
:type n: int
"""
self.R = [0] * n
self.C = [0] * n
self.DR = 0 # only one
self.DL = 0 # only one
def move(self, x, y, player):
"""
Player {player} makes a move at ({x}, {y}).
:type x: int The row of the board.
:type y: int The column of the board.
:type player: int The player, can be either 1 or 2.
:rtype: int The current winning condition, can be either:
0: No one wins.
1: Player 1 wins.
2: Player 2 wins.
"""
n = len(self.R)
delta = 1 if player == self.PLER_A else -1
self.R[x] += delta
self.C[y] += delta
self.DR += delta if x == y else 0 # x - y == 0
self.DL += delta if x == n - 1 - y else 0 # x + y == n - 1
return (abs(self.R[x]) == n or
abs(self.C[y]) == n or
abs(self.DR) == n or
abs(self.DL) == n)
# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(x,y,player)
================================================
FILE: leetcode/353_design_snake_game.py
================================================
"""
0. self.height is for `m`, self.width is for `n`
1. note that, REMOVE FIRST,
MUST remove the snake tail **BEFORE** check it hit its body
2. this game is over if
- hit wall
- hit it self
- no food
3. dont pop food in every move, just track its index
4. the score is just the len(body) - 1, except the head
5. what its return if no food or food is all taken?
6. does allow the snake just back if its body only 2?
Initially the snake appears at position (0,0) and the food at (1,2).
Your SnakeGame object will be instantiated and called as such:
obj = SnakeGame(width, height, food)
param_1 = obj.move(direction)
>>> snake = SnakeGame(3, 2, [[1, 2], [0, 1]])
>>> [snake.move(d) for d in 'RDRULU']
[0, 0, 1, 1, 2, -1]
>>> all(snake.move(d) == -1 for d in 'LUDR')
True
>>> snake = SnakeGame(3, 3, [[2, 0], [0, 0]])
>>> [snake.move(d) for d in 'DDUU']
[0, 1, 1, 2]
>>> all(snake.move(d) == -1 for d in 'RUDL')
True
"""
import collections
class SnakeGame:
def __init__(self, width, height, food):
"""
:type width: int, screen width
:type height: int, screen height
:type food: List[List[int]], A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1],
the second is at [1,0].
"""
if not width or not height or not food:
# raise error
return
self.width = width
self.height = height
self.food = food
self.fi = 0
self.is_over = False
self.SCORE_IN_OVER = -1
pos = [(0, 0)]
self.snake = collections.deque(pos)
self.body = set(pos)
self.dn = {
'U': (-1, 0),
'D': ( 1, 0),
'L': ( 0, -1),
'R': ( 0, 1),
}
def move(self, direction):
"""Moves the snake.
:type direction: str, 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
:rtype: int, The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
"""
if direction not in self.dn:
# treat this move as invalid action
return len(self.snake) - 1
if self.is_over:
# this game is over
return self.SCORE_IN_OVER
"""
new head will hit wall?
"""
x, y = self.snake[0]
dx, dy = self.dn[direction]
hx = x + dx
hy = y + dy
if not (0 <= hx < self.height and 0 <= hy < self.width):
self.is_over = True
return self.SCORE_IN_OVER
"""
eat food or not
"""
fx, fy = self.food[self.fi]
if fx == hx and fy == hy:
# eat that food
self.fi += 1
else:
# move to empty cell and need to remove tail
tail = self.snake.pop()
self.body.discard(tail)
"""
new head will hit its self?
this detection MUST AFTER removing tail
"""
if (hx, hy) in self.body:
self.is_over = True
return self.SCORE_IN_OVER
"""
new head is valid, track it
"""
self.snake.appendleft((hx, hy))
self.body.add((hx, hy))
"""
There is no food anymore
"""
if self.fi >= len(self.food):
self.is_over = True
return len(self.snake) - 1
================================================
FILE: leetcode/36_valid_sudoku.py
================================================
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
if not board or not board[0] or len(board) != len(board[0]):
return False
n = len(board)
EMPTY = '.'
CANDS = '123456789'
for x in range(n):
used = set()
for y in range(n):
if board[x][y] == EMPTY:
continue
if board[x][y] not in CANDS:
return False
if board[x][y] in used:
return False
used.add(board[x][y])
for y in range(n):
used = set()
for x in range(n):
if board[x][y] == EMPTY:
continue
if board[x][y] in used:
return False
used.add(board[x][y])
for i in range(3):
for j in range(3):
used = set()
for x in range(i * 3, i * 3 + 3):
for y in range(j * 3, j * 3 + 3):
if board[x][y] == EMPTY:
continue
if board[x][y] in used:
return False
used.add(board[x][y])
return True
================================================
FILE: leetcode/377_combination_sum_iv.py
================================================
"""
- item can only pick once (even diff item with same val): num loop -> amount loop, amount from end to start, + break
- item can pick multiple but diff order is same path: num loop -> amount loop, amount from start to end
- item can pick multiple but diff order is diff path: amount loop -> num loop, amount from start to end
"""
class Solution:
"""
Dynamic Programming
"""
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
dp = [0] * (target + 1)
dp[0] = 1
# if iterate num first, then the answer will become the number of unique set
# see the last Solution in this file
for amount in range(1, target + 1):
for num in nums:
if amount >= num:
dp[amount] += dp[amount - num]
return dp[target]
class Solution:
"""
Memory Search /
Dynamic Programming /
DFS
"""
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
dp = [-1] * (target + 1)
dp[0] = 1
self.memo_search(nums, target, dp)
return dp[target]
def memo_search(self, nums, remain, dp):
if dp[remain] > -1:
return dp[remain]
res = 0
for a in nums:
if remain < a:
continue
res += self.memo_search(nums, remain - a, dp)
dp[remain] = res
return res
class Solution:
"""
DFS: TLE
"""
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
ans = []
nums.sort(reverse=True)
self.dfs(nums, target, ans, [])
return len(ans)
def dfs(self, nums, remain, ans, path):
if remain == 0:
ans.append(path[::-1])
return
for a in nums:
if remain < a:
continue
path.append(a)
self.dfs(nums, remain - a, ans, path)
path.pop()
# ======
class Solution:
"""
Dynamic Programming: wrong answer for this question
This approach is to find the unique combination
"""
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
dp = [0] * (target + 1)
dp[0] = 1
for num in nums:
for amount in range(num, target + 1):
dp[amount] += dp[amount - num]
return dp[target]
================================================
FILE: leetcode/378_kth_smallest_element_in_a_sorted_matrix.py
================================================
from heapq import heappop, heappush
class Solution:
def kthSmallest(self, G, k):
"""
:type G: List[List[int]]
:type k: int
:rtype: int
"""
if not G or not G[0]:
return 0
heap = []
for x in range(len(G)):
heappush(heap, (G[x][0], x, 0))
while heap:
a, x, y = heappop(heap)
k -= 1
if k == 0:
return a
if y + 1 < len(G[x]):
heappush(heap, (G[x][y + 1], x, y + 1))
return 0
================================================
FILE: leetcode/37_sudoku_solver.py
================================================
class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0] or len(board) != len(board[0]):
return
self.dfs(board, 0, 0)
def dfs(self, board, x, y):
n = len(board)
if x == n:
return True
_x, _y = x, y + 1
if y == n - 1:
_x = x + 1
_y = 0
if board[x][y] != '.':
if not self.is_valid(board, x, y):
return False
return self.dfs(board, _x, _y)
for i in range(1, n + 1):
board[x][y] = str(i)
if (
self.is_valid(board, x, y) and
self.dfs(board, _x, _y)
):
return True
board[x][y] = '.'
return False
def is_valid(self, board, x, y):
if board[x][y] not in '123456789':
return False
n = len(board)
for i in range(n):
if y != i and board[x][y] == board[x][i]:
return False
if x != i and board[x][y] == board[i][y]:
return False
r = x // 3 * 3
c = y // 3 * 3
for i in range(r, r + 3):
for j in range(c, c + 3):
if x == i and y == j:
continue
if board[x][y] == board[i][j]:
return False
return True
================================================
FILE: leetcode/380_insert_delete_getrandom_o1.py
================================================
"""
Your RandomizedSet object will be instantiated and called as such:
obj = RandomizedSet()
param = obj.insert(val)
param = obj.remove(val)
param = obj.getRandom()
"""
import random
class RandomizedSet:
def __init__(self):
self.nums = []
self.val2idx = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
self.val2idx[val] = len(self.nums)
self.nums.append(val)
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.val2idx:
return False
i = self.val2idx[val]
key = self.nums[-1]
self.val2idx[key] = i
self.nums[i] = self.nums[-1]
self.nums.pop()
del self.val2idx[val]
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
i = random.randrange(len(self.nums))
return self.nums[i]
================================================
FILE: leetcode/381_insert_delete_getrandom_o1_duplicates_allowed.py
================================================
import random
class RandomizedCollection:
def __init__(self):
self.A = []
self.I = {}
def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool
"""
A, I = self.A, self.I
if val not in I:
I[val] = set()
A.append(val)
I[val].add(len(A) - 1)
return len(I[val]) == 1
def remove(self, val):
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool
"""
A, I = self.A, self.I
if val not in I or not I[val]:
return False
i = I[val].pop()
_val = A[-1]
I[_val].add(i)
I[_val].discard(len(A) - 1)
A[i] = _val
A.pop()
return True
def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
return random.choice(self.A)
# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
================================================
FILE: leetcode/382_linked_list_random_node.py
================================================
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from random import randint
class Solution:
def __init__(self, head):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.head = head
def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
res = node = self.head
i = 0
while node:
if randint(0, i) == i:
res = node
node = node.next
i += 1
return res.val
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
================================================
FILE: leetcode/384_shuffle_an_array.py
================================================
from random import randrange
class Solution:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.origin = nums[:]
self.nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
self.nums = self.origin[:]
return self.nums
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
a = self.nums
n = len(a)
for i in range(n):
_i = randrange(i, n)
a[i], a[_i] = a[_i], a[i]
return a
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
================================================
FILE: leetcode/386_lexicographical_numbers.py
================================================
class Solution:
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
ans = []
if not n:
return ans
stack = [1]
while stack:
x = stack.pop()
ans.append(x)
# considering the case no carry up if x + 1
# that is, x in [1, 8]
if x < n and x % 10 < 9:
stack.append(x + 1)
if x * 10 <= n:
stack.append(x * 10)
return ans
================================================
FILE: leetcode/387_first_unique_character_in_a_string.py
================================================
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return -1
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
for i in range(len(s)):
if freq[s[i]] == 1:
return i
return -1
================================================
FILE: leetcode/388_longest_absolute_file_path.py
================================================
"""
Main Concept:
if meet file, record the maximum size of the abs path `root/dir/file`
if meet dir, save current size for `root/dir`
for files:
two cases are at same depth
1. for hidden files
2. for extension in file
for dirs:
do NOT save the max size in each depth
since the children in same depth
may be under different parent
- root
- p1
- f-loooooong-1
- p2
- f-short-2
there is error in that case if save the max size
"""
class Solution:
def lengthLongestPath(self, path):
"""
:type path: str
:rtype: int
"""
ans = 0
if not path:
return ans
dep2size = {0: 0}
for line in path.split('\n'):
name = line.lstrip('\t')
size = len(name)
depth = len(line) - len(name)
if '.' in name:
ans = max(ans, dep2size[depth] + size)
else:
dep2size[depth + 1] = dep2size[depth] + size + 1
return ans
================================================
FILE: leetcode/389_find_the_difference.py
================================================
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
a = ord('a')
ans = ord(t[-1]) - a
for i in range(len(s)):
ans ^= ord(s[i]) - a
ans ^= ord(t[i]) - a
return chr(ans + a)
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
if not t:
return ''
freq = {}
for c in s:
if c not in freq:
freq[c] = 0
freq[c] += 1
for c in t:
if c not in freq:
return c
freq[c] -= 1
for c, cnt in freq.items():
if cnt:
return c
return ''
================================================
FILE: leetcode/38_count_and_say.py
================================================
class Solution:
def countAndSay(self, N):
"""
:type N: int
:rtype: str
"""
queue = '1'
if not N:
return queue
_queue = []
for _ in range(N - 1):
cnt = 0
char = queue[0]
for c in queue:
if c == char:
cnt += 1
continue
_queue.extend((str(cnt), char))
cnt = 1
char = c
_queue.extend((str(cnt), char))
queue, _queue = ''.join(_queue), []
return queue
================================================
FILE: leetcode/390_elimination_game.py
================================================
class Solution:
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
ans = gap = 1
turn = 0
while n > 1:
turn += 1
n //= 2
gap *= 2
delta = gap // 2 + gap * (n - 1)
if turn & 1:
ans += delta
else:
ans -= delta
return ans
================================================
FILE: leetcode/391_perfect_rectangle.py
================================================
import collections
class Solution:
def isRectangleCover(self, recs):
"""
:type recs: List[List[int]]
:rtype: bool
"""
if not recs:
return False
left = bottom = float('inf')
right = top = float('-inf')
points = collections.defaultdict(int)
for l, b, r, t in recs:
left = min(left, l)
bottom = min(bottom, b)
right = max(right, r)
top = max(top, t)
for x, y, val in (
(l, b, 1),
(r, b, 2),
(r, t, 4),
(l, t, 8),
):
if points[x, y] & val:
return False
points[x, y] |= val
if any(
# only check the mid-points
val not in (3, 6, 9, 12, 15)
for (x, y), val in points.items()
if left < x < right or bottom < y < top
):
return False
return True
================================================
FILE: leetcode/395_longest_substring_with_at_least_k_repeating_characters.py
================================================
class Solution:
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
ans = 0
if not s:
return ans
n = len(s)
_F = dict.fromkeys(s, 0)
for m in range(1, len(_F) + 1):
F = _F.copy()
left = right = 0
kind = valid = 0
while right < n:
if kind <= m:
F[s[right]] += 1
if F[s[right]] == 1:
kind += 1
if F[s[right]] == k:
valid += 1
right += 1
else:
if F[s[left]] == 1:
kind -= 1
if F[s[left]] == k:
valid -= 1
F[s[left]] -= 1
left += 1
if kind == valid == m and right - left > ans:
ans = right - left
return ans
================================================
FILE: leetcode/398_random_pick_index.py
================================================
from random import randint
class Solution:
def __init__(self, A):
"""
:type A: List[int]
"""
self.A = A
def pick(self, target):
"""
:type target: int
:rtype: int
"""
res = -1
cnt = 0
for i in range(len(self.A)):
if self.A[i] != target:
continue
cnt += 1
if randint(1, cnt) == cnt:
res = i
return res
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
================================================
FILE: leetcode/399_evaluate_division.py
================================================
import collections
class Solution:
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
ans = []
if not (
equations and
values and
queries and
len(equations) == len(values)
):
return ans
nexts = collections.defaultdict(set)
evals = collections.defaultdict(float)
for i in range(len(equations)):
a, b = equations[i]
nexts[a].add(b)
nexts[b].add(a)
evals[a, b] = 1.0 * values[i]
evals[b, a] = 1.0 / values[i]
for a, b in queries:
res = self.dfs(a, b, 1, nexts, evals, set())
ans.append(float(res))
return ans
def dfs(self, a, b, val, nexts, evals, visited):
res = -1
if a not in nexts:
return res
if a == b:
# this condition must be after `a not in nexts`
# to prevent the node not in graph
return val
visited.add(a)
for c in nexts[a]:
if c in visited or (a, c) not in evals:
continue
res = self.dfs(c, b, val * evals[a, c], nexts, evals, visited)
if res != -1:
break
visited.discard(a)
return res
================================================
FILE: leetcode/406_queue_reconstruction_by_height.py
================================================
"""
Main Concept:
1. group the mans with same height and record origin index
2. record all heights
3. sort heights and iterate from end to start
4. get the corresponding mans and insert to `k` index
input: [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
heights: [4, 5, 6, 7]
process:
7 [(0, 0), (1, 2)] # input[0], input[2]
[[7, 0]]
[[7, 0], [7, 1]]
6 [(1, 4)]
[[7, 0], [6, 1], [7, 1]]
5 [(0, 3), (2, 5)]
[[5, 0], [7, 0], [6, 1], [7, 1]]
[[5, 0], [7, 0], [5, 2], [6, 1], [7, 1]]
4 [(4, 1)]
[[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
"""
class Solution:
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
ans = []
if not people:
return ans
people.sort(key=lambda p: (p[0], -p[1]))
for i in range(len(people) - 1, -1, -1):
ans.insert(people[i][1], people[i])
return ans
class Solution:
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
ans = []
if not people:
return ans
h2mans = {}
heights = []
for i in range(len(people)):
h, k = people[i]
if h in h2mans:
h2mans[h].append((k, i))
else:
h2mans[h] = [(k, i)]
heights.append(h)
heights.sort()
for height in heights[::-1]:
for k, i in sorted(h2mans[height]):
ans.insert(k, people[i])
return ans
================================================
FILE: leetcode/416_partition_equal_subset_sum.py
================================================
"""
REF: https://leetcode.com/problems/partition-equal-subset-sum/discuss/90592
`dp[s]` means the specific sum `s` can be gotten from the sum of subset in `nums`
"""
class Solution:
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return True
target = sum(nums)
if target & 1 == 1:
return False
target //= 2
dp = [False] * (target + 1)
dp[0] = True
for a in nums:
for s in range(target, a - 1, -1):
if dp[s]:
continue
dp[s] = dp[s - a]
return dp[target]
================================================
FILE: leetcode/417_pacific_atlantic_water_flow.py
================================================
class Solution:
"""
BFS
1. for both p-side and a-side, init with queue and visit set
2. add the edge and do bfs
3. only add the cell which higher or equal the previous cell
4. get the intersection in both set
"""
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
pqueue = []
aqueue = []
for x in range(m):
pqueue.append((x, 0))
aqueue.append((x, n - 1))
for y in range(n):
pqueue.append((0, y))
aqueue.append((m - 1, y))
pvisited = set(pqueue)
avisited = set(aqueue)
self.bfs(matrix, pqueue, pvisited)
self.bfs(matrix, aqueue, avisited)
return list(pvisited & avisited)
def bfs(self, matrix, queue, visited):
m, n = len(matrix), len(matrix[0])
for x, y in queue:
for dx, dy in (
(0, -1), (0, 1),
(-1, 0), (1, 0),
):
_x = x + dx
_y = y + dy
if not (0 <= _x < m and 0 <= _y < n):
continue
if (_x, _y) in visited:
continue
if matrix[_x][_y] < matrix[x][y]:
continue
queue.append((_x, _y))
visited.add((_x, _y))
class Solution:
"""
DFS
"""
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
pvisited = set()
avisited = set()
for x in range(m):
self.dfs(matrix, x, 0, pvisited)
self.dfs(matrix, x, n - 1, avisited)
for y in range(n):
self.dfs(matrix, 0, y, pvisited)
self.dfs(matrix, m - 1, y, avisited)
return list(pvisited & avisited)
def dfs(self, matrix, x, y, visited):
visited.add((x, y))
for dx, dy in (
(0, -1), (0, 1),
(-1, 0), (1, 0),
):
_x = x + dx
_y = y + dy
if not (
0 <= _x < len(matrix) and
0 <= _y < len(matrix[0])
):
continue
if (_x, _y) in visited:
continue
if matrix[_x][_y] < matrix[x][y]:
continue
self.dfs(matrix, _x, _y, visited)
================================================
FILE: leetcode/41_first_missing_positive.py
================================================
"""
REF: http://www.cnblogs.com/yuzhangcmu/p/4200096.html
"""
class Solution:
def firstMissingPositive(self, A):
"""
:type A: List[int]
:rtype: int
"""
left, right = 0, len(A) - 1
while left <= right:
"""
for `A[left]`, the index it should be at is `A[left] - 1`
1. if it is already at `i` => pass
2. if it out of range or duplicated => let `A[right]` in
3. if it is legal => swap to let `A[left]` go to `i`
"""
i = A[left] - 1
if i == left:
left += 1
elif i < 0 or i > right or A[i] == A[left]:
A[left], A[right] = A[right], A[left]
# `A[left] = A[right]` is also ok, since no need to visit `A[right]` again
right -= 1
else:
A[left], A[i] = A[i], A[left]
return left + 1
================================================
FILE: leetcode/437_path_sum_iii.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
"""
find path count
"""
def pathSum(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: int
"""
if not root:
return 0
return sum((
self.count_valid_path(root, target),
self.pathSum(root.left, target),
self.pathSum(root.right, target),
))
def count_valid_path(self, node, remaining):
if not node:
return 0
return sum((
int(node.val == remaining),
self.count_valid_path(node.left, remaining - node.val),
self.count_valid_path(node.right, remaining - node.val),
))
class Solution:
"""
print path
"""
def pathSum(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: list[list[int]]
"""
ans = []
if not root:
return ans
self.dfs(root, target, ans, [])
return ans
def dfs(self, node, target, ans, path):
if not node:
return
path.append(node.val)
remaining = target
for i in range(len(path) - 1, -1, -1):
remaining -= path[i]
if remaining == 0:
ans.append(path[i:])
self.dfs(node.left, target, ans, path)
self.dfs(node.right, target, ans, path)
path.pop()
================================================
FILE: leetcode/454_4sum_ii.py
================================================
class Solution:
def fourSumCount(self, A, B, C, D):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
ans = 0
if not A or not B or not C or not D:
return ans
S = {}
for c in C:
for d in D:
key = - (c + d)
S[key] = S.get(key, 0) + 1
for a in A:
for b in B:
if a + b in S:
ans += S[a + b]
return ans
================================================
FILE: leetcode/461_hamming_distance.py
================================================
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
n = x ^ y
ans = 0
if not n:
return ans
while n != 0:
n = n & (n - 1)
ans += 1
return ans
================================================
FILE: leetcode/480_sliding_window_median.py
================================================
import heapq
class HashHeapq:
def __init__(self):
self.__heap = []
def __repr__(self):
return repr(self.__heap)
def __len__(self):
return len(self.__heap)
def __bool__(self):
return bool(self.__heap)
def push(self, val):
heapq.heappush(self.__heap, val)
def pop(self):
if not self.__heap:
return
return heapq.heappop(self.__heap)
def remove(self, val):
if not self.__heap:
return
i = 0
n = len(self.__heap)
while i < n and self.__heap[i] != val:
i += 1
if i == n:
return
if i == n - 1:
self.__heap.pop()
else:
self.__heap[i] = self.__heap[-1]
self.__heap.pop()
heapq._siftup(self.__heap, i)
heapq._siftdown(self.__heap, 0, i)
def top(self):
if not self.__heap:
return
return self.__heap[0]
class Solution:
def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
ans = []
if not nums or k <= 0 or len(nums) < k:
return ans
self.minheap = HashHeapq()
self.maxheap = HashHeapq()
for i in range(len(nums)):
# remove nums[i - k]
if i >= k:
if self.minheap and nums[i - k] >= self.minheap.top():
self.minheap.remove(nums[i - k])
else:
self.maxheap.remove(- nums[i - k])
# add nums[i]
if self.minheap and nums[i] >= self.minheap.top():
self.minheap.push(nums[i])
else:
self.maxheap.push(- nums[i])
# get median
if i >= k - 1:
ans.append(self.get_median())
return ans
def get_median(self):
if not self.minheap and not self.maxheap:
return 0.0
while len(self.minheap) > len(self.maxheap) + 1:
self.maxheap.push(- self.minheap.pop())
while len(self.maxheap) > len(self.minheap):
self.minheap.push(- self.maxheap.pop())
if len(self.minheap) > len(self.maxheap):
return self.minheap.top() * 1.0
return (self.minheap.top() - self.maxheap.top()) / 2.0
================================================
FILE: leetcode/486_predict_the_winner.py
================================================
"""
DP:
time: O(n^2)
space: O(n)
"""
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
n = len(nums)
dp = [0] * n
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[j] = max(
nums[i] - dp[j],
nums[j] - dp[j - 1]
)
return dp[n - 1] >= 0
"""
DP:
time: O(n^2)
space: O(n^2)
"""
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
n = len(nums)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[i][j] = max(
nums[i] - dp[i + 1][j],
nums[j] - dp[i][j - 1]
)
return dp[0][n - 1] >= 0
================================================
FILE: leetcode/48_rotate_image.py
================================================
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0] or len(matrix) != len(matrix[0]):
return
n = len(matrix)
# swap by diagonal axis
for i in range(n - 1):
for j in range(n - 1 - i):
x = n - 1 - j
y = n - 1 - i
matrix[i][j], matrix[x][y] = matrix[x][y], matrix[i][j]
# swap by x-mid axis
for i in range(n // 2):
for j in range(n):
x = n - 1 - i
y = j
matrix[i][j], matrix[x][y] = matrix[x][y], matrix[i][j]
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0] or len(matrix) != len(matrix[0]):
return
n = len(matrix)
ans = [[0] * n for _ in range(n)]
for x in range(n):
for y in range(n):
ans[y][n - 1 - x] = matrix[x][y]
matrix[:] = ans[:]
================================================
FILE: leetcode/490_the_maze.py
================================================
class Solution:
def hasPath(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: bool
>>> s = Solution()
>>> maze = [[0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 1, 0],
... [1, 1, 0, 1, 1],
... [0, 0, 0, 0, 0]]
>>> s.hasPath(maze, [0, 4], [4, 4])
True
>>> s.hasPath(maze, [0, 4], [3, 2])
False
"""
if not maze or not maze[0] or not start or not destination:
return False
x, y = start
tx, ty = destination
visited = set()
return self.dfs(maze, x, y, tx, ty, visited)
def dfs(self, maze, x, y, tx, ty, visited):
if x == tx and y == ty:
return True
if (x, y) in visited:
return False
visited.add((x, y))
m, n = len(maze), len(maze[0])
for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
_x = x + dx
_y = y + dy
while 0 <= _x < m and 0 <= _y < n and maze[_x][_y] == 0:
_x += dx
_y += dy
# since for now its means the position of wall
_x -= dx
_y -= dy
if self.dfs(maze, _x, _y, tx, ty, visited):
return True
return False
================================================
FILE: leetcode/494_target_sum.py
================================================
"""
REF: https://leetcode.com/problems/target-sum/discuss/97334
P: children used in positive,
N: children used in negative,
A: all children
sum(P) - sum(N) = target
=> sum(P) - sum(N) + sum(P) + sum(N) = target + sum(P) + sum(N)
=> 2 * sum(P) = target + sum(A)
=> sum(P) = (target + sum(A)) // 2
=> find the subset sum
"""
class Solution:
def findTargetSumWays(self, A, target):
"""
:type A: List[int]
:type target: int
:rtype: int
"""
if not A:
return 0
_sum = sum(A)
if _sum < target or (_sum + target) % 2 == 1:
return 0
return self.subset_sum(A, (_sum + target) // 2)
def subset_sum(self, A, target):
"""
`dp[i]` means the number of ways
to make sum `i` using non-repeated children in `A`
`i` from `target` to `a - 1` => to make sure `i >= a`
"""
dp = [0] * (target + 1)
dp[0] = 1
for a in A:
for i in range(target, a - 1, -1):
dp[i] += dp[i - a]
return dp[target]
================================================
FILE: leetcode/499_the_maze_iii.py
================================================
class Solution:
"""
BFS
"""
def findShortestWay(self, maze, ball, hole):
"""
:type maze: List[List[int]]
:type ball: List[int]
:type hole: List[int]
:rtype: str
>>> s = Solution()
>>> maze = [[0, 0, 0, 0, 0],
... [1, 1, 0, 0, 1],
... [0, 0, 0, 0, 0],
... [0, 1, 0, 0, 1],
... [0, 1, 0, 0, 0]]
>>> s.findShortestWay(maze, [4, 3], [0, 1])
'lul'
>>> s.findShortestWay(maze, [4, 3], [3, 0])
'impossible'
"""
NOT_FOUND = 'impossible'
if not maze or not maze[0]:
return NOT_FOUND
m, n = len(maze), len(maze[0])
sx, sy = ball
tx, ty = hole
queue = [(sx, sy)]
paths = {(sx, sy): []}
distance = {(sx, sy): 0}
for x, y in queue:
for dx, dy, dn in (
(-1, 0, 'u'), (1, 0, 'd'),
(0, -1, 'l'), (0, 1, 'r'),
):
_x = x + dx
_y = y + dy
_step = 0
while (
0 <= _x < m and 0 <= _y < n and
maze[_x][_y] == 0 and
not (_x == tx and _y == ty)
):
_x += dx
_y += dy
_step += 1
if not (_x == tx and _y == ty):
_x -= dx
_y -= dy
_step -= 1
if ((_x, _y) in distance and
distance[x, y] + _step > distance[_x, _y]):
continue
if ((_x, _y) in paths and
paths[x, y] + [dn] > paths[_x, _y]):
continue
distance[_x, _y] = distance[x, y] + _step
paths[_x, _y] = paths[x, y] + [dn]
queue.append((_x, _y))
return ''.join(paths[tx, ty]) if (tx, ty) in paths else NOT_FOUND
import heapq
class Solution2:
"""
Dijkstra
"""
def findShortestWay(self, maze, ball, hole):
"""
:type maze: List[List[int]]
:type ball: List[int]
:type hole: List[int]
:rtype: str
>>> s = Solution2()
>>> maze = [[0, 0, 0, 0, 0],
... [1, 1, 0, 0, 1],
... [0, 0, 0, 0, 0],
... [0, 1, 0, 0, 1],
... [0, 1, 0, 0, 0]]
>>> s.findShortestWay(maze, [4, 3], [0, 1])
'lul'
>>> s.findShortestWay(maze, [4, 3], [3, 0])
'impossible'
"""
NOT_FOUND = 'impossible'
if not maze or not maze[0]:
return NOT_FOUND
m, n = len(maze), len(maze[0])
sx, sy = ball
tx, ty = hole
heap = [(sx, sy)]
paths = {(sx, sy): []}
distance = {(sx, sy): 0}
while heap:
x, y = heapq.heappop(heap)
for dx, dy, dn in (
(-1, 0, 'u'), (1, 0, 'd'),
(0, -1, 'l'), (0, 1, 'r'),
):
_x = x + dx
_y = y + dy
while (
0 <= _x < m and 0 <= _y < n and
maze[_x][_y] == 0 and
not (_x == tx and _y == ty)
):
_x += dx
_y += dy
if not (_x == tx and _y == ty):
_x -= dx
_y -= dy
_step = distance[x, y] + abs(_x - x) + abs(_y - y)
if (_x, _y) in distance and _step > distance[_x, _y]:
continue
if (_x, _y) in paths and paths[x, y] + [dn] > paths[_x, _y]:
continue
distance[_x, _y] = _step
paths[_x, _y] = paths[x, y] + [dn]
heapq.heappush(heap, (_x, _y))
return ''.join(paths[tx, ty]) if (tx, ty) in paths else NOT_FOUND
================================================
FILE: leetcode/505_the_maze_ii.py
================================================
class Solution:
"""
BFS
"""
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
>>> s = Solution()
>>> maze = [[0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 1, 0],
... [1, 1, 0, 1, 1],
... [0, 0, 0, 0, 0]]
>>> s.shortestDistance(maze, [0, 4], [4, 4])
12
>>> s.shortestDistance(maze, [0, 4], [3, 2])
-1
"""
if not maze or not maze[0]:
return -1
m, n = len(maze), len(maze[0])
sx, sy = start
tx, ty = destination
queue = [(sx, sy)]
distance = {(sx, sy): 0}
for x, y in queue:
for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
_x = x + dx
_y = y + dy
_step = 0
while 0 <= _x < m and 0 <= _y < n and maze[_x][_y] == 0:
_x += dx
_y += dy
_step += 1
_x -= dx
_y -= dy
if ((_x, _y) in distance and
distance[x, y] + _step >= distance[_x, _y]):
continue
distance[_x, _y] = distance[x, y] + _step
if _x == tx and _y == ty:
return distance[_x, _y]
queue.append((_x, _y))
return -1
import heapq
class Solution2:
"""
Dijkstra
"""
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
>>> s = Solution2()
>>> maze = [[0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 1, 0],
... [1, 1, 0, 1, 1],
... [0, 0, 0, 0, 0]]
>>> s.shortestDistance(maze, [0, 4], [4, 4])
12
>>> s.shortestDistance(maze, [0, 4], [3, 2])
-1
"""
if not maze or not maze[0]:
return -1
m, n = len(maze), len(maze[0])
sx, sy = start
tx, ty = destination
heap = [(sx, sy)]
distance = {(sx, sy): 0}
while heap:
x, y = heapq.heappop(heap)
for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
_x = x + dx
_y = y + dy
while 0 <= _x < m and 0 <= _y < n and maze[_x][_y] == 0:
_x += dx
_y += dy
_x -= dx
_y -= dy
_step = distance[x, y] + abs(_x - x) + abs(_y - y)
if (_x, _y) in distance and _step >= distance[_x, _y]:
continue
if _x == tx and _y == ty:
return _step
distance[_x, _y] = _step
heapq.heappush(heap, (_x, _y))
return -1
================================================
FILE: leetcode/518_coin_change_2.py
================================================
class Solution:
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
"""
`dp[a]` means the ways to make up amount `a`
"""
dp = [0] * (amount + 1)
dp[0] = 1 # the ways to make up `0` is just only 1
"""
iterate coin first, and then amount
otherwise it will add the dup ways in
re-count if `[1, 2]` and `[2, 1]`, but they are same
"""
for c in coins:
for a in range(c, amount + 1):
# if a < c: continue
dp[a] += dp[a - c]
return dp[amount]
================================================
FILE: leetcode/51_n_queens.py
================================================
class Solution:
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
ans = []
if not n:
return ans
G = [['.'] * n for _ in range(n)]
self.dfs(G, 0, ans)
return ans
def dfs(self, G, y, ans):
if y == len(G):
ans.append(self.clone_board(G))
return
for x in range(len(G)):
if self.is_valid(G, x, y):
G[x][y] = 'Q'
self.dfs(G, y + 1, ans)
G[x][y] = '.'
def is_valid(self, G, x, y):
"""
traverse left half => i in [0, n], j in [0, y - 1] to
1. avoid `j == y` and speed up
and return False if
2. `x == i` => at same row
3. `x - i = y - j` => `x + j = y + i` => left diagonal line
4. `x - i = -(y - j)` => `x + y = i + j` => right diagonal line
"""
for i in range(len(G)):
for j in range(y):
if G[i][j] != 'Q':
continue
if (x + j == y + i or
x + y == i + j or
x == i):
return False
return True
def clone_board(self, G):
res = []
for R in G:
res.append(''.join(R))
return res
================================================
FILE: leetcode/524_longest_word_in_dictionary_through_deleting.py
================================================
class Solution:
"""
1. to check the word in list is subsequence of given s
2. ignoring if the length less than current ans
3. ignoring if the length equal current ans but has larger lexicographical order
"""
def findLongestWord(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: str
"""
ans = ''
for w in words:
if any((
not self.is_subseq(s, w),
len(w) < len(ans),
len(w) == len(ans) and w >= ans, # means w has larger lexicographical order
)):
continue
ans = w
return ans
def is_subseq(self, s, t):
"""
return True if `t` is subsequence of `s`
"""
m, n = len(s), len(t)
i = j = 0
while i < m and j < n:
if s[i] == t[j]:
j += 1
i += 1
return j == n
class Solution:
"""
Brute Force: TLE
"""
def findLongestWord(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: str
"""
cands = []
self.find_cands(s, 0, cands, [])
ans = ''
target = set(words)
for w in cands:
if any((
w not in target,
len(w) < len(ans),
len(w) == len(ans) and w >= ans,
)):
continue
ans = w
return ans
def find_cands(self, s, i, cands, path):
if i == len(s):
cands.append(''.join(path))
return
# keep s[i]
path.append(s[i])
self.find_cands(s, i + 1, cands, path)
path.pop()
# ignore s[i]
self.find_cands(s, i + 1, cands, path)
================================================
FILE: leetcode/52_n_queens_ii.py
================================================
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
Xs = set()
DLs = set() # left diagonal lines
DRs = set() # right diagonal lines
return self.divide_conquer(n, 0, 0, Xs, DLs, DRs)
def divide_conquer(self, n, y, cnt, Xs, DLs, DRs):
for x in range(n):
if x in Xs:
continue
dl = x - y
if dl in DLs:
continue
dr = x + y
if dr in DRs:
continue
if y == n - 1:
cnt += 1
continue
Xs.add(x)
DLs.add(dl)
DRs.add(dr)
cnt = self.divide_conquer(n, y + 1, cnt, Xs, DLs, DRs)
Xs.discard(x)
DLs.discard(dl)
DRs.discard(dr)
return cnt
================================================
FILE: leetcode/530_minimum_absolute_difference_in_bst.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
"""
time: O(n)
space: O(1)
"""
ans = float('inf')
pre = None
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return self.ans
self.getMinimumDifference(root.left)
if self.pre and root.val - self.pre.val < self.ans:
self.ans = root.val - self.pre.val
self.pre = root
self.getMinimumDifference(root.right)
return self.ans
================================================
FILE: leetcode/542_01_matrix.py
================================================
class Solution:
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
ans = [[float('inf')] * n for _ in range(m)]
queue = []
for x in range(m):
for y in range(n):
if matrix[x][y] == 0:
ans[x][y] = 0
queue.append((x, y))
for x, y in queue:
for dx, dy in (
(-1, 0), (1, 0),
(0, -1), (0, 1),
):
_x = x + dx
_y = y + dy
if not (0 <= _x < m and 0 <= _y < n):
continue
if ans[_x][_y] < ans[x][y] + 1:
continue
ans[_x][_y] = ans[x][y] + 1
queue.append((_x, _y))
return ans
================================================
FILE: leetcode/54_spiral_matrix.py
================================================
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
ans = []
if not matrix or not matrix[0]:
return ans
# need keep its order to go right, bottom, left, top
delta = (
(0, 1), (1, 0),
(0, -1), (-1, 0),
)
m, n = len(matrix), len(matrix[0])
x = y = turn = 0
for _ in range(m * n):
ans.append(matrix[x][y])
matrix[x][y] = None
_x = x + delta[turn][0]
_y = y + delta[turn][1]
if not (0 <= _x < m and 0 <= _y < n) or matrix[_x][_y] is None:
turn = (turn + 1) % len(delta)
_x = x + delta[turn][0]
_y = y + delta[turn][1]
x = _x
y = _y
return ans
================================================
FILE: leetcode/592_fraction_addition_and_subtraction.py
================================================
import re
class Solution:
def fractionAddition(self, E):
"""
:type E: str
:rtype: str
"""
S = [] # signs
if E[0] != '-':
S.append('+')
for c in E:
if c == '+' or c == '-':
S.append(c)
a, b = 0, 1
i = 0
for frac in re.split('\+|-', E):
if not frac:
continue
_a, _b = frac.split('/')
_a = int(_a)
_b = int(_b)
# if needs to prevent overflow, `// gcd`
if S[i] == '+':
a = a * _b + _a * b
else:
a = a * _b - _a * b
b = b * _b
gcd = self.get_gcd(a, b)
a //= gcd
b //= gcd
i += 1
return '{}/{}'.format(a, b)
def get_gcd(self, a, b):
while b:
a, b = b, a % b
return a
================================================
FILE: leetcode/593_valid_square.py
================================================
class Solution:
def validSquare(self, p1, p2, p3, p4):
"""
:type p1: List[int]
:type p2: List[int]
:type p3: List[int]
:type p4: List[int]
:rtype: bool
"""
ps = []
for p in (p1, p2, p3, p4):
if not p:
return False
ps.append(p)
ps.sort()
# 0: lb, 1: lt, 2:rb, 3: rt
l01 = self.get_distance(ps[0], ps[1])
l02 = self.get_distance(ps[0], ps[2])
l13 = self.get_distance(ps[1], ps[3])
l23 = self.get_distance(ps[2], ps[3])
l03 = self.get_distance(ps[0], ps[3])
l12 = self.get_distance(ps[1], ps[2])
return all((
l01 == l02 == l13 == l23 > 0,
l03 == l12,
))
def get_distance(self, a, b):
"""
find the size of 'ab'
"""
dx = a[0] - b[0]
dy = a[1] - b[1]
return (dx * dx + dy * dy) ** 0.5
================================================
FILE: leetcode/59_spiral_matrix_ii.py
================================================
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if not n or n < 1:
return []
if n == 1:
return [[1]]
ans = [[0] * n for _ in range(n)]
delta = (
(0, 1), (1, 0),
(0, -1), (-1, 0),
)
x = y = turn = 0
for i in range(1, n * n + 1):
ans[x][y] = i
_x = x + delta[turn][0]
_y = y + delta[turn][1]
if not (0 <= _x < n and 0 <= _y < n) or ans[_x][_y] != 0:
turn = (turn + 1) % len(delta)
_x = x + delta[turn][0]
_y = y + delta[turn][1]
x = _x
y = _y
return ans
================================================
FILE: leetcode/5_longest_palindromic_substring.py
================================================
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return ''
start = size = 0
for i in range(len(s)):
_start, _size = self.check_palindrome(s, i, i)
if _size > size:
size = _size
start = _start
_start, _size = self.check_palindrome(s, i, i + 1)
if _size > size:
size = _size
start = _start
return s[start:start + size]
def check_palindrome(self, s, left, right):
n = len(s)
while left >= 0 and right < n and s[left] == s[right]:
left -= 1
right += 1
return left + 1, right - left - 1
================================================
FILE: leetcode/616_add_bold_tag_in_string.py
================================================
"""
>>> gotcha = []
>>> for s in (Solution(),):
... for _in, _out in (
... (('', ['']), ''),
... (('abcxyz123', ['abc', '123']), '<b>abc</b>xyz<b>123</b>'),
... (('aaabbcc', ['aaa','aab','bc']), '<b>aaabbc</b>c'),
... (('aabcd', ['ab', 'bc']), 'a<b>abc</b>d'),
... ):
... res = s.addBoldTag(*_in)
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class Solution:
def addBoldTag(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: str
"""
if not s or not words:
return ''
TMPL = '<b>{}</b>'
n = len(s)
ans = []
is_bold = [False] * n
left = right = 0
for left in range(n):
for w in words:
size = len(w)
if s[left:left + size] == w and left + size > right:
right = left + size
is_bold[left] = right > left
left = right = 0
while left < n:
if not is_bold[left]:
ans.append(s[left])
left += 1
continue
right = left
while right < n and is_bold[right]:
right += 1
ans.append(TMPL.format(s[left:right]))
left = right # imply left' = left + 1
return ''.join(ans)
================================================
FILE: leetcode/643_maximum_average_subarray_i.py
================================================
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
"""
Assuming the answer we want is `Ans = Max(A[i] + A[i+1] + ... + A[i+k-1])`,
and we define the `P[i] = A[0] + A[1] + ... + A[i-1]`,
so that `Ans = Max(P[i+k] - P[i])`, and `i+k-1 < n -> i < n-k+1`
* max index in P is `i+k`, so in A is `(i+k)-1`, `i+k-1 < n`
"""
"""
P[0] = 0
P[1] = P[0] + A[0]
P[2] = P[1] + A[1]
P[i] = P[i-1] + A[i-1]
= A[0] + A[1] + ... + A[i-1]
"""
P = [0]
for x in nums: P.append(P[-1] + x)
max_sum = max(P[i+k] - P[i] for i in range(len(nums) - k + 1))
return max_sum / float(k)
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
"""
Assuming k = 3
i: 0 1 2 3
|--> Start to find max sum
|--> Start to remove past child
"""
max_sum, tmp_sum = float('-inf'), 0
for i in range(len(nums)):
tmp_sum += nums[i]
if i >= k:
tmp_sum -= nums[i-k]
if i + 1 >= k:
max_sum = max(max_sum, tmp_sum)
return max_sum / float(k)
================================================
FILE: leetcode/66_plus_one.py
================================================
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
ans = []
if not digits:
return ans
carry = 1
for i in range(len(digits) - 1, -1, -1):
carry += digits[i]
ans.append(carry % 10)
carry //= 10
if carry:
ans.append(carry)
ans.reverse()
return ans
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if not digits:
return []
carry = 0
digits[-1] += 1
for i in range(len(digits) - 1, -1, -1):
carry += digits[i]
digits[i] = carry % 10
carry //= 10
if carry:
digits.append(carry)
for i in range(len(digits) - 1, 0, -1):
digits[i], digits[i - 1] = digits[i - 1], digits[i]
return digits
================================================
FILE: leetcode/676_implement_magic_dictionary.py
================================================
"""
Your MagicDictionary object will be instantiated and called as such:
obj = MagicDictionary()
obj.buildDict(dict)
param_2 = obj.search(word)
"""
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.words = collections.defaultdict(set)
def buildDict(self, words):
"""
Build a dictionary through a list of words
:type words: List[str]
:rtype: void
"""
for word in words:
for i in range(len(word)):
key = '{0},{1}'.format(word[:i], word[i + 1:])
if key not in self.words:
self.words[key] = set()
# add char to distinct word if its same
self.words[key].add(word[i])
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
for i in range(len(word)):
key = '{0},{1}'.format(word[:i], word[i + 1:])
if key not in self.words:
continue
words = self.words[key]
# 1. word[i] not in words => means not same word
# 2. len(words) > 1 => if got same but still can mapping other
if word[i] not in words or len(words) > 1:
return True
return False
================================================
FILE: leetcode/679_24_game.py
================================================
class Solution:
EPS = 1e-6
OP = (
lambda a, b: a + b,
lambda a, b: a * b,
lambda a, b: a - b,
lambda a, b: a / b,
)
def judgePoint24(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
n = len(nums)
if n == 1:
return abs(nums[0] - 24) < self.EPS
for i in range(n):
for j in range(n):
if i == j:
continue
nxts = [nums[k] for k in range(n) if i != k != j] # i != j != k is different
for k in range(len(self.OP)):
if i < j and k < 2:
# since a + b == b + a, so just do half in j >= i
# same for `*`
continue
if nums[j] == 0 and k == 3:
# divide by 0
continue
nxts.append(self.OP[k](nums[i], nums[j]))
if self.judgePoint24(nxts):
return True
nxts.pop()
return False
================================================
FILE: leetcode/681_next_closest_time.py
================================================
"""
it's very similar with `next permutation`
just a `next combination`
1. `digits` save unique num and in order
2. `ids` record current used num
3. keep doing plus one and check valid
>>> gotcha = []
>>> s = Solution()
>>> for _in, _out in (
... ('19:34', '19:39'), ('23:59', '22:22'),
... ('22:22', '22:22'), ('24:24', ''),
... ('23:23', '23:32'), ('12:34', '12:41'),
... ('00:00', '00:00'), ('01:32', '01:33'),
... ):
... res = s.nextClosestTime(_in)
... if res != _out: print('in: {}, out: {}, exp: {}'.format(_in, res, _out))
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class Solution:
def nextClosestTime(self, time):
"""
:type time: str
:rtype: str
"""
if not (
time and len(time) == 5 and time[2] == ':' and
0 <= int(time[:2]) < 24 and 0 <= int(time[3:]) < 60
):
return ''
times = [int(t) for t in time if t != ':']
digits = []
for a in sorted(times):
if digits and a == digits[-1]:
continue
digits.append(a)
ids = [digits.index(t) for t in times]
ids[-1] += 1
while not self.is_valid(ids, digits):
ids[-1] += 1
h = digits[ids[0]] * 10 + digits[ids[1]]
m = digits[ids[2]] * 10 + digits[ids[3]]
return '{}:{}'.format(
'0' + str(h) if h < 10 else str(h),
'0' + str(m) if m < 10 else str(m)
)
def is_valid(self, ids, digits):
n = len(digits)
carry = 0
i = len(ids) - 1
while i >= 0:
carry += ids[i]
ids[i] = carry % n
carry = carry // n
i -= 1
if carry:
ids[:] = [0] * len(ids)
return True
h = digits[ids[0]] * 10 + digits[ids[1]]
m = digits[ids[2]] * 10 + digits[ids[3]]
if 0 <= h < 24 and 0 <= m < 60:
return True
return False
================================================
FILE: leetcode/682_baseball_game.py
================================================
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
if not ops:
return 0
stack = []
for op in ops:
if op == 'C':
stack.pop()
elif op == 'D':
stack.append(2 * stack[-1])
elif op == '+':
stack.append(stack[-1] + stack[-2])
else:
stack.append(int(op))
return sum(stack)
================================================
FILE: leetcode/683_k_empty_slots.py
================================================
"""
>>> gotcha = []
>>> for s in (Solution(), Solution2()):
... for _in, _out in (
... (([1,3,2], 1), 2),
... (([1,2,3], 1), -1),
... ):
... res = s.kEmptySlots(*_in)
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
import bisect
class Solution:
"""
Maintain pos by bloom order
"""
def kEmptySlots(self, flowers, k):
"""
:type flowers: List[int]
:type k: int
:rtype: int
"""
bloom = []
for day in range(len(flowers)):
x = flowers[day]
i = bisect.bisect_left(bloom, x)
for _x in bloom[max(0, i - 1):i + 1]:
if abs(_x - x) - 1 == k:
return day + 1 # changed to 1-based
bloom.insert(i, x)
return -1
class Solution2:
"""
Two Pointer:
https://blog.csdn.net/magicbean2/article/details/79235465
"""
def kEmptySlots(self, flowers, k):
"""
:type flowers: List[int]
:type k: int
:rtype: int
"""
n = len(flowers)
x2day = [0] * n
for day in range(n):
"""
day: 0-based => 1-based
x: 1-based => 0-based
"""
x = flowers[day]
x2day[x - 1] = day + 1
ans = INF = float('inf')
left, right = 0, k + 1
i = 0
while right < n:
if any((
x2day[i] < x2day[left],
x2day[i] <= x2day[right],
)):
if i == right:
ans = min(ans, max(x2day[left], x2day[right]))
left, right = i, k + i + 1
i += 1
return ans if ans < INF else -1
================================================
FILE: leetcode/684_redundant_connection.py
================================================
"""
given input is an undirected graph
1. iterate edges
2. if u and v are connected before we add edge in nodes (graph)
=> that is the edge should be removed
"""
class Solution:
"""
UnionFind
"""
def findRedundantConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
if not edges:
return []
nodes = {}
for u, v in edges:
if not self.union(nodes, u, v):
return [u, v]
return []
def union(self, nodes, u, v):
a = self.find(nodes, u)
b = self.find(nodes, v)
if a == b:
return False
nodes[a] = b
return True
def find(self, nodes, u):
if u not in nodes:
nodes[u] = u
return u
if nodes[u] == u:
return u
nodes[u] = self.find(nodes, nodes[u])
return nodes[u]
import collections
class Solution:
"""
DFS
"""
def findRedundantConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
if not edges:
return []
nodes = collections.defaultdict(set)
for u, v in edges:
# dfs to check u and v are connected already => cycle
if u in nodes and v in nodes and self.dfs(nodes, u, v, set()):
return [u, v]
nodes[u].add(v)
nodes[v].add(u)
return []
def dfs(self, nodes, u, v, visited):
if u == v:
return True
if u in visited:
return False
visited.add(u)
for x in nodes[u]:
if self.dfs(nodes, x, v, visited):
return True
return False
================================================
FILE: leetcode/685_redundant_connection_ii.py
================================================
"""
given input is an directed graph
3 corner cases:
1. There is a loop in the graph, and no vertex has more than 1 parent.
2. A vertex has more than 1 parent, but there isn’t a loop in the graph.
3. A vertex has more than 1 parent, and is part of a loop.
REF: https://leetcode.com/problems/redundant-connection-ii/discuss/108070/Python-O(N)-concise-solution-with-detailed-explanation-passed-updated-testcases
"""
import collections
class Solution:
def findRedundantDirectedConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
ans = edge = None # `edge` is the last edge in a loop
adj = collections.defaultdict(set)
uf = collections.defaultdict(int)
has_parent = set()
for u, v in edges:
adj[u].add(v)
if v in has_parent:
ans = (u, v)
if not self.union(uf, u, v):
edge = (u, v)
has_parent.add(v)
if not ans:
return edge
res = self.dfs(ans[1], adj, set())
return res if res else ans
def union(self, uf, u, v):
a = self.find(uf, u)
b = self.find(uf, v)
if a == b:
return False
uf[b] = a
return True
def find(self, uf, u):
if uf[u] == 0:
uf[u] = u
return u
if uf[u] == u:
return u
uf[u] = self.find(uf, uf[u])
return uf[u]
def dfs(self, u, adj, visited):
# to detect cycle
visited.add(u)
for v in adj[u]:
if v in visited:
return (u, v)
res = self.dfs(v, adj, visited)
if res:
return res
================================================
FILE: leetcode/688_knight_probability_in_chessboard.py
================================================
import collections
class Solution:
"""
DP:
1. init the first pos as 1
2. keep simulate the process and divide the probability
3. sum the values
"""
def knightProbability(self, n, k, r, c):
"""
:type n: int
:type k: int
:type r: int
:type c: int
:rtype: float
"""
dp = collections.defaultdict(int)
dp[r, c] = 1.0
for _ in range(k):
nxt = collections.defaultdict(int)
for x in range(n):
for y in range(n):
for dx, dy in (
(-1, -2),
( 1, -2),
(-2, -1),
( 2, -1),
(-2, 1),
( 2, 1),
(-1, 2),
( 1, 2),
):
_x = x + dx
_y = y + dy
if not (0 <= _x < n and 0 <= _y < n):
continue
nxt[_x, _y] += dp[x, y] / 8.0
dp = nxt
return sum(dp.values())
class Solution:
"""
BFS: TLE
"""
def knightProbability(self, n, k, r, c):
"""
:type n: int
:type k: int
:type r: int
:type c: int
:rtype: float
"""
if n == 1 and k == 0:
return 1.0
queue, _queue = [(r, c)], []
total = 8 ** k
valid = 0
while queue and k:
k -= 1
for x, y in queue:
for dx, dy in (
(-1, -2),
( 1, -2),
(-2, -1),
( 2, -1),
(-2, 1),
( 2, 1),
(-1, 2),
( 1, 2),
):
_x = x + dx
_y = y + dy
if not (0 <= _x < n and 0 <= _y < n):
continue
if k == 0:
valid += 1
if k > 0:
_queue.append((_x, _y))
queue, _queue = _queue, []
return valid / total
================================================
FILE: leetcode/689_maximum_sum_of_3_non_overlapping_subarrays.py
================================================
"""
REF: https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/108231
"""
class Solution:
def maxSumOfThreeSubarrays(self, A, k):
"""
:type A: List[int]
:type k: int
:rtype: List[int]
"""
ans = [-1] * 3
if not A or len(A) < 3 * k:
return ans
n = len(A)
S = [0] * (n + 1) # prefix sum
L = [0] * n # the starting index of the maximum interval sum with length k in [0, i]
R = [n - k] * n # the starting index of the maximum interval sum with length k in [i, n - 1]
for i in range(1, n + 1):
S[i] = S[i - 1] + A[i - 1]
max_sum = S[k] - S[0] # maximum interval sum
_sum = 0
for i in range(k, n):
L[i] = L[i - 1]
_sum = S[i + 1] - S[i + 1 - k]
if _sum > max_sum:
L[i] = i + 1 - k
max_sum = _sum
max_sum = S[n] - S[n - k]
_sum = 0
for i in range(n - k - 1, -1, -1):
R[i] = R[i + 1]
_sum = S[i + k] - S[i]
if _sum >= max_sum:
R[i] = i
max_sum = _sum
max_sum = _sum = 0
for i in range(k, n - 2 * k + 1):
left = L[i - 1]
right = R[i + k]
_sum = S[i + k] - S[i] + S[left + k] - S[left] + S[right + k] - S[right]
if _sum > max_sum:
max_sum = _sum
ans[:] = left, i, right
return ans
================================================
FILE: leetcode/697_degree_of_an_array.py
================================================
class Solution:
def findShortestSubArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
if not A:
return 0
n = len(A)
L, R, C = {}, {}, {}
for i in range(n):
if A[i] not in L:
L[A[i]] = i
R[A[i]] = i
C[A[i]] = C.get(A[i], 0) + 1
ans = len(A)
degree = max(C.values())
for a, c in C.items():
if c == degree and R[a] - L[a] + 1 < ans:
ans = R[a] - L[a] + 1
return ans
================================================
FILE: leetcode/719_find_k_th_smallest_pair_distance.py
================================================
class Solution:
def smallestDistancePair(self, A, k):
"""
:type A: List[int]
:type k: int
:rtype: int
"""
if not A or not k:
return -1
A.sort()
left, right = 0, A[-1] - A[0]
while left + 1 < right:
mid = (left + right) // 2
if self.check_valid(A, mid, k):
right = mid
else:
left = mid
return left if self.check_valid(A, left, k) else right
def check_valid(self, A, mid, k):
"""
valid if there are at least `k` pairs when distance is `mid`
"""
cnt = left = 0
for right in range(len(A)):
while A[right] - A[left] > mid:
left += 1
cnt += right - left
if cnt >= k:
return True
return False
================================================
FILE: leetcode/721_accounts_merge.py
================================================
class Solution:
def accountsMerge(self, A):
"""
:type A: List[List[str]]
:rtype: List[List[str]]
"""
if not A:
return []
M = {} # mails
M2N = {} # mail to name
for L in A:
for i in range(1, len(L)):
M2N[L[i]] = L[0]
self.connect(M, L[i], L[1])
for a in M:
self.find(M, a)
res = {}
for m1, m0 in M.items():
if m0 not in res:
res[m0] = []
res[m0].append(m1)
return [[M2N[m]] + sorted(M) for m, M in res.items()]
def connect(self, N, a, b):
_a = self.find(N, a)
_b = self.find(N, b)
if _a is not _b:
N[_a] = _b
def find(self, N, a):
if a not in N:
N[a] = a
return a
if N[a] is a:
return a
N[a] = self.find(N, N[a])
return N[a]
================================================
FILE: leetcode/734_sentence_similarity.py
================================================
"""
>>> pairs = [['great', 'fine'], ['acting', 'drama'], ['skills', 'talent']]
>>> gotcha = []
>>> s = Solution()
>>> for _in, _out in (
... ((['great', 'acting'], ['fine', 'drama'], pairs), True),
... ((['great', 'acting'], ['fine', 'talent'], pairs), False),
... ((['great'], ['great'], []), True),
... ((['great'], ['fine', 'drama'], pairs), False),
... ):
... res = s.areSentencesSimilar(*_in)
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
import collections
class Solution:
def areSentencesSimilar(self, words1, words2, pairs):
"""
:type words1: List[str]
:type words2: List[str]
:type pairs: List[List[str]]
:rtype: bool
"""
if len(words1) != len(words2):
return False
simils = collections.defaultdict(set)
for a, b in pairs:
simils[a].add(b)
simils[b].add(a)
for i in range(len(words1)):
a = words1[i]
b = words2[i]
if a != b and b not in simils[a]:
return False
return True
================================================
FILE: leetcode/737_sentence_similarity_ii.py
================================================
"""
>>> pairs = [['great', 'fine'], ['acting', 'drama'], ['skills', 'talent']]
>>> gotcha = []
>>> for s in (Solution(), Solution2()):
... for _in, _out in (
... ((['great', 'acting'], ['fine', 'drama'], pairs), True),
... ((['great', 'acting'], ['fine', 'talent'], pairs), False),
... ((['great'], ['great'], []), True),
... ((['great'], ['fine', 'drama'], pairs), False),
... ):
... res = s.areSentencesSimilarTwo(*_in)
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class Solution:
"""
UnionFind
"""
def areSentencesSimilarTwo(self, words1, words2, pairs):
"""
:type words1: List[str]
:type words2: List[str]
:type pairs: List[List[str]]
:rtype: bool
"""
if len(words1) != len(words2):
return False
nodes = {}
for a, b in pairs:
self.union(nodes, a, b)
for i in range(len(words1)):
a = words1[i]
b = words2[i]
_a = self.find(nodes, a)
_b = self.find(nodes, b)
if a != b and _a != _b:
return False
return True
def union(self, nodes, a, b):
_a = self.find(nodes, a)
_b = self.find(nodes, b)
if _a is not _b:
nodes[_a] = _b
return _b
def find(self, nodes, a):
if a not in nodes:
nodes[a] = a
return a
if nodes[a] is a:
return a
nodes[a] = self.find(nodes, nodes[a])
return nodes[a]
import collections
class Solution2:
"""
DFS
"""
def areSentencesSimilarTwo(self, words1, words2, pairs):
"""
:type words1: List[str]
:type words2: List[str]
:type pairs: List[List[str]]
:rtype: bool
"""
if len(words1) != len(words2):
return False
simils = collections.defaultdict(set)
for a, b in pairs:
simils[a].add(b)
simils[b].add(a)
for i in range(len(words1)):
a = words1[i]
b = words2[i]
if a != b and not self.dfs(a, b, simils, set()):
return False
return True
def dfs(self, start, end, simils, path):
# check start and end are connected
if start == end:
return True
if start not in simils or start in path:
return False
path.add(start)
for nxt in simils[start]:
if nxt in path:
continue
res = self.dfs(nxt, end, simils, path)
if res:
return True
path.discard(start)
return False
================================================
FILE: leetcode/744_find_smallest_letter_greater_than_target.py
================================================
class Solution:
def nextGreatestLetter(self, L, target):
"""
:type L: List[str]
:type target: str
:rtype: str
"""
n = len(L)
left, right = 0, n - 1
while left + 1 < right:
mid = (left + right) // 2
if L[mid] <= target:
left = mid
else:
right = mid
if target < L[left]:
return L[left]
if target < L[right]:
return L[right]
return L[0]
================================================
FILE: leetcode/746_min_cost_climbing_stairs.py
================================================
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
if not cost:
return 0
n = len(cost)
"""
`dp[i]` means the min cost to possible to reach previous `i` steps
"""
dp = [0] * (n + 1)
for i in range(2, n + 1):
"""
If you decide to come from some step,
and then pay the fee to the from step
"""
dp[i] = min(
dp[i - 1] + cost[i - 1],
dp[i - 2] + cost[i - 2]
)
return dp[n]
================================================
FILE: leetcode/747_largest_number_at_least_twice_of_others.py
================================================
class Solution:
def dominantIndex(self, A):
"""
:type A: List[int]
:rtype: int
"""
_max = __max = float('-inf')
_max_i = -1
for i in range(len(A)):
if A[i] > _max:
__max = _max
_max = A[i]
_max_i = i
continue
if A[i] > __max:
__max = A[i]
if _max >= __max * 2:
return _max_i
return -1
================================================
FILE: leetcode/748_shortest_completing_word.py
================================================
class Solution:
def shortestCompletingWord(self, P, words):
"""
:type P: str
:type words: List[str]
:rtype: str
"""
ans = ''
if not P or not words:
return ans
p_times = self.get_times(P)
_min_size = float('inf')
for word in words:
times = self.get_times(word)
if len(word) < _min_size and self.is_included(p_times, times):
ans = word
_min_size = len(word)
return ans
def is_included(self, a_times, b_times):
"""True if A is a subset of B"""
for char, times in a_times.items():
if char not in b_times:
return False
if b_times[char] < times:
return False
return True
def get_times(self, word):
times = {}
ord_a = ord('a')
ord_z = ord('z')
for char in word.lower():
if ord_a <= ord(char) <= ord_z:
times[char] = times.get(char, 0) + 1
return times
================================================
FILE: leetcode/749_contain_virus.py
================================================
"""
Test Case:
[[1,1,1], [1,0,1], [1,1,1]]
[[1,1,1,0,0,0,0,0,0], [1,0,1,0,1,1,1,1,1], [1,1,1,0,0,0,0,0,0]]
# In the process of spreading will intersect
[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0],[1,0,0,0,0,0,0,0,0,0],[0,0,1,0,0,0,1,0,0,0],[0,0,0,0,0,0,1,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,1,0],[0,0,0,0,1,0,1,0,0,0],[0,0,0,0,0,0,0,0,0,0]]
# needs to dedup `ex_virus` and `spreading`
[[0,1,0,1,1,1,1,1,1,0],[0,0,0,1,0,0,0,0,0,0],[0,0,1,1,1,0,0,0,1,0],[0,0,0,1,1,0,0,1,1,0],[0,1,0,0,1,0,1,1,0,1],[0,0,0,1,0,1,0,1,1,1],[0,1,0,0,1,0,0,1,1,0],[0,1,0,1,0,0,0,1,1,0],[0,1,1,0,0,1,1,0,0,1],[1,0,1,1,0,1,0,1,0,1]]
"""
class Solution:
NORMAL = 0
VIRUS = 1
EX_VIRUS = -1
V = (
(-1, 0),
( 1, 0),
( 0, -1),
( 0, 1),
)
def containVirus(self, G):
"""
:type G: List[List[int]]
:rtype: int
"""
walls = 0
if not G or not G[0]:
return walls
while True:
_walls = self.build_walls(G)
if _walls == 0:
break
walls += _walls
return walls
def build_walls(self, G):
m, n = len(G), len(G[0])
ex_virus = []
spreading = []
walls = []
visited = [[False] * n for _ in range(m)]
for x in range(m):
for y in range(n):
if G[x][y] == self.VIRUS and not visited[x][y]:
ex_virus.append(set())
spreading.append(set())
walls.append(0)
self.dfs(x, y, G, visited, ex_virus, spreading, walls)
_max_save = _max_i = -1
s = len(spreading)
for i in range(s):
t = len(spreading[i])
if t > _max_save:
_max_save = t
_max_i = i
if _max_save == -1:
return 0
for i in range(s):
if i == _max_i:
for x, y in ex_virus[i]:
G[x][y] = self.EX_VIRUS
else:
for x, y in spreading[i]:
G[x][y] = self.VIRUS
return walls[_max_i]
def dfs(self, x, y, G, visited, ex_virus, spreading, walls):
m, n = len(G), len(G[0])
if not (0 <= x < m and 0 <= y < n) or visited[x][y]:
return
if G[x][y] == self.VIRUS:
visited[x][y] = True
ex_virus[-1].add((x, y))
for dx, dy in self.V:
_x = x + dx
_y = y + dy
self.dfs(_x, _y, G, visited, ex_virus, spreading, walls)
elif G[x][y] == self.NORMAL:
spreading[-1].add((x, y))
walls[-1] += 1
================================================
FILE: leetcode/750_number_of_corner_rectangles.py
================================================
class Solution:
def countCornerRectangles(self, G):
"""
:type G: List[List[int]]
:rtype: int
iterate every row and save all the pairs of 1 in current row
if there is some pair with same indices in passed row
and then we can ensure rectangles exist
note that:
1 pair: 0 rec
2 pairs: 0+1= 1 rec
4 pairs: 0+1+2+3= 6 recs
n pairs: C(n, 2) = n * (n - 1) / 2 = 0+1+2+...+(n-1)
example: 4 pairs => C(4, 2) = 6 recs
1 1
1 1
1 1
1 1
"""
ans = 0
if not G:
return ans
n = 0
count = {}
for R in G:
for end in range(1, len(R)):
if R[end] == 0:
continue
for start in range(end):
if R[start] == 0:
continue
if (start, end) not in count:
count[start, end] = 0
continue
count[start, end] += 1
ans += count[start, end]
return ans
================================================
FILE: leetcode/758_bold_words_in_string.py
================================================
"""
>>> gotcha = []
>>> for s in (Solution(),):
... for _in, _out in (
... (([''], ''), ''),
... ((['abc', '123'], 'abcxyz123'), '<b>abc</b>xyz<b>123</b>'),
... ((['aaa','aab','bc'], 'aaabbcc'), '<b>aaabbc</b>c'),
... ((['ab', 'bc'], 'aabcd'), 'a<b>abc</b>d'),
... ):
... res = s.boldWords(*_in)
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class Solution:
def boldWords(self, words, s):
"""
:type words: List[str]
:type s: str
:rtype: str
"""
if not s or not words:
return ''
TMPL = '<b>{}</b>'
n = len(s)
ans = []
is_bold = [False] * n
left = right = 0
for left in range(n):
for w in words:
size = len(w)
if s[left:left + size] == w and left + size > right:
right = left + size
is_bold[left] = right > left
left = right = 0
while left < n:
if not is_bold[left]:
ans.append(s[left])
left += 1
continue
right = left
while right < n and is_bold[right]:
right += 1
ans.append(TMPL.format(s[left:right]))
left = right # imply left' = left + 1
return ''.join(ans)
================================================
FILE: leetcode/769_max_chunks_to_make_sorted.py
================================================
"""
Main Concept:
given nums: 0, 2, 1, 4, 3, 5, 7, 6
1. the sorted nums is just its index
2. maintain a `M` to record, and `M[i]` means the max in [0:i] in nums
3. if `M[i] == i`, ans += 1
sorted: 0, 1, 2, 3, 4, 5, 6, 7
index: 0, 1, 2, 3, 4, 5, 6, 7
max: 0, 2, 2, 4, 4, 5, 7, 7
ans: 1, 1, 2, 2, 3, 4, 4, 5
chunks: 0| 2, 1| 4, 3| 5| 7, 6
Improvement:
just compare when visit it
space: O(n) -> O(1)
"""
class Solution:
def maxChunksToSorted(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
if not nums:
return ans
_max = 0 # since 0 is the min in nums
for i in range(len(nums)):
_max = max(_max, nums[i])
if _max == i:
ans += 1
return ans
class Solution:
def maxChunksToSorted(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
if not nums:
return ans
n = len(nums)
M = [0] * n # `M[i]` means the max in [0:i] in nums
for i in range(n):
M[i] = nums[i]
if i > 0 and M[i - 1] > M[i]:
M[i] = M[i - 1]
for i in range(n):
if M[i] == i:
ans += 1
return ans
================================================
FILE: leetcode/776_split_bst.py
================================================
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def splitBST(self, root, target):
"""
:type root: TreeNode
:type target: int
:rtype: List[TreeNode]
"""
if not root:
return None, None
if root.val > target:
left, right = self.splitBST(root.left, target)
root.left = right
return left, root
else:
left, right = self.splitBST(root.right, target)
root.right = left
return root, right
================================================
FILE: leetcode/777_swap_adjacent_in_lr_string.py
================================================
class Solution:
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
if len(start) != len(end):
return False
m, n = len(start), len(end)
i = j = 0
while i < m and j < n:
while i < m and start[i] == 'X':
i += 1
while j < n and end[j] == 'X':
j += 1
if i == m and j == n:
return True
if i == m or j == n:
return False
if start[i] != end[j]:
return False
if start[i] == 'L' and j > i:
return False
if start[i] == 'R' and i > j:
return False
i += 1
j += 1
return True
================================================
FILE: leetcode/778_swim_in_rising_water.py
================================================
from heapq import heappush, heappop
class Solution:
def swimInWater(self, G):
"""
:type G: List[List[int]]
:rtype: int
"""
ans = 0
if not G or not G[0]:
return ans
n = len(G)
V = ((-1, 0), (1, 0), (0, -1), (0, 1))
heap = [(G[0][0], 0, 0)]
visited = {(0, 0): True}
while heap:
depth, x, y = heappop(heap)
if depth > ans:
ans = depth
if x == y == n - 1:
return ans
for dx, dy in V:
_x = x + dx
_y = y + dy
if not (0 <= _x < n and 0 <= _y < n):
continue
if (_x, _y) in visited:
continue
visited[_x, _y] = True
heappush(heap, (G[_x][_y], _x, _y))
return ans
================================================
FILE: leetcode/779_k_th_symbol_in_grammar.py
================================================
class Solution:
def kthGrammar(self, N, K):
"""
:type N: int
:type K: int
:rtype: int
"""
if N == 1:
return 0
if K % 2 == 0:
if self.kthGrammar(N - 1, K // 2) == 0:
return 1
else:
return 0
else:
if self.kthGrammar(N - 1, (K + 1) // 2) == 0:
return 0
else:
return 1
================================================
FILE: leetcode/783_minimum_distance_between_bst_nodes.py
================================================
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
"""
Recursion
time: O(n)
space: O(1)
"""
ans = float('inf')
pre = None
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return self.ans
self.minDiffInBST(root.left)
if self.pre and root.val - self.pre.val < self.ans:
self.ans = root.val - self.pre.val
self.pre = root
self.minDiffInBST(root.right)
return self.ans
class Solution:
"""
Iteration
time: O(n)
space: O(n)
"""
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return
ans = float('inf')
pre = None
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if pre and node.val - pre.val < ans:
ans = node.val - pre.val
pre = node
node = node.right
return ans
================================================
FILE: leetcode/784_letter_case_permutation.py
================================================
class Solution:
def letterCasePermutation(self, s):
"""
:type s: str
:rtype: List[str]
"""
if not s:
return ['']
ans = []
self.dfs(s, 0, ans, [])
return ans
def dfs(self, s, i, ans, path):
if i == len(s):
ans.append(''.join(path))
return
options = [s[i]] if s[i].isdigit() else [s[i].lower(), s[i].upper()]
for c in options:
path.append(c)
self.dfs(s, i + 1, ans, path)
path.pop()
================================================
FILE: leetcode/785_is_graph_bipartite.py
================================================
class Solution:
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
color = {}
for node in range(len(graph)):
if node not in color:
color[node] = 0
for nei in graph[node]:
if nei not in color:
color[nei] = color[node] ^ 1
elif color[nei] == color[node]:
return False
return True
================================================
FILE: leetcode/786_k_th_smallest_prime_fraction.py
================================================
"""
Main Concept:
just like found kth smallest num in matrix
example: [1, 2, 5, 7]
7 5 2 1
1 1/7 1/5 1/2 1/1
2 2/7 2/5 ...
5 ...
7 ...
"""
from heapq import heappush, heappop
class Solution:
def kthSmallestPrimeFraction(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
heap = []
n = len(A)
A.sort()
for i in range(n):
heappush(heap, (A[i]/A[-1], i, n - 1))
for _ in range(K - 1):
_, i, j = heappop(heap)
j -= 1
if j >= 0:
heappush(heap, (A[i]/A[j], i, j))
_, i, j = heappop(heap)
return [A[i], A[j]]
================================================
FILE: leetcode/787_cheapest_flights_within_k_stops.py
================================================
class Solution:
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
min_cost = [float('inf')] * n # the minimum cost to get to node
costs = [float('inf')] * n
min_cost[src] = costs[src] = 0
for _ in range(K + 1):
for u, v, cost in flights:
costs[v] = min(costs[v], min_cost[u] + cost)
min_cost = costs
return costs[dst] if costs[dst] < float('inf') else -1
class Solution:
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
if src == dst:
return 0
INF = float('inf')
"""
`dp[i][k]` means the cost when the end is `i` with `k` stop
"""
dp = [[INF] * (K + 1) for _ in range(n)]
dp[src][0] = 0
for start, end, cost in flights:
if start == src and cost < dp[end][0]:
dp[end][0] = cost
for k in range(1, K + 1):
for i in range(n):
dp[i][k] = dp[i][k - 1]
for start, end, cost in flights:
dp[end][k] = min(
dp[end][k],
dp[start][k - 1] + cost
)
return dp[dst][K] if dp[dst][K] < INF else -1
================================================
FILE: leetcode/788_rotated_digits.py
================================================
class Solution:
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
ans = 0
for i in range(1, N + 1):
if self.is_good(i):
ans += 1
return ans
def is_good(self, N):
res = False
while N > 0:
D = N % 10
if D in (3, 4, 7):
return False
if D in (2, 5, 6, 9):
res = True
N = N // 10
return res
================================================
FILE: leetcode
gitextract_pg3fa3pn/
├── .editorconfig
├── .gitignore
├── .travis.yml
├── README.md
├── bin/
│ ├── test_javascript.js
│ └── test_python.py
├── codewars/
│ ├── delete_occurrences_of_an_element_if_it_occurs_more_than_n_times.js
│ ├── double_cola.js
│ ├── iq_test.js
│ ├── is_a_number_prime.js
│ ├── multiply.js
│ ├── rectangle_into_squares.js
│ ├── reverse_words.js
│ ├── simple_encryption_1_alternating_split.js
│ ├── sudoku_solution_validator.js
│ ├── take_a_ten_minute_walk.js
│ ├── tribonacci_sequence.js
│ ├── unique_in_order.js
│ └── who_likes_it.js
├── leetcode/
│ ├── 101_symmetric_tree.py
│ ├── 105_construct_binary_tree_from_preorder_and_inorder_traversal.py
│ ├── 108_convert_sorted_array_to_binary_search_tree.py
│ ├── 112_path_sum.py
│ ├── 113_path_sum_ii.py
│ ├── 116_populating_next_right_pointers_in_each_node.py
│ ├── 117_populating_next_right_pointers_in_each_node_ii.py
│ ├── 118_pascal_s_triangle.py
│ ├── 11_container_with_most_water.py
│ ├── 124_binary_tree_maximum_path_sum.py
│ ├── 134_gas_station.py
│ ├── 136_single_number.py
│ ├── 149_max_points_on_a_line.py
│ ├── 14_longest_common_prefix.py
│ ├── 150_evaluate_reverse_polish_notation.py
│ ├── 157_read_n_characters_given_read4.py
│ ├── 160_intersection_of_two_linked_lists.py
│ ├── 165_compare_version_numbers.py
│ ├── 166_fraction_to_recurring_decimal.py
│ ├── 169_majority_element.py
│ ├── 171_excel_sheet_column_number.py
│ ├── 172_factorial_trailing_zeroes.py
│ ├── 174_dungeon_game.py
│ ├── 179_largest_number.py
│ ├── 17_letter_combinations_of_a_phone_number.py
│ ├── 190_reverse_bits.py
│ ├── 191_number_of_1_bits.py
│ ├── 19_remove_nth_node_from_end_of_list.py
│ ├── 202_happy_number.py
│ ├── 204_count_primes.py
│ ├── 208_implement_trie_prefix_tree.py
│ ├── 20_valid_parentheses.py
│ ├── 215_kth_largest_element_in_an_array.py
│ ├── 217_contains_duplicate.py
│ ├── 218_the_skyline_problem.py
│ ├── 224_basic_calculator.py
│ ├── 227_basic_calculator_ii.py
│ ├── 229_majority_element_ii.py
│ ├── 22_generate_parentheses.py
│ ├── 230_kth_smallest_element_in_a_bst.py
│ ├── 234_palindrome_linked_list.py
│ ├── 235_lowest_common_ancestor_of_a_binary_search_tree.py
│ ├── 236_lowest_common_ancestor_of_a_binary_tree.py
│ ├── 237_delete_node_in_a_linked_list.py
│ ├── 242_valid_anagram.py
│ ├── 269_alien_dictionary.py
│ ├── 277_find_the_celebrity.py
│ ├── 280_wiggle_sort.py
│ ├── 282_expression_add_operators.py
│ ├── 285_inorder_successor_in_bst.py
│ ├── 288_unique_word_abbreviation.py
│ ├── 289_game_of_life.py
│ ├── 295_find_median_from_data_stream.py
│ ├── 299_bulls_and_cows.py
│ ├── 303_range_sum_query_immutable.py
│ ├── 304_range_sum_query_2d_immutable.py
│ ├── 307_range_sum_query_mutable.py
│ ├── 308_range_sum_query_2d_mutable.py
│ ├── 30_substring_with_concatenation_of_all_words.py
│ ├── 315_count_of_smaller_numbers_after_self.py
│ ├── 323_number_of_connected_components_in_an_undirected_graph.py
│ ├── 324_wiggle_sort_ii.py
│ ├── 326_power_of_three.py
│ ├── 329_longest_increasing_path_in_a_matrix.py
│ ├── 334_increasing_triplet_subsequence.py
│ ├── 33_search_in_rotated_sorted_array.py
│ ├── 340_longest_substring_with_at_most_k_distinct_characters.py
│ ├── 344_reverse_string.py
│ ├── 347_top_k_frequent_elements.py
│ ├── 348_design_tic_tac_toe.py
│ ├── 353_design_snake_game.py
│ ├── 36_valid_sudoku.py
│ ├── 377_combination_sum_iv.py
│ ├── 378_kth_smallest_element_in_a_sorted_matrix.py
│ ├── 37_sudoku_solver.py
│ ├── 380_insert_delete_getrandom_o1.py
│ ├── 381_insert_delete_getrandom_o1_duplicates_allowed.py
│ ├── 382_linked_list_random_node.py
│ ├── 384_shuffle_an_array.py
│ ├── 386_lexicographical_numbers.py
│ ├── 387_first_unique_character_in_a_string.py
│ ├── 388_longest_absolute_file_path.py
│ ├── 389_find_the_difference.py
│ ├── 38_count_and_say.py
│ ├── 390_elimination_game.py
│ ├── 391_perfect_rectangle.py
│ ├── 395_longest_substring_with_at_least_k_repeating_characters.py
│ ├── 398_random_pick_index.py
│ ├── 399_evaluate_division.py
│ ├── 406_queue_reconstruction_by_height.py
│ ├── 416_partition_equal_subset_sum.py
│ ├── 417_pacific_atlantic_water_flow.py
│ ├── 41_first_missing_positive.py
│ ├── 437_path_sum_iii.py
│ ├── 454_4sum_ii.py
│ ├── 461_hamming_distance.py
│ ├── 480_sliding_window_median.py
│ ├── 486_predict_the_winner.py
│ ├── 48_rotate_image.py
│ ├── 490_the_maze.py
│ ├── 494_target_sum.py
│ ├── 499_the_maze_iii.py
│ ├── 505_the_maze_ii.py
│ ├── 518_coin_change_2.py
│ ├── 51_n_queens.py
│ ├── 524_longest_word_in_dictionary_through_deleting.py
│ ├── 52_n_queens_ii.py
│ ├── 530_minimum_absolute_difference_in_bst.py
│ ├── 542_01_matrix.py
│ ├── 54_spiral_matrix.py
│ ├── 592_fraction_addition_and_subtraction.py
│ ├── 593_valid_square.py
│ ├── 59_spiral_matrix_ii.py
│ ├── 5_longest_palindromic_substring.py
│ ├── 616_add_bold_tag_in_string.py
│ ├── 643_maximum_average_subarray_i.py
│ ├── 66_plus_one.py
│ ├── 676_implement_magic_dictionary.py
│ ├── 679_24_game.py
│ ├── 681_next_closest_time.py
│ ├── 682_baseball_game.py
│ ├── 683_k_empty_slots.py
│ ├── 684_redundant_connection.py
│ ├── 685_redundant_connection_ii.py
│ ├── 688_knight_probability_in_chessboard.py
│ ├── 689_maximum_sum_of_3_non_overlapping_subarrays.py
│ ├── 697_degree_of_an_array.py
│ ├── 719_find_k_th_smallest_pair_distance.py
│ ├── 721_accounts_merge.py
│ ├── 734_sentence_similarity.py
│ ├── 737_sentence_similarity_ii.py
│ ├── 744_find_smallest_letter_greater_than_target.py
│ ├── 746_min_cost_climbing_stairs.py
│ ├── 747_largest_number_at_least_twice_of_others.py
│ ├── 748_shortest_completing_word.py
│ ├── 749_contain_virus.py
│ ├── 750_number_of_corner_rectangles.py
│ ├── 758_bold_words_in_string.py
│ ├── 769_max_chunks_to_make_sorted.py
│ ├── 776_split_bst.py
│ ├── 777_swap_adjacent_in_lr_string.py
│ ├── 778_swim_in_rising_water.py
│ ├── 779_k_th_symbol_in_grammar.py
│ ├── 783_minimum_distance_between_bst_nodes.py
│ ├── 784_letter_case_permutation.py
│ ├── 785_is_graph_bipartite.py
│ ├── 786_k_th_smallest_prime_fraction.py
│ ├── 787_cheapest_flights_within_k_stops.py
│ ├── 788_rotated_digits.py
│ ├── 789_escape_the_ghosts.py
│ ├── 790_domino_and_tromino_tiling.py
│ ├── 791_custom_sort_string.py
│ ├── 7_reverse_integer.py
│ ├── 81_search_in_rotated_sorted_array_ii.py
│ └── 8_string_to_integer_atoi.py
├── lintcode/
│ ├── 102_linked_list_cycle.py
│ ├── 103_linked_list_cycle_ii.py
│ ├── 104_merge_k_sorted_lists.py
│ ├── 105_copy_list_with_random_pointer.py
│ ├── 107_word_break.py
│ ├── 108_palindrome_partitioning_ii.py
│ ├── 109_triangle.py
│ ├── 10_string_permutation_ii.py
│ ├── 110_minimum_path_sum.py
│ ├── 111_climbing_stairs.py
│ ├── 114_unique_paths.py
│ ├── 115_unique_paths_ii.py
│ ├── 116_jump_game.py
│ ├── 117_jump_game_ii.py
│ ├── 118_distinct_subsequences.py
│ ├── 119_edit_distance.py
│ ├── 11_search_range_in_binary_search_tree.py
│ ├── 120_word_ladder.py
│ ├── 121_word_ladder_ii.py
│ ├── 122_largest_rectangle_in_histogram.py
│ ├── 123_word_search.py
│ ├── 124_longest_consecutive_sequence.py
│ ├── 125_backpack_ii.py
│ ├── 126_max_tree.py
│ ├── 127_topological_sorting.py
│ ├── 128_hash_function.py
│ ├── 129_rehashing.py
│ ├── 12_min_stack.py
│ ├── 130_heapify.py
│ ├── 131_building_outline.py
│ ├── 132_word_search_ii.py
│ ├── 134_lru_cache.py
│ ├── 135_combination_sum.py
│ ├── 1365_minimum_cycle_section.py
│ ├── 1366_directed_graph_loop.py
│ ├── 1367_police_distance.py
│ ├── 1368_same_number.py
│ ├── 136_palindrome_partitioning.py
│ ├── 137_clone_graph.py
│ ├── 138_subarray_sum.py
│ ├── 139_subarray_sum_closest.py
│ ├── 13_strstr.py
│ ├── 141_sqrtx.py
│ ├── 142_o1_check_power_of_2.py
│ ├── 143_sort_colors_ii.py
│ ├── 148_sort_colors.py
│ ├── 149_best_time_to_buy_and_sell_stock.py
│ ├── 14_first_position_of_target.py
│ ├── 150_best_time_to_buy_and_sell_stock_ii.py
│ ├── 151_best_time_to_buy_and_sell_stock_iii.py
│ ├── 153_combination_sum_ii.py
│ ├── 154_regular_expression_matching.py
│ ├── 155_minimum_depth_of_binary_tree.py
│ ├── 156_merge_intervals.py
│ ├── 158_two_strings_are_anagrams.py
│ ├── 159_find_minimum_in_rotated_sorted_array.py
│ ├── 15_permutations.py
│ ├── 160_find_minimum_in_rotated_sorted_array_ii.py
│ ├── 165_merge_two_sorted_lists.py
│ ├── 167_add_two_numbers.py
│ ├── 168_burst_balloons.py
│ ├── 16_permutations_ii.py
│ ├── 171_anagrams.py
│ ├── 175_invert_binary_tree.py
│ ├── 178_graph_valid_tree.py
│ ├── 17_subsets.py
│ ├── 183_wood_cut.py
│ ├── 18_subsets_ii.py
│ ├── 190_next_permutation_ii.py
│ ├── 191_maximum_product_subarray.py
│ ├── 192_wildcard_matching.py
│ ├── 196_find_the_missing_number.py
│ ├── 197_permutation_index.py
│ ├── 198_permutation_index_ii.py
│ ├── 1_a_b_problem.py
│ ├── 204_singleton.py
│ ├── 211_string_permutation.py
│ ├── 215_rate_limiter.py
│ ├── 221_add_two_numbers_ii.py
│ ├── 231_typeahead.py
│ ├── 232_tiny_url.py
│ ├── 234_webpage_crawler.py
│ ├── 236_swap_bits.py
│ ├── 242_convert_binary_tree_to_linked_lists_by_depth.py
│ ├── 243_amicable_pair
│ ├── 245_subtree.py
│ ├── 246_binary_tree_path_sum_ii.py
│ ├── 24_lfu_cache.py
│ ├── 254_drop_eggs.py
│ ├── 272_climbing_stairs_ii.py
│ ├── 28_search_a_2d_matrix.py
│ ├── 29_interleaving_string.py
│ ├── 30_insert_interval.py
│ ├── 31_partition_array.py
│ ├── 32_minimum_window_substring.py
│ ├── 35_reverse_linked_list.py
│ ├── 360_sliding_window_median.py
│ ├── 362_sliding_window_maximum.py
│ ├── 363_trapping_rain_water.py
│ ├── 364_trapping_rain_water_ii.py
│ ├── 368_expression_evaluation.py
│ ├── 36_reverse_linked_list_ii.py
│ ├── 376_binary_tree_path_sum.py
│ ├── 378_convert_binary_search_tree_to_doubly_linked_list.py
│ ├── 382_triangle_count.py
│ ├── 384_longest_substring_without_repeating_characters.py
│ ├── 386_longest_substring_with_at_most_k_distinct_characters.py
│ ├── 38_search_a_2d_matrix_ii.py
│ ├── 390_find_peak_element_ii.py
│ ├── 391_number_of_airplanes_in_the_sky.py
│ ├── 392_house_robber.py
│ ├── 393_best_time_to_buy_and_sell_stock_iv.py
│ ├── 394_coins_in_a_line.py
│ ├── 395_coins_in_a_line_ii.py
│ ├── 396_coins_in_a_line_iii.py
│ ├── 397_longest_increasing_continuous_subsequence.py
│ ├── 3_digit_counts.py
│ ├── 401_kth_smallest_number_in_sorted_matrix.py
│ ├── 402_continuous_subarray_sum.py
│ ├── 406_minimum_size_subarray_sum.py
│ ├── 40_implement_queue_by_two_stacks.py
│ ├── 414_divide_two_integers.py
│ ├── 415_valid_palindrome.py
│ ├── 417_valid_number.py
│ ├── 418_integer_to_roman.py
│ ├── 419_roman_to_integer.py
│ ├── 41_maximum_subarray.py
│ ├── 42_maximum_subarray_ii.py
│ ├── 430_scramble_string.py
│ ├── 431_connected_component_in_undirected_graph.py
│ ├── 432_find_the_weak_connected_component_in_the_directed_graph.py
│ ├── 433_number_of_islands.py
│ ├── 434_number_of_islands_ii.py
│ ├── 437_copy_books.py
│ ├── 43_maximum_subarray_iii.py
│ ├── 440_backpack_iii.py
│ ├── 442_implement_trie.py
│ ├── 443_two_sum_greater_than_target.py
│ ├── 447_search_in_a_big_sorted_array.py
│ ├── 450_reverse_nodes_in_k_group.py
│ ├── 453_flatten_binary_tree_to_linked_list.py
│ ├── 457_classical_binary_search.py
│ ├── 458_last_position_of_target.py
│ ├── 459_closest_number_in_sorted_array.py
│ ├── 45_maximum_subarray_difference.py
│ ├── 460_k_closest_numbers_in_sorted_array.py
│ ├── 461_kth_smallest_numbers_in_unsorted_array.py
│ ├── 462_total_occurrence_of_target.py
│ ├── 465_kth_smallest_sum_in_two_sorted_arrays.py
│ ├── 469_identical_binary_tree.py
│ ├── 471_top_k_frequent_words.py
│ ├── 472_binary_tree_path_sum_iii.py
│ ├── 473_add_and_search_word.py
│ ├── 474_lowest_common_ancestor_ii.py
│ ├── 475_binary_tree_maximum_path_sum_ii.py
│ ├── 479_second_max_of_array.py
│ ├── 480_binary_tree_paths.py
│ ├── 486_merge_k_sorted_arrays.py
│ ├── 494_implement_stack_by_two_queues.py
│ ├── 496_toy_factory.py
│ ├── 497_shape_factory.py
│ ├── 498_parking_lot.py
│ ├── 499_word_count.py
│ ├── 4_ugly_number_ii.py
│ ├── 500_inverted_index.py
│ ├── 501_mini_twitter.py
│ ├── 502_mini_cassandra.py
│ ├── 503_anagram_map_reduce.py
│ ├── 504_inverted_index_map_reduce.py
│ ├── 505_web_logger.py
│ ├── 509_mini_yelp.py
│ ├── 510_maximal_rectangle.py
│ ├── 512_decode_ways.py
│ ├── 513_perfect_squares.py
│ ├── 515_paint_house.py
│ ├── 516_paint_house_ii.py
│ ├── 517_ugly_number.py
│ ├── 518_super_ugly_number.py
│ ├── 519_consistent_hashing.py
│ ├── 51_previous_permutation.py
│ ├── 520_consistent_hashing_ii.py
│ ├── 521_remove_duplicate_numbers_in_array.py
│ ├── 522_tiny_url_ii.py
│ ├── 523_url_parser.py
│ ├── 525_mini_uber.py
│ ├── 526_load_balancer.py
│ ├── 527_trie_serialization.py
│ ├── 528_flatten_nested_list_iterator.py
│ ├── 529_geohash.py
│ ├── 52_next_permutation.py
│ ├── 530_geohash_ii.py
│ ├── 531_six_degrees.py
│ ├── 532_reverse_pairs.py
│ ├── 533_two_sum_closest_to_target.py
│ ├── 534_house_robber_ii.py
│ ├── 538_memcache.py
│ ├── 539_move_zeroes.py
│ ├── 53_reverse_words_in_a_string.py
│ ├── 540_zigzag_iterator.py
│ ├── 541_zigzag_iterator_ii.py
│ ├── 543_kth_largest_in_n_arrays.py
│ ├── 544_top_k_largest_numbers.py
│ ├── 545_top_k_largest_numbers_ii.py
│ ├── 547_intersection_of_two_arrays.py
│ ├── 548_intersection_of_two_arrays_ii.py
│ ├── 54_string_to_integer_ii.py
│ ├── 551_nested_list_weight_sum.py
│ ├── 552_create_maximum_number.py
│ ├── 553_bomb_enemy.py
│ ├── 555_counting_bloom_filter.py
│ ├── 556_standard_bloom_filter.py
│ ├── 559_trie_service.py
│ ├── 560_friendship_service.py
│ ├── 563_backpack_v.py
│ ├── 564_backpack_vi.py
│ ├── 565_heart_beat.py
│ ├── 566_gfs_client.py
│ ├── 56_two_sum.py
│ ├── 573_build_post_office_ii.py
│ ├── 574_build_post_office.py
│ ├── 575_expression_expand.py
│ ├── 578_lowest_common_ancestor_iii.py
│ ├── 57_3sum.py
│ ├── 582_word_break_ii.py
│ ├── 584_drop_eggs_ii.py
│ ├── 585_maximum_number_in_mountain_sequence.py
│ ├── 586_sqrtx_ii.py
│ ├── 587_two_sum_unique_pairs.py
│ ├── 589_connecting_graph.py
│ ├── 58_4sum.py
│ ├── 590_connecting_graph_ii.py
│ ├── 591_connecting_graph_iii.py
│ ├── 594_strstr_ii.py
│ ├── 595_binary_tree_longest_consecutive_sequence.py
│ ├── 596_minimum_subtree.py
│ ├── 597_subtree_with_maximum_average.py
│ ├── 598_zombie_in_matrix.py
│ ├── 599_insert_into_a_cyclic_sorted_list.py
│ ├── 59_3sum_closest.py
│ ├── 5_kth_largest_element.py
│ ├── 600_smallest_rectangle_enclosing_black_pixels.py
│ ├── 601_flatten_2d_vector.py
│ ├── 602_russian_doll_envelopes.py
│ ├── 603_largest_divisible_subset.py
│ ├── 604_window_sum.py
│ ├── 605_sequence_reconstruction.py
│ ├── 606_kth_largest_element_ii.py
│ ├── 607_two_sum_data_structure_design.py
│ ├── 608_two_sum_input_array_is_sorted.py
│ ├── 609_two_sum_less_than_or_equal_to_target.py
│ ├── 610_two_sum_difference_equals_to_target.py
│ ├── 611_knight_shortest_path.py
│ ├── 612_k_closest_points.py
│ ├── 613_high_five.py
│ ├── 614_binary_tree_longest_consecutive_sequence_ii.py
│ ├── 615_course_schedule.py
│ ├── 616_course_schedule_ii.py
│ ├── 617_maximum_average_subarray.py
│ ├── 618_search_graph_nodes.py
│ ├── 619_binary_tree_longest_consecutive_sequence_iii.py
│ ├── 61_search_for_a_range.py
│ ├── 620_maximum_subarray_iv.py
│ ├── 621_maximum_subarray_v.py
│ ├── 622_frog_jump.py
│ ├── 623_k_edit_distance.py
│ ├── 624_remove_substrings.py
│ ├── 625_partition_array_ii.py
│ ├── 630_knight_shortest_path_ii.py
│ ├── 633_find_the_duplicate_number.py
│ ├── 634_word_squares.py
│ ├── 635_boggle_game.py
│ ├── 636_132_pattern.py
│ ├── 646_first_position_unique_character.py
│ ├── 647_substring_anagrams.py
│ ├── 64_merge_sorted_array.py
│ ├── 654_sparse_matrix_multiplication.py
│ ├── 655_big_integer_addition.py
│ ├── 656_big_integer_multiplication.py
│ ├── 65_median_of_two_sorted_arrays.py
│ ├── 662_guess_number_game.py
│ ├── 664_counting_bits.py
│ ├── 667_longest_palindromic_subsequence.py
│ ├── 668_ones_and_zeroes.py
│ ├── 669_coin_change.py
│ ├── 66_binary_tree_preorder_traversal.py
│ ├── 676_decode_ways_ii.py
│ ├── 67_binary_tree_inorder_traversal.py
│ ├── 689_two_sum_bst_edtion.py
│ ├── 68_binary_tree_postorder_traversal.py
│ ├── 69_binary_tree_level_order_traversal.py
│ ├── 6_merge_two_sorted_arrays.py
│ ├── 70_binary_tree_level_order_traversal_ii.py
│ ├── 717_tree_longest_path_with_same_value.py
│ ├── 718_repeat_string.py
│ ├── 71_binary_tree_zigzag_level_order_traversal.py
│ ├── 724_minimum_partition.py
│ ├── 725_boolean_parenthesization.py
│ ├── 729_last_digit_by_factorial_divide.py
│ ├── 745_palindromic_ranges.py
│ ├── 74_first_bad_version.py
│ ├── 752_rogue_knight_sven.py
│ ├── 75_find_peak_element.py
│ ├── 76_longest_increasing_subsequence.py
│ ├── 772_group_anagrams.py
│ ├── 775_palindrome_pairs.py
│ ├── 776_strobogrammatic_number_ii.py
│ ├── 77_longest_common_subsequence.py
│ ├── 784_the_longest_common_prefix_ii.py
│ ├── 790_parser.py
│ ├── 791_merge_number.py
│ ├── 792_kth_prime_number.py
│ ├── 793_intersection_of_arrays.py
│ ├── 7_binary_tree_serialization.py
│ ├── 813_find_anagram_mappings.py
│ ├── 81_data_stream_median.py
│ ├── 823_input_stream.py
│ ├── 824_single_number_iv.py
│ ├── 826_computer_maintenance.py
│ ├── 830_string_sort.py
│ ├── 831_3sum_ii.py
│ ├── 832_count_negative_number.py
│ ├── 833_process_sequence.py
│ ├── 85_insert_node_in_a_binary_search_tree.py
│ ├── 86_binary_search_tree_iterator.py
│ ├── 87_remove_node_in_binary_search_tree.py
│ ├── 88_lowest_common_ancestor.py
│ ├── 89_k_sum.py
│ ├── 8_rotate_string.py
│ ├── 900_closest_binary_search_tree_value.py
│ ├── 901_closest_binary_search_tree_value_ii.py
│ ├── 919_meeting_rooms_ii.py
│ ├── 920_meeting_rooms.py
│ ├── 92_backpack.py
│ ├── 93_balanced_binary_tree.py
│ ├── 95_validate_binary_search_tree.py
│ ├── 96_partition_list.py
│ ├── 97_maximum_depth_of_binary_tree.py
│ ├── 98_sort_list.py
│ └── 9_fizz_buzz.py
├── other/
│ ├── anti_queue_reconstruction_by_height.py
│ ├── binary_tree_maximum_path_product.py
│ ├── candy_crush.py
│ ├── card_shuffler.py
│ ├── deep_fetch.js
│ ├── deep_fetch.test.js
│ ├── find_treasure_in_maze.py
│ ├── find_ways_in_board_game.py
│ ├── freq_iterator.py
│ ├── gcd_and_lcm.py
│ ├── get_most_popular_word.py
│ ├── guess_secret.py
│ ├── inorder_non_threaded_binary_tree_traversal.py
│ ├── is_valid_relation.py
│ ├── merge_mail.py
│ ├── reservation.py
│ ├── robot_cleaner.py
│ ├── snake_and_ladder_problem.py
│ ├── stock_stream.py
│ ├── string_abbreviation.py
│ ├── the_point_inside_polygon.py
│ ├── uneven_random_get.py
│ ├── unique_paths_with_followups.py
│ ├── unique_word_abbreviation_ii.py
│ └── upside_down_numbers.py
├── pramp/
│ ├── array_index_and_element_equality.py
│ ├── array_of_array_products.py
│ ├── award_budget_cuts.py
│ ├── bracket_match.py
│ ├── busiest_time_in_the_mall.py
│ ├── decrypt_message.py
│ ├── deletion_distance.py
│ ├── drone_flight_planner.py
│ ├── find_the_duplicates.py
│ ├── flatten_a_dictionary.py
│ ├── h_tree_construction.py
│ ├── k_messed_array_sort.py
│ ├── largest_smaller_bst_node.py
│ ├── number_of_paths.py
│ ├── pairs_with_specific_difference.py
│ ├── pancake_sort.py
│ ├── root_of_number.py
│ ├── sales_path.py
│ ├── sentence_reverse.py
│ ├── smallest_substring_of_all_characters.py
│ ├── time_planner.py
│ └── word_count_engine.py
└── topic/
├── README.md
├── _test/
│ └── python/
│ ├── __init__.py
│ └── test_base.py
├── balanced_search_tree/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ └── red_black_tree.py
├── bit_manipulation/
│ ├── README.md
│ └── python/
│ ├── __init__.py
│ ├── calculator_in_bit.py
│ └── calculator_in_bit__test.py
├── complexity_analysis.md
├── dynamic_programming/
│ └── README.md
├── graph/
│ ├── README.md
│ └── python/
│ ├── __init__.py
│ ├── union_find.py
│ └── union_find__test.py
├── hash/
│ └── python/
│ ├── __init__.py
│ ├── geohash.py
│ ├── geohash__test.py
│ ├── hashtable.py
│ └── hashtable__test.py
├── heap/
│ └── python/
│ ├── __init__.py
│ ├── binary_hash_heap.py
│ ├── binary_heap.py
│ ├── heap__test.py
│ ├── lazy_removable_heapq.py
│ └── removable_heapq.py
├── language/
│ ├── javascript/
│ │ ├── README.md
│ │ └── traversal.md
│ ├── php/
│ │ └── README.md
│ ├── python/
│ │ ├── README.md
│ │ ├── matrix.md
│ │ ├── runtime_of_builtins.md
│ │ └── traversal.md
│ └── sql/
│ └── README.md
├── linked_list/
│ ├── README.md
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── cyclic_doubly_list.py
│ ├── cyclic_list.py
│ ├── dummy_tail_doubly_list.py
│ ├── dummy_tail_list.py
│ ├── head_tail_doubly_list.py
│ ├── head_tail_list.py
│ ├── linked_list__test.py
│ ├── two_dummy_doubly_list.py
│ └── two_dummy_list.py
├── problem_set/
│ ├── subarray_sum.md
│ └── substring_with_distinct_characters.md
├── range_query/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── binary_indexed_tree.py
│ ├── interval_tree.py
│ ├── prefix_sum.py
│ ├── range_tree.py
│ └── segment_tree.py
├── searching/
│ ├── binary_search.md
│ └── python/
│ ├── __init__.py
│ └── _helper.py
├── sorting/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── merge_sort.py
│ ├── quick_sort.py
│ └── sorting__test.py
├── system_design/
│ └── latency.md
├── traversal/
│ └── python/
│ ├── __init__.py
│ ├── _helper.py
│ ├── binary_tree_traversal__test.py
│ ├── iterative_traversal.py
│ ├── morris_traversal.py
│ └── recursive_traversal.py
└── tree/
├── binary_tree.md
└── python/
├── __init__.py
├── _helper.py
├── binary_tree.py
├── binary_tree__test.py
├── trie.py
└── trie__test.py
SYMBOL INDEX (2088 symbols across 591 files)
FILE: bin/test_python.py
function get_unittests (line 17) | def get_unittests(dirname):
function get_doctests (line 39) | def get_doctests(dirname):
FILE: codewars/delete_occurrences_of_an_element_if_it_occurs_more_than_n_times.js
function deleteNth (line 1) | function deleteNth(nums, n) {
FILE: codewars/double_cola.js
function whoIsNext (line 1) | function whoIsNext(names, r) {
FILE: codewars/iq_test.js
function iqTest (line 1) | function iqTest(nums) {
FILE: codewars/is_a_number_prime.js
function isPrime (line 1) | function isPrime(num) {
FILE: codewars/multiply.js
function multiply (line 1) | function multiply(a, b) {
FILE: codewars/rectangle_into_squares.js
function sqInRect (line 1) | function sqInRect(lng, wdth) {
FILE: codewars/reverse_words.js
function reverseWords (line 1) | function reverseWords(s) {
FILE: codewars/simple_encryption_1_alternating_split.js
function encrypt (line 1) | function encrypt(text, n) {
function decrypt (line 23) | function decrypt(text, n) {
FILE: codewars/sudoku_solution_validator.js
function validSolution (line 1) | function validSolution(board) {
FILE: codewars/take_a_ten_minute_walk.js
function isValidWalk (line 1) | function isValidWalk(walk) {
FILE: codewars/tribonacci_sequence.js
function tribonacci (line 1) | function tribonacci(signature, n) {
FILE: codewars/unique_in_order.js
function uniqueInOrder (line 1) | function uniqueInOrder(iterable) {
FILE: codewars/who_likes_it.js
function likes (line 1) | function likes(names) {
FILE: leetcode/101_symmetric_tree.py
class Solution (line 11) | class Solution:
method isSymmetric (line 12) | def isSymmetric(self, root):
method divide_conquer (line 22) | def divide_conquer(self, left, right):
FILE: leetcode/105_construct_binary_tree_from_preorder_and_inorder_traversal.py
class Solution (line 9) | class Solution(object):
method buildTree (line 10) | def buildTree(self, P, I):
FILE: leetcode/108_convert_sorted_array_to_binary_search_tree.py
class Solution (line 9) | class Solution:
method sortedArrayToBST (line 10) | def sortedArrayToBST(self, nums):
FILE: leetcode/112_path_sum.py
class Solution (line 11) | class Solution:
method hasPathSum (line 12) | def hasPathSum(self, root, target):
FILE: leetcode/113_path_sum_ii.py
class Solution (line 11) | class Solution:
method pathSum (line 12) | def pathSum(self, root, target):
method dfs (line 27) | def dfs(self, node, remaining, ans, path):
FILE: leetcode/116_populating_next_right_pointers_in_each_node.py
class Solution (line 12) | class Solution:
method connect (line 16) | def connect(self, root):
method connect (line 40) | def connect(self, root):
class Solution (line 36) | class Solution:
method connect (line 16) | def connect(self, root):
method connect (line 40) | def connect(self, root):
FILE: leetcode/117_populating_next_right_pointers_in_each_node_ii.py
class Solution (line 12) | class Solution:
method connect (line 18) | def connect(self, root):
method connect (line 53) | def connect(self, root):
method connect (line 86) | def connect(self, root):
class Solution (line 49) | class Solution:
method connect (line 18) | def connect(self, root):
method connect (line 53) | def connect(self, root):
method connect (line 86) | def connect(self, root):
class Solution (line 82) | class Solution:
method connect (line 18) | def connect(self, root):
method connect (line 53) | def connect(self, root):
method connect (line 86) | def connect(self, root):
FILE: leetcode/118_pascal_s_triangle.py
class Solution (line 1) | class Solution:
method generate (line 2) | def generate(self, num_rows):
method generate (line 26) | def generate(self, num_rows):
class Solution (line 25) | class Solution:
method generate (line 2) | def generate(self, num_rows):
method generate (line 26) | def generate(self, num_rows):
FILE: leetcode/11_container_with_most_water.py
class Solution (line 1) | class Solution:
method maxArea (line 2) | def maxArea(self, H):
FILE: leetcode/124_binary_tree_maximum_path_sum.py
class Solution (line 11) | class Solution:
method maxPathSum (line 12) | def maxPathSum(self, root):
method divide_conquer (line 23) | def divide_conquer(self, node):
method maxPathSum (line 38) | def maxPathSum(self, root):
method divide_conquer (line 50) | def divide_conquer(self, node):
class Solution (line 37) | class Solution:
method maxPathSum (line 12) | def maxPathSum(self, root):
method divide_conquer (line 23) | def divide_conquer(self, node):
method maxPathSum (line 38) | def maxPathSum(self, root):
method divide_conquer (line 50) | def divide_conquer(self, node):
FILE: leetcode/134_gas_station.py
class Solution (line 1) | class Solution:
method canCompleteCircuit (line 7) | def canCompleteCircuit(self, gas, cost):
method canCompleteCircuit (line 36) | def canCompleteCircuit(self, gas, cost):
class Solution (line 32) | class Solution:
method canCompleteCircuit (line 7) | def canCompleteCircuit(self, gas, cost):
method canCompleteCircuit (line 36) | def canCompleteCircuit(self, gas, cost):
FILE: leetcode/136_single_number.py
class Solution (line 1) | class Solution:
method singleNumber (line 2) | def singleNumber(self, nums):
FILE: leetcode/149_max_points_on_a_line.py
class Solution (line 8) | class Solution:
method maxPoints (line 9) | def maxPoints(self, P):
method get_gcd (line 48) | def get_gcd(self, a, b):
FILE: leetcode/14_longest_common_prefix.py
class Solution (line 1) | class Solution:
method longestCommonPrefix (line 2) | def longestCommonPrefix(self, strs):
FILE: leetcode/150_evaluate_reverse_polish_notation.py
class Solution (line 1) | class Solution:
method evalRPN (line 2) | def evalRPN(self, E):
FILE: leetcode/157_read_n_characters_given_read4.py
class Solution (line 11) | class Solution:
method read (line 12) | def read(self, buf, n):
function read4 (line 43) | def read4(buf):
FILE: leetcode/160_intersection_of_two_linked_lists.py
class Solution (line 8) | class Solution(object):
method getIntersectionNode (line 9) | def getIntersectionNode(self, A, B):
FILE: leetcode/165_compare_version_numbers.py
class Solution (line 1) | class Solution:
method compareVersion (line 2) | def compareVersion(self, version1, version2):
method get_int (line 30) | def get_int(self, s):
FILE: leetcode/166_fraction_to_recurring_decimal.py
class Solution (line 1) | class Solution:
method fractionToDecimal (line 2) | def fractionToDecimal(self, a, b):
FILE: leetcode/169_majority_element.py
class Solution (line 1) | class Solution:
method majorityElement (line 2) | def majorityElement(self, nums):
method majorityElement (line 25) | def majorityElement(self, nums):
method majorityElement (line 39) | def majorityElement(self, nums):
class Solution (line 24) | class Solution:
method majorityElement (line 2) | def majorityElement(self, nums):
method majorityElement (line 25) | def majorityElement(self, nums):
method majorityElement (line 39) | def majorityElement(self, nums):
class Solution (line 38) | class Solution:
method majorityElement (line 2) | def majorityElement(self, nums):
method majorityElement (line 25) | def majorityElement(self, nums):
method majorityElement (line 39) | def majorityElement(self, nums):
FILE: leetcode/171_excel_sheet_column_number.py
class Solution (line 1) | class Solution:
method titleToNumber (line 2) | def titleToNumber(self, s):
FILE: leetcode/172_factorial_trailing_zeroes.py
class Solution (line 1) | class Solution:
method trailingZeroes (line 2) | def trailingZeroes(self, n):
FILE: leetcode/174_dungeon_game.py
class Solution (line 1) | class Solution:
method calculateMinimumHP (line 2) | def calculateMinimumHP(self, G):
FILE: leetcode/179_largest_number.py
class LgSort (line 6) | class LgSort(str):
method __lt__ (line 7) | def __lt__(a, b):
class Solution (line 11) | class Solution:
method largestNumber (line 12) | def largestNumber(self, A):
FILE: leetcode/17_letter_combinations_of_a_phone_number.py
class Solution (line 1) | class Solution:
method letterCombinations (line 2) | def letterCombinations(self, s):
FILE: leetcode/190_reverse_bits.py
class Solution (line 2) | class Solution:
method reverseBits (line 5) | def reverseBits(self, n):
method reverseBits (line 27) | def reverseBits(self, n):
class Solution (line 24) | class Solution:
method reverseBits (line 5) | def reverseBits(self, n):
method reverseBits (line 27) | def reverseBits(self, n):
FILE: leetcode/191_number_of_1_bits.py
class Solution (line 1) | class Solution:
method hammingWeight (line 2) | def hammingWeight(self, n):
FILE: leetcode/19_remove_nth_node_from_end_of_list.py
class Solution (line 10) | class Solution:
method removeNthFromEnd (line 11) | def removeNthFromEnd(self, head, n):
FILE: leetcode/202_happy_number.py
class Solution (line 1) | class Solution:
method isHappy (line 2) | def isHappy(self, n):
method square_sum (line 18) | def square_sum(self, a):
FILE: leetcode/204_count_primes.py
class Solution (line 8) | class Solution:
method countPrimes (line 9) | def countPrimes(self, n):
FILE: leetcode/208_implement_trie_prefix_tree.py
class TrieNode (line 1) | class TrieNode:
method __init__ (line 2) | def __init__(self, val=None):
class Trie (line 7) | class Trie:
method __init__ (line 8) | def __init__(self):
method insert (line 11) | def insert(self, word):
method search (line 27) | def search(self, word):
method startsWith (line 43) | def startsWith(self, prefix):
FILE: leetcode/20_valid_parentheses.py
class Solution (line 1) | class Solution:
method isValid (line 2) | def isValid(self, s):
FILE: leetcode/215_kth_largest_element_in_an_array.py
class Solution (line 4) | class Solution:
method findKthLargest (line 5) | def findKthLargest(self, A, k):
FILE: leetcode/217_contains_duplicate.py
class Solution (line 1) | class Solution:
method containsDuplicate (line 2) | def containsDuplicate(self, A):
FILE: leetcode/218_the_skyline_problem.py
class HashHeapq (line 7) | class HashHeapq:
method __init__ (line 8) | def __init__(self):
method push (line 12) | def push(self, val):
method pop (line 15) | def pop(self):
method remove (line 21) | def remove(self, val):
method top (line 30) | def top(self):
method is_empty (line 36) | def is_empty(self):
class Solution (line 44) | class Solution:
method getSkyline (line 45) | def getSkyline(self, buildings):
FILE: leetcode/224_basic_calculator.py
class Solution (line 1) | class Solution:
method calculate (line 2) | def calculate(self, s):
method to_rpn (line 22) | def to_rpn(self, s):
method eval_rpn (line 48) | def eval_rpn(self, s):
method calculate (line 63) | def calculate(self, s):
method to_rpn (line 78) | def to_rpn(self, s):
method eval_rpn (line 104) | def eval_rpn(self, s):
class Solution (line 62) | class Solution:
method calculate (line 2) | def calculate(self, s):
method to_rpn (line 22) | def to_rpn(self, s):
method eval_rpn (line 48) | def eval_rpn(self, s):
method calculate (line 63) | def calculate(self, s):
method to_rpn (line 78) | def to_rpn(self, s):
method eval_rpn (line 104) | def eval_rpn(self, s):
FILE: leetcode/227_basic_calculator_ii.py
class Solution (line 1) | class Solution:
method calculate (line 2) | def calculate(self, s):
method to_rpn (line 27) | def to_rpn(self, s, P):
method eval_rpn (line 53) | def eval_rpn(self, s, OP):
method calculate (line 68) | def calculate(self, s):
method to_rpn (line 83) | def to_rpn(self, s):
method eval_rpn (line 111) | def eval_rpn(self, s):
class Solution (line 67) | class Solution:
method calculate (line 2) | def calculate(self, s):
method to_rpn (line 27) | def to_rpn(self, s, P):
method eval_rpn (line 53) | def eval_rpn(self, s, OP):
method calculate (line 68) | def calculate(self, s):
method to_rpn (line 83) | def to_rpn(self, s):
method eval_rpn (line 111) | def eval_rpn(self, s):
FILE: leetcode/229_majority_element_ii.py
class Solution (line 1) | class Solution:
method majorityElement (line 2) | def majorityElement(self, nums):
FILE: leetcode/22_generate_parentheses.py
class Solution (line 1) | class Solution:
method generateParenthesis (line 2) | def generateParenthesis(self, n):
method dfs (line 14) | def dfs(self, n, lcnt, rcnt, ans, path):
FILE: leetcode/230_kth_smallest_element_in_a_bst.py
class Solution (line 11) | class Solution:
method kthSmallest (line 12) | def kthSmallest(self, root, k):
FILE: leetcode/234_palindrome_linked_list.py
class Solution (line 8) | class Solution:
method isPalindrome (line 9) | def isPalindrome(self, head):
method isPalindrome (line 32) | def isPalindrome(self, head):
class Solution (line 31) | class Solution:
method isPalindrome (line 9) | def isPalindrome(self, head):
method isPalindrome (line 32) | def isPalindrome(self, head):
FILE: leetcode/235_lowest_common_ancestor_of_a_binary_search_tree.py
class Solution (line 9) | class Solution(object):
method lowestCommonAncestor (line 10) | def lowestCommonAncestor(self, root, p, q):
FILE: leetcode/236_lowest_common_ancestor_of_a_binary_tree.py
class Solution (line 9) | class Solution(object):
method lowestCommonAncestor (line 10) | def lowestCommonAncestor(self, root, p, q):
FILE: leetcode/237_delete_node_in_a_linked_list.py
class Solution (line 8) | class Solution(object):
method deleteNode (line 9) | def deleteNode(self, node):
FILE: leetcode/242_valid_anagram.py
class Solution (line 1) | class Solution:
method isAnagram (line 2) | def isAnagram(self, s, t):
FILE: leetcode/269_alien_dictionary.py
class Solution (line 1) | class Solution:
method alienOrder (line 2) | def alienOrder(self, words):
method alienOrder (line 32) | def alienOrder(self, words):
class Solution (line 28) | class Solution:
method alienOrder (line 2) | def alienOrder(self, words):
method alienOrder (line 32) | def alienOrder(self, words):
FILE: leetcode/277_find_the_celebrity.py
class Solution (line 6) | class Solution:
method findCelebrity (line 7) | def findCelebrity(self, n):
FILE: leetcode/280_wiggle_sort.py
class Solution (line 1) | class Solution:
method wiggleSort (line 2) | def wiggleSort(self, nums):
FILE: leetcode/282_expression_add_operators.py
class Solution (line 8) | class Solution:
method addOperators (line 9) | def addOperators(self, s, target):
method dfs (line 23) | def dfs(self, s, start, target, val, multi, ans, path):
FILE: leetcode/285_inorder_successor_in_bst.py
class Solution (line 70) | class Solution:
method inorderSuccessor (line 77) | def inorderSuccessor(self, root, target):
class Solution2 (line 104) | class Solution2:
method inorderSuccessor (line 110) | def inorderSuccessor(self, root, target):
class Solution3 (line 138) | class Solution3:
method inorderSuccessor (line 146) | def inorderSuccessor(self, root, target):
class Solution4 (line 171) | class Solution4:
method inorderSuccessor (line 179) | def inorderSuccessor(self, root, target):
FILE: leetcode/288_unique_word_abbreviation.py
class ValidWordAbbr (line 19) | class ValidWordAbbr:
method __init__ (line 20) | def __init__(self, dictionary):
method isUnique (line 31) | def isUnique(self, word):
method abbreviation (line 40) | def abbreviation(self, word):
FILE: leetcode/289_game_of_life.py
class Solution (line 11) | class Solution:
method gameOfLife (line 15) | def gameOfLife(self, board):
method get_live_neibs (line 38) | def get_live_neibs(self, board, x, y):
method gameOfLife (line 62) | def gameOfLife(self, board):
method get_live_neibs (line 93) | def get_live_neibs(self, board, x, y):
class Solution (line 58) | class Solution:
method gameOfLife (line 15) | def gameOfLife(self, board):
method get_live_neibs (line 38) | def get_live_neibs(self, board, x, y):
method gameOfLife (line 62) | def gameOfLife(self, board):
method get_live_neibs (line 93) | def get_live_neibs(self, board, x, y):
FILE: leetcode/295_find_median_from_data_stream.py
class MedianFinder (line 10) | class MedianFinder:
method __init__ (line 11) | def __init__(self):
method addNum (line 15) | def addNum(self, num):
method findMedian (line 25) | def findMedian(self):
FILE: leetcode/299_bulls_and_cows.py
class Solution (line 1) | class Solution:
method getHint (line 2) | def getHint(self, secret, guess):
method getHint (line 36) | def getHint(self, secret, guess):
class Solution (line 35) | class Solution:
method getHint (line 2) | def getHint(self, secret, guess):
method getHint (line 36) | def getHint(self, secret, guess):
FILE: leetcode/303_range_sum_query_immutable.py
class NumArray (line 8) | class NumArray:
method __init__ (line 9) | def __init__(self, nums):
method sumRange (line 22) | def sumRange(self, i, j):
FILE: leetcode/304_range_sum_query_2d_immutable.py
class NumMatrix (line 8) | class NumMatrix:
method __init__ (line 9) | def __init__(self, matrix):
method sumRegion (line 28) | def sumRegion(self, x1, y1, x2, y2):
FILE: leetcode/307_range_sum_query_mutable.py
class NumArray (line 12) | class NumArray:
method __init__ (line 13) | def __init__(self, nums):
method update (line 27) | def update(self, i, val):
method sumRange (line 44) | def sumRange(self, i, j):
method sum (line 52) | def sum(self, i):
FILE: leetcode/308_range_sum_query_2d_mutable.py
class NumMatrix (line 9) | class NumMatrix:
method __init__ (line 10) | def __init__(self, matrix):
method update (line 25) | def update(self, x, y, val):
method sumRegion (line 47) | def sumRegion(self, x1, y1, x2, y2):
method sum (line 62) | def sum(self, x, y):
FILE: leetcode/30_substring_with_concatenation_of_all_words.py
class Solution (line 1) | class Solution:
method findSubstring (line 2) | def findSubstring(self, s, S):
FILE: leetcode/315_count_of_smaller_numbers_after_self.py
class Solution (line 1) | class Solution:
method countSmaller (line 5) | def countSmaller(self, nums):
method update (line 27) | def update(self, i):
method sum (line 34) | def sum(self, i):
method countSmaller (line 48) | def countSmaller(self, nums):
class Solution (line 44) | class Solution:
method countSmaller (line 5) | def countSmaller(self, nums):
method update (line 27) | def update(self, i):
method sum (line 34) | def sum(self, i):
method countSmaller (line 48) | def countSmaller(self, nums):
FILE: leetcode/323_number_of_connected_components_in_an_undirected_graph.py
class Solution (line 17) | class Solution:
method countComponents (line 21) | def countComponents(self, n, edges):
method union (line 40) | def union(self, nodes, a, b):
method find (line 50) | def find(self, nodes, a):
class Solution2 (line 61) | class Solution2:
method countComponents (line 65) | def countComponents(self, n, edges):
method dfs (line 96) | def dfs(self, a, adj, visited):
FILE: leetcode/324_wiggle_sort_ii.py
class Solution (line 6) | class Solution:
method wiggleSort (line 7) | def wiggleSort(self, A):
FILE: leetcode/326_power_of_three.py
class Solution (line 1) | class Solution:
method isPowerOfThree (line 2) | def isPowerOfThree(self, n):
FILE: leetcode/329_longest_increasing_path_in_a_matrix.py
class Solution (line 1) | class Solution:
method longestIncreasingPath (line 2) | def longestIncreasingPath(self, G):
method dfs (line 28) | def dfs(self, G, x, y, memo):
FILE: leetcode/334_increasing_triplet_subsequence.py
class Solution (line 1) | class Solution:
method increasingTriplet (line 2) | def increasingTriplet(self, A):
FILE: leetcode/33_search_in_rotated_sorted_array.py
class Solution (line 1) | class Solution:
method search (line 2) | def search(self, nums, target):
FILE: leetcode/340_longest_substring_with_at_most_k_distinct_characters.py
class Solution (line 10) | class Solution:
method lengthOfLongestSubstringKDistinct (line 11) | def lengthOfLongestSubstringKDistinct(self, s, k):
FILE: leetcode/344_reverse_string.py
class Solution (line 1) | class Solution:
method reverseString (line 2) | def reverseString(self, s):
FILE: leetcode/347_top_k_frequent_elements.py
class Solution (line 1) | class Solution:
method topKFrequent (line 2) | def topKFrequent(self, A, k):
FILE: leetcode/348_design_tic_tac_toe.py
class TicTacToe (line 1) | class TicTacToe(object):
method __init__ (line 5) | def __init__(self, n):
method move (line 15) | def move(self, x, y, player):
FILE: leetcode/353_design_snake_game.py
class SnakeGame (line 38) | class SnakeGame:
method __init__ (line 39) | def __init__(self, width, height, food):
method move (line 71) | def move(self, direction):
FILE: leetcode/36_valid_sudoku.py
class Solution (line 1) | class Solution:
method isValidSudoku (line 2) | def isValidSudoku(self, board):
FILE: leetcode/377_combination_sum_iv.py
class Solution (line 8) | class Solution:
method combinationSum4 (line 12) | def combinationSum4(self, nums, target):
method combinationSum4 (line 40) | def combinationSum4(self, nums, target):
method memo_search (line 54) | def memo_search(self, nums, remain, dp):
method combinationSum4 (line 74) | def combinationSum4(self, nums, target):
method dfs (line 89) | def dfs(self, nums, remain, ans, path):
method combinationSum4 (line 112) | def combinationSum4(self, nums, target):
class Solution (line 34) | class Solution:
method combinationSum4 (line 12) | def combinationSum4(self, nums, target):
method combinationSum4 (line 40) | def combinationSum4(self, nums, target):
method memo_search (line 54) | def memo_search(self, nums, remain, dp):
method combinationSum4 (line 74) | def combinationSum4(self, nums, target):
method dfs (line 89) | def dfs(self, nums, remain, ans, path):
method combinationSum4 (line 112) | def combinationSum4(self, nums, target):
class Solution (line 70) | class Solution:
method combinationSum4 (line 12) | def combinationSum4(self, nums, target):
method combinationSum4 (line 40) | def combinationSum4(self, nums, target):
method memo_search (line 54) | def memo_search(self, nums, remain, dp):
method combinationSum4 (line 74) | def combinationSum4(self, nums, target):
method dfs (line 89) | def dfs(self, nums, remain, ans, path):
method combinationSum4 (line 112) | def combinationSum4(self, nums, target):
class Solution (line 106) | class Solution:
method combinationSum4 (line 12) | def combinationSum4(self, nums, target):
method combinationSum4 (line 40) | def combinationSum4(self, nums, target):
method memo_search (line 54) | def memo_search(self, nums, remain, dp):
method combinationSum4 (line 74) | def combinationSum4(self, nums, target):
method dfs (line 89) | def dfs(self, nums, remain, ans, path):
method combinationSum4 (line 112) | def combinationSum4(self, nums, target):
FILE: leetcode/378_kth_smallest_element_in_a_sorted_matrix.py
class Solution (line 4) | class Solution:
method kthSmallest (line 5) | def kthSmallest(self, G, k):
FILE: leetcode/37_sudoku_solver.py
class Solution (line 1) | class Solution:
method solveSudoku (line 2) | def solveSudoku(self, board):
method dfs (line 12) | def dfs(self, board, x, y):
method is_valid (line 40) | def is_valid(self, board, x, y):
FILE: leetcode/380_insert_delete_getrandom_o1.py
class RandomizedSet (line 11) | class RandomizedSet:
method __init__ (line 12) | def __init__(self):
method insert (line 16) | def insert(self, val):
method remove (line 25) | def remove(self, val):
method getRandom (line 44) | def getRandom(self):
FILE: leetcode/381_insert_delete_getrandom_o1_duplicates_allowed.py
class RandomizedCollection (line 4) | class RandomizedCollection:
method __init__ (line 5) | def __init__(self):
method insert (line 9) | def insert(self, val):
method remove (line 23) | def remove(self, val):
method getRandom (line 43) | def getRandom(self):
FILE: leetcode/382_linked_list_random_node.py
class Solution (line 10) | class Solution:
method __init__ (line 11) | def __init__(self, head):
method getRandom (line 19) | def getRandom(self):
FILE: leetcode/384_shuffle_an_array.py
class Solution (line 4) | class Solution:
method __init__ (line 5) | def __init__(self, nums):
method reset (line 12) | def reset(self):
method shuffle (line 20) | def shuffle(self):
FILE: leetcode/386_lexicographical_numbers.py
class Solution (line 1) | class Solution:
method lexicalOrder (line 2) | def lexicalOrder(self, n):
FILE: leetcode/387_first_unique_character_in_a_string.py
class Solution (line 1) | class Solution:
method firstUniqChar (line 2) | def firstUniqChar(self, s):
FILE: leetcode/388_longest_absolute_file_path.py
class Solution (line 28) | class Solution:
method lengthLongestPath (line 29) | def lengthLongestPath(self, path):
FILE: leetcode/389_find_the_difference.py
class Solution (line 1) | class Solution:
method findTheDifference (line 2) | def findTheDifference(self, s, t):
method findTheDifference (line 19) | def findTheDifference(self, s, t):
class Solution (line 18) | class Solution:
method findTheDifference (line 2) | def findTheDifference(self, s, t):
method findTheDifference (line 19) | def findTheDifference(self, s, t):
FILE: leetcode/38_count_and_say.py
class Solution (line 1) | class Solution:
method countAndSay (line 2) | def countAndSay(self, N):
FILE: leetcode/390_elimination_game.py
class Solution (line 1) | class Solution:
method lastRemaining (line 2) | def lastRemaining(self, n):
FILE: leetcode/391_perfect_rectangle.py
class Solution (line 4) | class Solution:
method isRectangleCover (line 5) | def isRectangleCover(self, recs):
FILE: leetcode/395_longest_substring_with_at_least_k_repeating_characters.py
class Solution (line 1) | class Solution:
method longestSubstring (line 2) | def longestSubstring(self, s, k):
FILE: leetcode/398_random_pick_index.py
class Solution (line 4) | class Solution:
method __init__ (line 5) | def __init__(self, A):
method pick (line 11) | def pick(self, target):
FILE: leetcode/399_evaluate_division.py
class Solution (line 4) | class Solution:
method calcEquation (line 5) | def calcEquation(self, equations, values, queries):
method dfs (line 38) | def dfs(self, a, b, val, nexts, evals, visited):
FILE: leetcode/406_queue_reconstruction_by_height.py
class Solution (line 31) | class Solution:
method reconstructQueue (line 32) | def reconstructQueue(self, people):
method reconstructQueue (line 51) | def reconstructQueue(self, people):
class Solution (line 50) | class Solution:
method reconstructQueue (line 32) | def reconstructQueue(self, people):
method reconstructQueue (line 51) | def reconstructQueue(self, people):
FILE: leetcode/416_partition_equal_subset_sum.py
class Solution (line 9) | class Solution:
method canPartition (line 10) | def canPartition(self, nums):
FILE: leetcode/417_pacific_atlantic_water_flow.py
class Solution (line 1) | class Solution:
method pacificAtlantic (line 10) | def pacificAtlantic(self, matrix):
method bfs (line 38) | def bfs(self, matrix, queue, visited):
method pacificAtlantic (line 64) | def pacificAtlantic(self, matrix):
method dfs (line 86) | def dfs(self, matrix, x, y, visited):
class Solution (line 60) | class Solution:
method pacificAtlantic (line 10) | def pacificAtlantic(self, matrix):
method bfs (line 38) | def bfs(self, matrix, queue, visited):
method pacificAtlantic (line 64) | def pacificAtlantic(self, matrix):
method dfs (line 86) | def dfs(self, matrix, x, y, visited):
FILE: leetcode/41_first_missing_positive.py
class Solution (line 6) | class Solution:
method firstMissingPositive (line 7) | def firstMissingPositive(self, A):
FILE: leetcode/437_path_sum_iii.py
class Solution (line 11) | class Solution:
method pathSum (line 15) | def pathSum(self, root, target):
method count_valid_path (line 30) | def count_valid_path(self, node, remaining):
method pathSum (line 45) | def pathSum(self, root, target):
method dfs (line 60) | def dfs(self, node, target, ans, path):
class Solution (line 41) | class Solution:
method pathSum (line 15) | def pathSum(self, root, target):
method count_valid_path (line 30) | def count_valid_path(self, node, remaining):
method pathSum (line 45) | def pathSum(self, root, target):
method dfs (line 60) | def dfs(self, node, target, ans, path):
FILE: leetcode/454_4sum_ii.py
class Solution (line 1) | class Solution:
method fourSumCount (line 2) | def fourSumCount(self, A, B, C, D):
FILE: leetcode/461_hamming_distance.py
class Solution (line 1) | class Solution:
method hammingDistance (line 2) | def hammingDistance(self, x, y):
FILE: leetcode/480_sliding_window_median.py
class HashHeapq (line 4) | class HashHeapq:
method __init__ (line 5) | def __init__(self):
method __repr__ (line 8) | def __repr__(self):
method __len__ (line 11) | def __len__(self):
method __bool__ (line 14) | def __bool__(self):
method push (line 17) | def push(self, val):
method pop (line 20) | def pop(self):
method remove (line 26) | def remove(self, val):
method top (line 47) | def top(self):
class Solution (line 54) | class Solution:
method medianSlidingWindow (line 55) | def medianSlidingWindow(self, nums, k):
method get_median (line 89) | def get_median(self):
FILE: leetcode/486_predict_the_winner.py
class Solution (line 6) | class Solution:
method PredictTheWinner (line 7) | def PredictTheWinner(self, nums):
method PredictTheWinner (line 34) | def PredictTheWinner(self, nums):
class Solution (line 33) | class Solution:
method PredictTheWinner (line 7) | def PredictTheWinner(self, nums):
method PredictTheWinner (line 34) | def PredictTheWinner(self, nums):
FILE: leetcode/48_rotate_image.py
class Solution (line 1) | class Solution:
method rotate (line 2) | def rotate(self, matrix):
method rotate (line 28) | def rotate(self, matrix):
class Solution (line 27) | class Solution:
method rotate (line 2) | def rotate(self, matrix):
method rotate (line 28) | def rotate(self, matrix):
FILE: leetcode/490_the_maze.py
class Solution (line 1) | class Solution:
method hasPath (line 2) | def hasPath(self, maze, start, destination):
method dfs (line 30) | def dfs(self, maze, x, y, tx, ty, visited):
FILE: leetcode/494_target_sum.py
class Solution (line 16) | class Solution:
method findTargetSumWays (line 17) | def findTargetSumWays(self, A, target):
method subset_sum (line 32) | def subset_sum(self, A, target):
FILE: leetcode/499_the_maze_iii.py
class Solution (line 1) | class Solution:
method findShortestWay (line 5) | def findShortestWay(self, maze, ball, hole):
class Solution2 (line 78) | class Solution2:
method findShortestWay (line 82) | def findShortestWay(self, maze, ball, hole):
FILE: leetcode/505_the_maze_ii.py
class Solution (line 1) | class Solution:
method shortestDistance (line 5) | def shortestDistance(self, maze, start, destination):
class Solution2 (line 67) | class Solution2:
method shortestDistance (line 71) | def shortestDistance(self, maze, start, destination):
FILE: leetcode/518_coin_change_2.py
class Solution (line 1) | class Solution:
method change (line 2) | def change(self, amount, coins):
FILE: leetcode/51_n_queens.py
class Solution (line 1) | class Solution:
method solveNQueens (line 2) | def solveNQueens(self, n):
method dfs (line 15) | def dfs(self, G, y, ans):
method is_valid (line 26) | def is_valid(self, G, x, y):
method clone_board (line 45) | def clone_board(self, G):
FILE: leetcode/524_longest_word_in_dictionary_through_deleting.py
class Solution (line 1) | class Solution:
method findLongestWord (line 7) | def findLongestWord(self, s, words):
method is_subseq (line 27) | def is_subseq(self, s, t):
method findLongestWord (line 46) | def findLongestWord(self, s, words):
method find_cands (line 70) | def find_cands(self, s, i, cands, path):
class Solution (line 42) | class Solution:
method findLongestWord (line 7) | def findLongestWord(self, s, words):
method is_subseq (line 27) | def is_subseq(self, s, t):
method findLongestWord (line 46) | def findLongestWord(self, s, words):
method find_cands (line 70) | def find_cands(self, s, i, cands, path):
FILE: leetcode/52_n_queens_ii.py
class Solution (line 1) | class Solution:
method totalNQueens (line 2) | def totalNQueens(self, n):
method divide_conquer (line 12) | def divide_conquer(self, n, y, cnt, Xs, DLs, DRs):
FILE: leetcode/530_minimum_absolute_difference_in_bst.py
class Solution (line 11) | class Solution:
method getMinimumDifference (line 19) | def getMinimumDifference(self, root):
FILE: leetcode/542_01_matrix.py
class Solution (line 1) | class Solution:
method updateMatrix (line 2) | def updateMatrix(self, matrix):
FILE: leetcode/54_spiral_matrix.py
class Solution (line 1) | class Solution:
method spiralOrder (line 2) | def spiralOrder(self, matrix):
FILE: leetcode/592_fraction_addition_and_subtraction.py
class Solution (line 4) | class Solution:
method fractionAddition (line 5) | def fractionAddition(self, E):
method get_gcd (line 45) | def get_gcd(self, a, b):
FILE: leetcode/593_valid_square.py
class Solution (line 1) | class Solution:
method validSquare (line 2) | def validSquare(self, p1, p2, p3, p4):
method get_distance (line 34) | def get_distance(self, a, b):
FILE: leetcode/59_spiral_matrix_ii.py
class Solution (line 1) | class Solution:
method generateMatrix (line 2) | def generateMatrix(self, n):
FILE: leetcode/5_longest_palindromic_substring.py
class Solution (line 1) | class Solution:
method longestPalindrome (line 2) | def longestPalindrome(self, s):
method check_palindrome (line 27) | def check_palindrome(self, s, left, right):
FILE: leetcode/616_add_bold_tag_in_string.py
class Solution (line 18) | class Solution:
method addBoldTag (line 19) | def addBoldTag(self, s, words):
FILE: leetcode/643_maximum_average_subarray_i.py
class Solution (line 1) | class Solution:
method findMaxAverage (line 2) | def findMaxAverage(self, nums, k):
method findMaxAverage (line 27) | def findMaxAverage(self, nums, k):
class Solution (line 26) | class Solution:
method findMaxAverage (line 2) | def findMaxAverage(self, nums, k):
method findMaxAverage (line 27) | def findMaxAverage(self, nums, k):
FILE: leetcode/66_plus_one.py
class Solution (line 1) | class Solution:
method plusOne (line 2) | def plusOne(self, digits):
method plusOne (line 28) | def plusOne(self, digits):
class Solution (line 27) | class Solution:
method plusOne (line 2) | def plusOne(self, digits):
method plusOne (line 28) | def plusOne(self, digits):
FILE: leetcode/676_implement_magic_dictionary.py
class MagicDictionary (line 9) | class MagicDictionary:
method __init__ (line 10) | def __init__(self):
method buildDict (line 16) | def buildDict(self, words):
method search (line 32) | def search(self, word):
FILE: leetcode/679_24_game.py
class Solution (line 1) | class Solution:
method judgePoint24 (line 10) | def judgePoint24(self, nums):
FILE: leetcode/681_next_closest_time.py
class Solution (line 25) | class Solution:
method nextClosestTime (line 26) | def nextClosestTime(self, time):
method is_valid (line 60) | def is_valid(self, ids, digits):
FILE: leetcode/682_baseball_game.py
class Solution (line 1) | class Solution:
method calPoints (line 2) | def calPoints(self, ops):
FILE: leetcode/683_k_empty_slots.py
class Solution (line 17) | class Solution:
method kEmptySlots (line 21) | def kEmptySlots(self, flowers, k):
class Solution2 (line 40) | class Solution2:
method kEmptySlots (line 45) | def kEmptySlots(self, flowers, k):
FILE: leetcode/684_redundant_connection.py
class Solution (line 10) | class Solution:
method findRedundantConnection (line 14) | def findRedundantConnection(self, edges):
method union (line 30) | def union(self, nodes, u, v):
method find (line 40) | def find(self, nodes, u):
method findRedundantConnection (line 58) | def findRedundantConnection(self, edges):
method dfs (line 78) | def dfs(self, nodes, u, v, visited):
class Solution (line 54) | class Solution:
method findRedundantConnection (line 14) | def findRedundantConnection(self, edges):
method union (line 30) | def union(self, nodes, u, v):
method find (line 40) | def find(self, nodes, u):
method findRedundantConnection (line 58) | def findRedundantConnection(self, edges):
method dfs (line 78) | def dfs(self, nodes, u, v, visited):
FILE: leetcode/685_redundant_connection_ii.py
class Solution (line 17) | class Solution:
method findRedundantDirectedConnection (line 18) | def findRedundantDirectedConnection(self, edges):
method union (line 45) | def union(self, uf, u, v):
method find (line 55) | def find(self, uf, u):
method dfs (line 65) | def dfs(self, u, adj, visited):
FILE: leetcode/688_knight_probability_in_chessboard.py
class Solution (line 4) | class Solution:
method knightProbability (line 11) | def knightProbability(self, n, k, r, c):
method knightProbability (line 54) | def knightProbability(self, n, k, r, c):
class Solution (line 50) | class Solution:
method knightProbability (line 11) | def knightProbability(self, n, k, r, c):
method knightProbability (line 54) | def knightProbability(self, n, k, r, c):
FILE: leetcode/689_maximum_sum_of_3_non_overlapping_subarrays.py
class Solution (line 6) | class Solution:
method maxSumOfThreeSubarrays (line 7) | def maxSumOfThreeSubarrays(self, A, k):
FILE: leetcode/697_degree_of_an_array.py
class Solution (line 1) | class Solution:
method findShortestSubArray (line 2) | def findShortestSubArray(self, A):
FILE: leetcode/719_find_k_th_smallest_pair_distance.py
class Solution (line 1) | class Solution:
method smallestDistancePair (line 2) | def smallestDistancePair(self, A, k):
method check_valid (line 23) | def check_valid(self, A, mid, k):
FILE: leetcode/721_accounts_merge.py
class Solution (line 1) | class Solution:
method accountsMerge (line 2) | def accountsMerge(self, A):
method connect (line 29) | def connect(self, N, a, b):
method find (line 36) | def find(self, N, a):
FILE: leetcode/734_sentence_similarity.py
class Solution (line 22) | class Solution:
method areSentencesSimilar (line 23) | def areSentencesSimilar(self, words1, words2, pairs):
FILE: leetcode/737_sentence_similarity_ii.py
class Solution (line 19) | class Solution:
method areSentencesSimilarTwo (line 23) | def areSentencesSimilarTwo(self, words1, words2, pairs):
method union (line 49) | def union(self, nodes, a, b):
method find (line 58) | def find(self, nodes, a):
class Solution2 (line 72) | class Solution2:
method areSentencesSimilarTwo (line 76) | def areSentencesSimilarTwo(self, words1, words2, pairs):
method dfs (line 101) | def dfs(self, start, end, simils, path):
FILE: leetcode/744_find_smallest_letter_greater_than_target.py
class Solution (line 1) | class Solution:
method nextGreatestLetter (line 2) | def nextGreatestLetter(self, L, target):
FILE: leetcode/746_min_cost_climbing_stairs.py
class Solution (line 1) | class Solution:
method minCostClimbingStairs (line 2) | def minCostClimbingStairs(self, cost):
FILE: leetcode/747_largest_number_at_least_twice_of_others.py
class Solution (line 1) | class Solution:
method dominantIndex (line 2) | def dominantIndex(self, A):
FILE: leetcode/748_shortest_completing_word.py
class Solution (line 1) | class Solution:
method shortestCompletingWord (line 2) | def shortestCompletingWord(self, P, words):
method is_included (line 24) | def is_included(self, a_times, b_times):
method get_times (line 35) | def get_times(self, word):
FILE: leetcode/749_contain_virus.py
class Solution (line 16) | class Solution:
method containVirus (line 28) | def containVirus(self, G):
method build_walls (line 47) | def build_walls(self, G):
method dfs (line 83) | def dfs(self, x, y, G, visited, ex_virus, spreading, walls):
FILE: leetcode/750_number_of_corner_rectangles.py
class Solution (line 1) | class Solution:
method countCornerRectangles (line 2) | def countCornerRectangles(self, G):
FILE: leetcode/758_bold_words_in_string.py
class Solution (line 18) | class Solution:
method boldWords (line 19) | def boldWords(self, words, s):
FILE: leetcode/769_max_chunks_to_make_sorted.py
class Solution (line 23) | class Solution:
method maxChunksToSorted (line 24) | def maxChunksToSorted(self, nums):
method maxChunksToSorted (line 46) | def maxChunksToSorted(self, nums):
class Solution (line 45) | class Solution:
method maxChunksToSorted (line 24) | def maxChunksToSorted(self, nums):
method maxChunksToSorted (line 46) | def maxChunksToSorted(self, nums):
FILE: leetcode/776_split_bst.py
class Solution (line 9) | class Solution:
method splitBST (line 10) | def splitBST(self, root, target):
FILE: leetcode/777_swap_adjacent_in_lr_string.py
class Solution (line 1) | class Solution:
method canTransform (line 2) | def canTransform(self, start, end):
FILE: leetcode/778_swim_in_rising_water.py
class Solution (line 4) | class Solution:
method swimInWater (line 5) | def swimInWater(self, G):
FILE: leetcode/779_k_th_symbol_in_grammar.py
class Solution (line 1) | class Solution:
method kthGrammar (line 2) | def kthGrammar(self, N, K):
FILE: leetcode/783_minimum_distance_between_bst_nodes.py
class Solution (line 11) | class Solution:
method minDiffInBST (line 20) | def minDiffInBST(self, root):
method minDiffInBST (line 45) | def minDiffInBST(self, root):
class Solution (line 39) | class Solution:
method minDiffInBST (line 20) | def minDiffInBST(self, root):
method minDiffInBST (line 45) | def minDiffInBST(self, root):
FILE: leetcode/784_letter_case_permutation.py
class Solution (line 1) | class Solution:
method letterCasePermutation (line 2) | def letterCasePermutation(self, s):
method dfs (line 13) | def dfs(self, s, i, ans, path):
FILE: leetcode/785_is_graph_bipartite.py
class Solution (line 1) | class Solution:
method isBipartite (line 2) | def isBipartite(self, graph):
FILE: leetcode/786_k_th_smallest_prime_fraction.py
class Solution (line 16) | class Solution:
method kthSmallestPrimeFraction (line 17) | def kthSmallestPrimeFraction(self, A, K):
FILE: leetcode/787_cheapest_flights_within_k_stops.py
class Solution (line 1) | class Solution:
method findCheapestPrice (line 2) | def findCheapestPrice(self, n, flights, src, dst, K):
method findCheapestPrice (line 24) | def findCheapestPrice(self, n, flights, src, dst, K):
class Solution (line 23) | class Solution:
method findCheapestPrice (line 2) | def findCheapestPrice(self, n, flights, src, dst, K):
method findCheapestPrice (line 24) | def findCheapestPrice(self, n, flights, src, dst, K):
FILE: leetcode/788_rotated_digits.py
class Solution (line 1) | class Solution:
method rotatedDigits (line 2) | def rotatedDigits(self, N):
method is_good (line 15) | def is_good(self, N):
FILE: leetcode/789_escape_the_ghosts.py
class Solution (line 1) | class Solution:
method escapeGhosts (line 2) | def escapeGhosts(self, ghosts, target):
FILE: leetcode/790_domino_and_tromino_tiling.py
class Solution (line 1) | class Solution:
method numTilings (line 2) | def numTilings(self, N):
FILE: leetcode/791_custom_sort_string.py
class Solution (line 1) | class Solution:
method customSortString (line 2) | def customSortString(self, S, T):
FILE: leetcode/7_reverse_integer.py
class Solution (line 1) | class Solution:
method reverse (line 2) | def reverse(self, x):
FILE: leetcode/81_search_in_rotated_sorted_array_ii.py
class Solution (line 1) | class Solution:
method search (line 2) | def search(self, nums, target):
FILE: leetcode/8_string_to_integer_atoi.py
class Solution (line 1) | class Solution:
method myAtoi (line 2) | def myAtoi(self, s):
FILE: lintcode/102_linked_list_cycle.py
class Solution (line 10) | class Solution:
method hasCycle (line 15) | def hasCycle(self, head):
FILE: lintcode/103_linked_list_cycle_ii.py
class Solution (line 11) | class Solution:
method detectCycle (line 16) | def detectCycle(self, head):
FILE: lintcode/104_merge_k_sorted_lists.py
class Solution (line 11) | class Solution:
method mergeKLists (line 12) | def mergeKLists(self, lists):
FILE: lintcode/105_copy_list_with_random_pointer.py
class Solution (line 16) | class Solution:
method copyRandomList (line 17) | def copyRandomList(self, head):
method copyRandomList (line 64) | def copyRandomList(self, head):
class Solution (line 63) | class Solution:
method copyRandomList (line 17) | def copyRandomList(self, head):
method copyRandomList (line 64) | def copyRandomList(self, head):
FILE: lintcode/107_word_break.py
class Solution (line 1) | class Solution:
method wordBreak (line 5) | def wordBreak(self, s, words):
FILE: lintcode/108_palindrome_partitioning_ii.py
class Solution (line 1) | class Solution:
method minCut (line 4) | def minCut(self, S):
method get_palin_map (line 29) | def get_palin_map(self, S):
FILE: lintcode/109_triangle.py
class Solution (line 4) | class Solution:
method minimumTotal (line 9) | def minimumTotal(self, triangle):
method memo_search (line 15) | def memo_search(self, depth, start, triangle, memo):
method minimumTotal (line 42) | def minimumTotal(self, triangle):
method minimumTotal (line 84) | def minimumTotal(self, triangle):
class Solution (line 37) | class Solution:
method minimumTotal (line 9) | def minimumTotal(self, triangle):
method memo_search (line 15) | def memo_search(self, depth, start, triangle, memo):
method minimumTotal (line 42) | def minimumTotal(self, triangle):
method minimumTotal (line 84) | def minimumTotal(self, triangle):
class Solution (line 79) | class Solution:
method minimumTotal (line 9) | def minimumTotal(self, triangle):
method memo_search (line 15) | def memo_search(self, depth, start, triangle, memo):
method minimumTotal (line 42) | def minimumTotal(self, triangle):
method minimumTotal (line 84) | def minimumTotal(self, triangle):
FILE: lintcode/10_string_permutation_ii.py
class Solution (line 1) | class Solution:
method stringPermutation2 (line 6) | def stringPermutation2(self, S):
method dfs (line 16) | def dfs(self, S, ans, path):
FILE: lintcode/110_minimum_path_sum.py
class Solution (line 1) | class Solution:
method minPathSum (line 6) | def minPathSum(self, grid):
FILE: lintcode/111_climbing_stairs.py
class Solution (line 4) | class Solution:
method climbStairs (line 9) | def climbStairs(self, n):
method climbStairs (line 36) | def climbStairs(self, n):
method climbStairs (line 59) | def climbStairs(self, n):
class Solution (line 31) | class Solution:
method climbStairs (line 9) | def climbStairs(self, n):
method climbStairs (line 36) | def climbStairs(self, n):
method climbStairs (line 59) | def climbStairs(self, n):
class Solution (line 54) | class Solution:
method climbStairs (line 9) | def climbStairs(self, n):
method climbStairs (line 36) | def climbStairs(self, n):
method climbStairs (line 59) | def climbStairs(self, n):
FILE: lintcode/114_unique_paths.py
class Solution (line 1) | class Solution:
method uniquePaths (line 2) | def uniquePaths(self, m, n):
FILE: lintcode/115_unique_paths_ii.py
class Solution (line 1) | class Solution:
method uniquePathsWithObstacles (line 6) | def uniquePathsWithObstacles(self, G):
FILE: lintcode/116_jump_game.py
class Solution (line 6) | class Solution:
method canJump (line 7) | def canJump(self, A):
method canJump (line 28) | def canJump(self, A):
class Solution (line 27) | class Solution:
method canJump (line 7) | def canJump(self, A):
method canJump (line 28) | def canJump(self, A):
FILE: lintcode/117_jump_game_ii.py
class Solution (line 4) | class Solution:
method jump (line 9) | def jump(self, A):
method jump (line 36) | def jump(self, A):
class Solution (line 31) | class Solution:
method jump (line 9) | def jump(self, A):
method jump (line 36) | def jump(self, A):
FILE: lintcode/118_distinct_subsequences.py
class Solution (line 1) | class Solution:
method numDistinct (line 7) | def numDistinct(self, S, T):
FILE: lintcode/119_edit_distance.py
class Solution (line 1) | class Solution:
method minDistance (line 2) | def minDistance(self, s, t):
FILE: lintcode/11_search_range_in_binary_search_tree.py
class Solution (line 10) | class Solution:
method searchRange (line 11) | def searchRange(self, root, a, b):
method dfs (line 27) | def dfs(self, node, a, b, ans):
FILE: lintcode/120_word_ladder.py
class Solution (line 11) | class Solution:
method ladderLength (line 12) | def ladderLength(self, s, e, D):
method get_next_word (line 53) | def get_next_word(self, word, next_words):
FILE: lintcode/121_word_ladder_ii.py
class Solution (line 10) | class Solution:
method findLadders (line 17) | def findLadders(self, A, B, D):
method dfs (line 52) | def dfs(self, word, B, next_words, distance, ans, path):
method get_next_word (line 65) | def get_next_word(self, word, next_words):
FILE: lintcode/122_largest_rectangle_in_histogram.py
class Solution (line 9) | class Solution:
method largestRectangleArea (line 10) | def largestRectangleArea(self, H):
method largestRectangleArea (line 40) | def largestRectangleArea(self, H):
method largestRectangleArea (line 70) | def largestRectangleArea(self, H):
class Solution (line 39) | class Solution:
method largestRectangleArea (line 10) | def largestRectangleArea(self, H):
method largestRectangleArea (line 40) | def largestRectangleArea(self, H):
method largestRectangleArea (line 70) | def largestRectangleArea(self, H):
class Solution (line 69) | class Solution:
method largestRectangleArea (line 10) | def largestRectangleArea(self, H):
method largestRectangleArea (line 40) | def largestRectangleArea(self, H):
method largestRectangleArea (line 70) | def largestRectangleArea(self, H):
FILE: lintcode/123_word_search.py
class Solution (line 1) | class Solution:
method exist (line 14) | def exist(self, G, s):
method dfs (line 28) | def dfs(self, G, x, y, s, i, visited):
FILE: lintcode/124_longest_consecutive_sequence.py
class Solution (line 1) | class Solution:
method longestConsecutive (line 5) | def longestConsecutive(self, nums):
method longestConsecutive (line 47) | def longestConsecutive(self, nums):
class Solution (line 41) | class Solution:
method longestConsecutive (line 5) | def longestConsecutive(self, nums):
method longestConsecutive (line 47) | def longestConsecutive(self, nums):
FILE: lintcode/125_backpack_ii.py
class Solution (line 4) | class Solution:
method backPackII (line 11) | def backPackII(self, m, A, V):
method backPackII (line 45) | def backPackII(self, m, A, V):
class Solution (line 38) | class Solution:
method backPackII (line 11) | def backPackII(self, m, A, V):
method backPackII (line 45) | def backPackII(self, m, A, V):
FILE: lintcode/126_max_tree.py
class Solution (line 10) | class Solution:
method maxTree (line 24) | def maxTree(self, A):
FILE: lintcode/127_topological_sorting.py
class Solution (line 10) | class Solution:
method topSort (line 15) | def topSort(self, graph):
FILE: lintcode/128_hash_function.py
class Solution (line 1) | class Solution:
method hashCode (line 7) | def hashCode(self, key, HASH_SIZE):
FILE: lintcode/129_rehashing.py
class Solution (line 11) | class Solution:
method rehashing (line 16) | def rehashing(self, hash_table):
FILE: lintcode/12_min_stack.py
class MinStack (line 1) | class MinStack:
method __init__ (line 2) | def __init__(self):
method push (line 6) | def push(self, x):
method pop (line 16) | def pop(self):
method top (line 30) | def top(self):
method min (line 39) | def min(self):
FILE: lintcode/130_heapify.py
class Solution (line 1) | class Solution:
method heapify (line 6) | def heapify(self, A):
method siftdown (line 11) | def siftdown(self, A, i):
FILE: lintcode/131_building_outline.py
class HashHeapq (line 8) | class HashHeapq:
method __init__ (line 9) | def __init__(self):
method push (line 13) | def push(self, val):
method pop (line 16) | def pop(self):
method remove (line 22) | def remove(self, val):
method top (line 31) | def top(self):
method is_empty (line 37) | def is_empty(self):
class Solution (line 45) | class Solution:
method buildingOutline (line 46) | def buildingOutline(self, buildings):
FILE: lintcode/132_word_search_ii.py
class Solution (line 1) | class Solution:
method __init__ (line 2) | def __init__(self):
method new_node (line 7) | def new_node(self):
method put (line 13) | def put(self, parent, string):
method wordSearchII (line 29) | def wordSearchII(self, board, words):
method find (line 45) | def find(self, x, y, parent, result):
FILE: lintcode/134_lru_cache.py
class LRUCache (line 15) | class LRUCache:
method __init__ (line 16) | def __init__(self, capacity):
method get (line 27) | def get(self, key):
method set (line 38) | def set(self, key, val):
method _evict (line 56) | def _evict(self):
method _update (line 60) | def _update(self, key, val=None):
method _add (line 69) | def _add(self, key, val):
method _pop_head (line 73) | def _pop_head(self):
method _add_tail (line 78) | def _add_tail(self, node):
class CacheNode (line 82) | class CacheNode:
method __init__ (line 83) | def __init__(self, key, val=None, pre=None, nxt=None):
method link (line 89) | def link(self, pre, nxt):
method unlink (line 95) | def unlink(self):
FILE: lintcode/135_combination_sum.py
class Solution (line 1) | class Solution:
method combinationSum (line 7) | def combinationSum(self, A, target):
method dfs (line 16) | def dfs(self, A, start, remaining, ans, path):
FILE: lintcode/1365_minimum_cycle_section.py
class Solution (line 1) | class Solution:
method minimumCycleSection (line 6) | def minimumCycleSection(self, array):
FILE: lintcode/1366_directed_graph_loop.py
class Solution (line 4) | class Solution:
method isCyclicGraph (line 10) | def isCyclicGraph(self, start, end):
method dfs (line 30) | def dfs(self, u, nxt, visited, rec_stack):
FILE: lintcode/1367_police_distance.py
class Solution (line 1) | class Solution:
method policeDistance (line 6) | def policeDistance(self, matrix):
FILE: lintcode/1368_same_number.py
class Solution (line 1) | class Solution:
method sameNumber (line 7) | def sameNumber(self, nums, k):
FILE: lintcode/136_palindrome_partitioning.py
class Solution (line 1) | class Solution:
method partition (line 10) | def partition(self, s):
method check_palindrome (line 20) | def check_palindrome(self, s):
method dfs (line 75) | def dfs(self, s, start, palindromes):
FILE: lintcode/137_clone_graph.py
class Solution (line 13) | class Solution:
method cloneGraph (line 14) | def cloneGraph(self, node):
method cloneGraph (line 45) | def cloneGraph(self, node):
method dfs (line 55) | def dfs(self, node, N):
class Solution (line 44) | class Solution:
method cloneGraph (line 14) | def cloneGraph(self, node):
method cloneGraph (line 45) | def cloneGraph(self, node):
method dfs (line 55) | def dfs(self, node, N):
FILE: lintcode/138_subarray_sum.py
class Solution (line 1) | class Solution:
method subarraySum (line 6) | def subarraySum(self, nums):
FILE: lintcode/139_subarray_sum_closest.py
class Solution (line 5) | class Solution:
method subarraySumClosest (line 10) | def subarraySumClosest(self, nums):
FILE: lintcode/13_strstr.py
class Solution (line 1) | class Solution:
method strStr (line 2) | def strStr(self, haystack, needle):
FILE: lintcode/141_sqrtx.py
class Solution (line 1) | class Solution:
method sqrt (line 2) | def sqrt(self, x):
FILE: lintcode/142_o1_check_power_of_2.py
class Solution (line 1) | class Solution:
method checkPowerOf2 (line 6) | def checkPowerOf2(self, n):
FILE: lintcode/143_sort_colors_ii.py
class Solution (line 5) | class Solution:
method sortColors2 (line 11) | def sortColors2(self, colors, k):
method rainbow_sort (line 16) | def rainbow_sort(self, colors, start, end, color_from, color_to):
method sortColors2 (line 52) | def sortColors2(self, colors, k):
class Solution (line 46) | class Solution:
method sortColors2 (line 11) | def sortColors2(self, colors, k):
method rainbow_sort (line 16) | def rainbow_sort(self, colors, start, end, color_from, color_to):
method sortColors2 (line 52) | def sortColors2(self, colors, k):
FILE: lintcode/148_sort_colors.py
class Solution (line 1) | class Solution:
method sortColors (line 6) | def sortColors(self, A):
FILE: lintcode/149_best_time_to_buy_and_sell_stock.py
class Solution (line 1) | class Solution:
method maxProfit (line 6) | def maxProfit(self, P):
FILE: lintcode/14_first_position_of_target.py
class Solution (line 1) | class Solution:
method binarySearch (line 5) | def binarySearch(self, A, target):
FILE: lintcode/150_best_time_to_buy_and_sell_stock_ii.py
class Solution (line 1) | class Solution:
method maxProfit (line 6) | def maxProfit(self, P):
FILE: lintcode/151_best_time_to_buy_and_sell_stock_iii.py
class Solution (line 1) | class Solution:
method maxProfit (line 6) | def maxProfit(self, P):
FILE: lintcode/153_combination_sum_ii.py
class Solution (line 1) | class Solution:
method combinationSum2 (line 7) | def combinationSum2(self, A, target):
method dfs (line 16) | def dfs(self, A, start, remaining, ans, path):
FILE: lintcode/154_regular_expression_matching.py
class Solution (line 22) | class Solution:
method isMatch (line 23) | def isMatch(self, s, p):
FILE: lintcode/155_minimum_depth_of_binary_tree.py
class Solution (line 10) | class Solution:
method minDepth (line 15) | def minDepth(self, root):
method minDepth (line 43) | def minDepth(self, root):
class Solution (line 38) | class Solution:
method minDepth (line 15) | def minDepth(self, root):
method minDepth (line 43) | def minDepth(self, root):
FILE: lintcode/156_merge_intervals.py
class Solution (line 10) | class Solution:
method merge (line 11) | def merge(self, intvs):
FILE: lintcode/158_two_strings_are_anagrams.py
class Solution (line 1) | class Solution:
method anagram (line 7) | def anagram(self, s, t):
FILE: lintcode/159_find_minimum_in_rotated_sorted_array.py
class Solution (line 1) | class Solution:
method findMin (line 6) | def findMin(self, nums):
FILE: lintcode/15_permutations.py
class Solution (line 1) | class Solution:
method permute (line 2) | def permute(self, nums):
method dfs (line 17) | def dfs(self, nums, ans, path):
FILE: lintcode/160_find_minimum_in_rotated_sorted_array_ii.py
class Solution (line 4) | class Solution:
method findMin (line 9) | def findMin(self, A):
method findMin (line 30) | def findMin(self, A):
class Solution (line 25) | class Solution:
method findMin (line 9) | def findMin(self, A):
method findMin (line 30) | def findMin(self, A):
FILE: lintcode/165_merge_two_sorted_lists.py
class Solution (line 8) | class Solution:
method mergeTwoLists (line 9) | def mergeTwoLists(self, a, b):
FILE: lintcode/167_add_two_numbers.py
class Solution (line 10) | class Solution:
method addLists (line 11) | def addLists(self, A, B):
FILE: lintcode/168_burst_balloons.py
class Solution (line 1) | class Solution:
method maxCoins (line 6) | def maxCoins(self, V):
FILE: lintcode/16_permutations_ii.py
class Solution (line 1) | class Solution:
method permuteUnique (line 5) | def permuteUnique(self, nums):
method dfs (line 21) | def dfs(self, nums, ans, path):
method permuteUnique (line 45) | def permuteUnique(self, nums):
method dfs (line 62) | def dfs(self, nums, visited, ans, path):
class Solution (line 41) | class Solution:
method permuteUnique (line 5) | def permuteUnique(self, nums):
method dfs (line 21) | def dfs(self, nums, ans, path):
method permuteUnique (line 45) | def permuteUnique(self, nums):
method dfs (line 62) | def dfs(self, nums, visited, ans, path):
FILE: lintcode/171_anagrams.py
class Solution (line 1) | class Solution:
method anagrams (line 6) | def anagrams(self, S):
FILE: lintcode/175_invert_binary_tree.py
class Solution (line 10) | class Solution:
method invertBinaryTree (line 15) | def invertBinaryTree(self, root):
method divide_conquer (line 18) | def divide_conquer(self, node):
FILE: lintcode/178_graph_valid_tree.py
class Solution (line 1) | class Solution:
method validTree (line 2) | def validTree(self, n, edges):
method find (line 24) | def find(self, nodes, a):
FILE: lintcode/17_subsets.py
class Solution (line 4) | class Solution:
method subsets (line 9) | def subsets(self, A):
method dfs (line 17) | def dfs(self, A, start, ans, subset):
method subsets (line 35) | def subsets(self, A):
class Solution (line 30) | class Solution:
method subsets (line 9) | def subsets(self, A):
method dfs (line 17) | def dfs(self, A, start, ans, subset):
method subsets (line 35) | def subsets(self, A):
FILE: lintcode/183_wood_cut.py
class Solution (line 1) | class Solution:
method woodCut (line 7) | def woodCut(self, L, k):
method check_if_possible (line 37) | def check_if_possible(self, L, size, max_pieces):
FILE: lintcode/18_subsets_ii.py
class Solution (line 4) | class Solution:
method subsetsWithDup (line 9) | def subsetsWithDup(self, A):
method dfs (line 17) | def dfs(self, A, start, ans, subset):
FILE: lintcode/190_next_permutation_ii.py
class Solution (line 1) | class Solution:
method nextPermutation (line 2) | def nextPermutation(self, nums):
FILE: lintcode/191_maximum_product_subarray.py
class Solution (line 9) | class Solution:
method maxProduct (line 14) | def maxProduct(self, A):
FILE: lintcode/192_wildcard_matching.py
class Solution (line 23) | class Solution:
method isMatch (line 24) | def isMatch(self, s, p):
FILE: lintcode/196_find_the_missing_number.py
class Solution (line 1) | class Solution:
method findMissing (line 2) | def findMissing(self, nums):
method findMissing (line 19) | def findMissing(self, nums):
class Solution (line 18) | class Solution:
method findMissing (line 2) | def findMissing(self, nums):
method findMissing (line 19) | def findMissing(self, nums):
FILE: lintcode/197_permutation_index.py
class Solution (line 11) | class Solution:
method permutationIndex (line 16) | def permutationIndex(self, A):
FILE: lintcode/198_permutation_index_ii.py
class Solution (line 10) | class Solution:
method permutationIndexII (line 15) | def permutationIndexII(self, A):
FILE: lintcode/1_a_b_problem.py
class Solution (line 1) | class Solution:
method aplusb (line 7) | def aplusb(self, a, b):
FILE: lintcode/204_singleton.py
class Solution (line 1) | class Solution:
method getInstance (line 6) | def getInstance(cls):
FILE: lintcode/211_string_permutation.py
class Solution (line 1) | class Solution:
method Permutation (line 7) | def Permutation(self, A, B):
FILE: lintcode/215_rate_limiter.py
class Solution (line 4) | class Solution:
method __init__ (line 16) | def __init__(self):
method isRatelimited (line 25) | def isRatelimited(self, timestamp, event, rate, increment):
method check_limited (line 46) | def check_limited(self, event, freq, begin_time):
FILE: lintcode/221_add_two_numbers_ii.py
class Solution (line 10) | class Solution:
method addLists2 (line 11) | def addLists2(self, a, b):
method rev_list (line 57) | def rev_list(self, head):
FILE: lintcode/231_typeahead.py
class Typeahead (line 1) | class Typeahead:
method __init__ (line 5) | def __init__(self, dict):
method search (line 22) | def search(self, str):
method __init__ (line 89) | def __init__(self, dict):
method search (line 98) | def search(self, str):
class Trie (line 35) | class Trie:
method __init__ (line 36) | def __init__(self):
method new_node (line 39) | def new_node(self):
method put (line 45) | def put(self, key):
method _put (line 51) | def _put(self, word, key):
method search (line 59) | def search(self, key):
class Typeahead (line 85) | class Typeahead:
method __init__ (line 5) | def __init__(self, dict):
method search (line 22) | def search(self, str):
method __init__ (line 89) | def __init__(self, dict):
method search (line 98) | def search(self, str):
FILE: lintcode/232_tiny_url.py
class TinyUrl (line 4) | class TinyUrl:
method __init__ (line 5) | def __init__(self):
method longToShort (line 15) | def longToShort(self, url):
method shortToLong (line 33) | def shortToLong(self, url):
method get_tiny_url (line 48) | def get_tiny_url(self, hash_key):
method get_hash_key (line 51) | def get_hash_key(self, size):
FILE: lintcode/234_webpage_crawler.py
class CrawlerThread (line 8) | class CrawlerThread(Thread):
method run (line 9) | def run(self):
class Solution (line 26) | class Solution:
method crawler (line 29) | def crawler(self, url):
FILE: lintcode/236_swap_bits.py
class Solution (line 1) | class Solution:
method swapOddEvenBits (line 6) | def swapOddEvenBits(self, x):
FILE: lintcode/242_convert_binary_tree_to_linked_lists_by_depth.py
class Solution (line 16) | class Solution:
method binaryTreeToLists (line 19) | def binaryTreeToLists(self, root):
FILE: lintcode/245_subtree.py
class Solution (line 10) | class Solution:
method isSubtree (line 16) | def isSubtree(self, A, B):
method isEqual (line 29) | def isEqual(self, A, B):
FILE: lintcode/246_binary_tree_path_sum_ii.py
class Solution (line 10) | class Solution:
method binaryTreePathSum2 (line 16) | def binaryTreePathSum2(self, root, target):
method dfs (line 21) | def dfs(self, node, target, ans, path):
FILE: lintcode/24_lfu_cache.py
class LFUCache (line 20) | class LFUCache:
method __init__ (line 21) | def __init__(self, capacity):
method get (line 32) | def get(self, key):
method set (line 43) | def set(self, key, val):
method _evict (line 61) | def _evict(self):
method _update (line 69) | def _update(self, key, val=None):
method _add (line 90) | def _add(self, key, val):
class CacheNode (line 104) | class CacheNode:
method __init__ (line 105) | def __init__(self, key, val=None, freq_node=None, pre=None, nxt=None):
method unlink (line 113) | def unlink(self):
class FreqNode (line 119) | class FreqNode:
method __init__ (line 120) | def __init__(self, freq, pre=None, nxt=None):
method unlink (line 130) | def unlink(self):
method after (line 136) | def after(self, freq_node):
method is_empty (line 143) | def is_empty(self):
method pop_head (line 147) | def pop_head(self):
method append_tail (line 156) | def append_tail(self, cache_node):
FILE: lintcode/254_drop_eggs.py
class Solution (line 23) | class Solution:
method dropEggs (line 28) | def dropEggs(self, n):
method dropEggs (line 58) | def dropEggs(self, n):
class Solution (line 53) | class Solution:
method dropEggs (line 28) | def dropEggs(self, n):
method dropEggs (line 58) | def dropEggs(self, n):
FILE: lintcode/272_climbing_stairs_ii.py
class Solution (line 4) | class Solution:
method climbStairs2 (line 9) | def climbStairs2(self, n):
method climbStairs2 (line 30) | def climbStairs2(self, n):
class Solution (line 25) | class Solution:
method climbStairs2 (line 9) | def climbStairs2(self, n):
method climbStairs2 (line 30) | def climbStairs2(self, n):
FILE: lintcode/28_search_a_2d_matrix.py
class Solution (line 1) | class Solution:
method searchMatrix (line 2) | def searchMatrix(self, matrix, target):
FILE: lintcode/29_interleaving_string.py
class Solution (line 1) | class Solution:
method isInterleave (line 8) | def isInterleave(self, A, B, C):
FILE: lintcode/30_insert_interval.py
class Solution (line 18) | class Solution:
method insert (line 19) | def insert(self, intvs, intv):
FILE: lintcode/31_partition_array.py
class Solution (line 1) | class Solution:
method partitionArray (line 7) | def partitionArray(self, A, k):
FILE: lintcode/32_minimum_window_substring.py
class Solution (line 1) | class Solution:
method minWindow (line 2) | def minWindow(self, s, t):
FILE: lintcode/35_reverse_linked_list.py
class Solution (line 12) | class Solution:
method reverse (line 17) | def reverse(self, head):
FILE: lintcode/360_sliding_window_median.py
class HashHeapqWithLazy (line 4) | class HashHeapqWithLazy:
method __init__ (line 5) | def __init__(self):
method __len__ (line 10) | def __len__(self):
method __bool__ (line 13) | def __bool__(self):
method push (line 16) | def push(self, val):
method pop (line 20) | def pop(self):
method remove (line 27) | def remove(self, val):
method top (line 34) | def top(self):
method _is_empty (line 40) | def _is_empty(self):
class Solution (line 48) | class Solution:
method medianSlidingWindow (line 49) | def medianSlidingWindow(self, nums, k):
method get_median (line 83) | def get_median(self):
FILE: lintcode/362_sliding_window_maximum.py
class HashHeapq (line 4) | class HashHeapq:
method __init__ (line 5) | def __init__(self):
method push (line 9) | def push(self, val):
method pop (line 12) | def pop(self):
method remove (line 17) | def remove(self, val):
method top (line 22) | def top(self):
method is_empty (line 27) | def is_empty(self):
class Solution (line 34) | class Solution:
method maxSlidingWindow (line 35) | def maxSlidingWindow(self, A, k):
method maxSlidingWindow (line 66) | def maxSlidingWindow(self, A, k):
class Solution (line 60) | class Solution:
method maxSlidingWindow (line 35) | def maxSlidingWindow(self, A, k):
method maxSlidingWindow (line 66) | def maxSlidingWindow(self, A, k):
FILE: lintcode/363_trapping_rain_water.py
class Solution (line 1) | class Solution:
method trapRainWater (line 6) | def trapRainWater(self, heights):
FILE: lintcode/364_trapping_rain_water_ii.py
class Solution (line 3) | class Solution:
method trapRainWater (line 8) | def trapRainWater(self, heights):
FILE: lintcode/368_expression_evaluation.py
class Solution (line 7) | class Solution:
method evaluateExpression (line 19) | def evaluateExpression(self, E):
method dal2rpn (line 33) | def dal2rpn(self, E):
method eval_rpn (line 80) | def eval_rpn(self, E):
FILE: lintcode/36_reverse_linked_list_ii.py
class Solution (line 11) | class Solution:
method reverseBetween (line 18) | def reverseBetween(self, head, m, n):
FILE: lintcode/376_binary_tree_path_sum.py
class Solution (line 10) | class Solution:
method binaryTreePathSum (line 16) | def binaryTreePathSum(self, root, target):
method dfs (line 21) | def dfs(self, node, remaining, ans, path):
FILE: lintcode/378_convert_binary_search_tree_to_doubly_linked_list.py
class Solution (line 16) | class Solution:
method bstToDoublyList (line 21) | def bstToDoublyList(self, root):
FILE: lintcode/382_triangle_count.py
class Solution (line 1) | class Solution:
method triangleCount (line 6) | def triangleCount(self, S):
FILE: lintcode/384_longest_substring_without_repeating_characters.py
class Solution (line 4) | class Solution:
method lengthOfLongestSubstring (line 5) | def lengthOfLongestSubstring(self, s):
FILE: lintcode/386_longest_substring_with_at_most_k_distinct_characters.py
class Solution (line 4) | class Solution:
method lengthOfLongestSubstringKDistinct (line 5) | def lengthOfLongestSubstringKDistinct(self, s, k):
FILE: lintcode/38_search_a_2d_matrix_ii.py
class Solution (line 7) | class Solution:
method searchMatrix (line 8) | def searchMatrix(self, matrix, target):
method searchMatrix (line 50) | def searchMatrix(self, matrix, target):
class Solution (line 49) | class Solution:
method searchMatrix (line 8) | def searchMatrix(self, matrix, target):
method searchMatrix (line 50) | def searchMatrix(self, matrix, target):
FILE: lintcode/390_find_peak_element_ii.py
class Solution (line 17) | class Solution:
method findPeakII (line 36) | def findPeakII(self, A):
method findColMax (line 70) | def findColMax(self, A, col, up, down):
method findRowMax (line 78) | def findRowMax(self, A, row, left, right):
method isPeak (line 85) | def isPeak(self, A, row, col):
FILE: lintcode/391_number_of_airplanes_in_the_sky.py
class Solution (line 10) | class Solution:
method countOfAirplanes (line 15) | def countOfAirplanes(self, airplanes):
FILE: lintcode/392_house_robber.py
class Solution (line 5) | class Solution:
method houseRobber (line 10) | def houseRobber(self, A):
method houseRobber (line 34) | def houseRobber(self, A):
method houseRobber (line 66) | def houseRobber(self, A):
class Solution (line 29) | class Solution:
method houseRobber (line 10) | def houseRobber(self, A):
method houseRobber (line 34) | def houseRobber(self, A):
method houseRobber (line 66) | def houseRobber(self, A):
class Solution (line 65) | class Solution:
method houseRobber (line 10) | def houseRobber(self, A):
method houseRobber (line 34) | def houseRobber(self, A):
method houseRobber (line 66) | def houseRobber(self, A):
FILE: lintcode/393_best_time_to_buy_and_sell_stock_iv.py
class Solution (line 1) | class Solution:
method maxProfit (line 7) | def maxProfit(self, K, P):
FILE: lintcode/394_coins_in_a_line.py
class Solution (line 25) | class Solution:
method firstWillWin (line 26) | def firstWillWin(self, n):
FILE: lintcode/395_coins_in_a_line_ii.py
class Solution (line 18) | class Solution:
method firstWillWin (line 19) | def firstWillWin(self, values):
FILE: lintcode/396_coins_in_a_line_iii.py
class Solution (line 28) | class Solution:
method firstWillWin (line 29) | def firstWillWin(self, values):
FILE: lintcode/397_longest_increasing_continuous_subsequence.py
class Solution (line 5) | class Solution:
method longestIncreasingContinuousSubsequence (line 10) | def longestIncreasingContinuousSubsequence(self, A):
method get_lics_size (line 20) | def get_lics_size(self, A):
method longestIncreasingContinuousSubsequence (line 58) | def longestIncreasingContinuousSubsequence(self, A):
method get_lics_size (line 68) | def get_lics_size(self, A):
class Solution (line 53) | class Solution:
method longestIncreasingContinuousSubsequence (line 10) | def longestIncreasingContinuousSubsequence(self, A):
method get_lics_size (line 20) | def get_lics_size(self, A):
method longestIncreasingContinuousSubsequence (line 58) | def longestIncreasingContinuousSubsequence(self, A):
method get_lics_size (line 68) | def get_lics_size(self, A):
FILE: lintcode/3_digit_counts.py
class Solution (line 1) | class Solution:
method digitCounts (line 7) | def digitCounts(self, k, n):
method count (line 13) | def count(self, k, a):
FILE: lintcode/401_kth_smallest_number_in_sorted_matrix.py
class Solution (line 3) | class Solution:
method kthSmallest (line 9) | def kthSmallest(self, matrix, k):
FILE: lintcode/402_continuous_subarray_sum.py
class Solution (line 1) | class Solution:
method continuousSubarraySum (line 6) | def continuousSubarraySum(self, A):
FILE: lintcode/406_minimum_size_subarray_sum.py
class Solution (line 1) | class Solution:
method minimumSize (line 7) | def minimumSize(self, nums, s):
FILE: lintcode/40_implement_queue_by_two_stacks.py
class MyQueue (line 1) | class MyQueue:
method __init__ (line 2) | def __init__(self, ):
method push (line 10) | def push(self, element):
method pop (line 16) | def pop(self, ):
method top (line 23) | def top(self, ):
FILE: lintcode/414_divide_two_integers.py
class Solution (line 1) | class Solution:
method divide (line 2) | def divide(self, a, b):
FILE: lintcode/415_valid_palindrome.py
class Solution (line 1) | class Solution:
method isPalindrome (line 2) | def isPalindrome(self, s):
FILE: lintcode/417_valid_number.py
class Solution (line 1) | class Solution:
method isNumber (line 6) | def isNumber(self, s):
FILE: lintcode/418_integer_to_roman.py
class Solution (line 1) | class Solution:
method intToRoman (line 2) | def intToRoman(self, num):
FILE: lintcode/419_roman_to_integer.py
class Solution (line 1) | class Solution:
method romanToInt (line 2) | def romanToInt(self, s):
FILE: lintcode/41_maximum_subarray.py
class Solution (line 4) | class Solution:
method maxSubArray (line 9) | def maxSubArray(self, A):
method maxSubArray (line 43) | def maxSubArray(self, A):
class Solution (line 38) | class Solution:
method maxSubArray (line 9) | def maxSubArray(self, A):
method maxSubArray (line 43) | def maxSubArray(self, A):
FILE: lintcode/42_maximum_subarray_ii.py
class Solution (line 16) | class Solution:
method maxTwoSubArrays (line 17) | def maxTwoSubArrays(self, nums):
method get_max_sums (line 40) | def get_max_sums(self, nums, num_range):
FILE: lintcode/430_scramble_string.py
class Solution (line 1) | class Solution:
method isScramble (line 7) | def isScramble(self, s1, s2):
FILE: lintcode/431_connected_component_in_undirected_graph.py
class Solution (line 10) | class Solution:
method connectedSet (line 14) | def connectedSet(self, nodes):
method union (line 41) | def union(self, nodes, a, b):
method find (line 48) | def find(self, nodes, a):
method connectedSet (line 63) | def connectedSet(self, nodes):
method dfs (line 85) | def dfs(self, a, visited, path):
class Solution (line 59) | class Solution:
method connectedSet (line 14) | def connectedSet(self, nodes):
method union (line 41) | def union(self, nodes, a, b):
method find (line 48) | def find(self, nodes, a):
method connectedSet (line 63) | def connectedSet(self, nodes):
method dfs (line 85) | def dfs(self, a, visited, path):
FILE: lintcode/432_find_the_weak_connected_component_in_the_directed_graph.py
class Solution (line 10) | class Solution:
method __init__ (line 11) | def __init__(self):
method connectedSet2 (line 18) | def connectedSet2(self, nodes):
method connect (line 34) | def connect(self, a, b):
method find (line 40) | def find(self, a):
FILE: lintcode/433_number_of_islands.py
class Solution (line 1) | class Solution:
method numIslands (line 2) | def numIslands(self, grid):
method dfs (line 22) | def dfs(self, grid, x, y):
FILE: lintcode/434_number_of_islands_ii.py
class Solution (line 10) | class Solution:
method numIslands2 (line 11) | def numIslands2(self, m, n, operators):
method union (line 54) | def union(self, nodes, a, b):
method find (line 64) | def find(self, nodes, a):
FILE: lintcode/437_copy_books.py
class Solution (line 4) | class Solution:
method copyBooks (line 10) | def copyBooks(self, P, k):
method copyBooks (line 69) | def copyBooks(self, P, k):
method copyBooks (line 146) | def copyBooks(self, P, k):
method check_if_possible (line 175) | def check_if_possible(self, P, spent_time, max_copiers):
class Solution (line 63) | class Solution:
method copyBooks (line 10) | def copyBooks(self, P, k):
method copyBooks (line 69) | def copyBooks(self, P, k):
method copyBooks (line 146) | def copyBooks(self, P, k):
method check_if_possible (line 175) | def check_if_possible(self, P, spent_time, max_copiers):
class Solution (line 140) | class Solution:
method copyBooks (line 10) | def copyBooks(self, P, k):
method copyBooks (line 69) | def copyBooks(self, P, k):
method copyBooks (line 146) | def copyBooks(self, P, k):
method check_if_possible (line 175) | def check_if_possible(self, P, spent_time, max_copiers):
FILE: lintcode/43_maximum_subarray_iii.py
class Solution (line 6) | class Solution:
method maxSubArray (line 12) | def maxSubArray(self, A, k):
FILE: lintcode/440_backpack_iii.py
class Solution (line 4) | class Solution:
method backPackIII (line 11) | def backPackIII(self, A, V, m):
method backPackIII (line 39) | def backPackIII(self, A, V, m):
class Solution (line 32) | class Solution:
method backPackIII (line 11) | def backPackIII(self, A, V, m):
method backPackIII (line 39) | def backPackIII(self, A, V, m):
FILE: lintcode/442_implement_trie.py
class TrieNode (line 1) | class TrieNode:
method __init__ (line 2) | def __init__(self):
class Trie (line 7) | class Trie:
method __init__ (line 8) | def __init__(self):
method insert (line 15) | def insert(self, word):
method search (line 33) | def search(self, word):
method startsWith (line 51) | def startsWith(self, prefix):
FILE: lintcode/443_two_sum_greater_than_target.py
class Solution (line 1) | class Solution:
method twoSum2 (line 7) | def twoSum2(self, A, target):
FILE: lintcode/447_search_in_a_big_sorted_array.py
class Solution (line 14) | class Solution:
method searchBigSortedArray (line 20) | def searchBigSortedArray(self, reader, target):
FILE: lintcode/450_reverse_nodes_in_k_group.py
class Solution (line 10) | class Solution:
method reverseKGroup (line 16) | def reverseKGroup(self, head, k):
method find_kth (line 29) | def find_kth(self, head, k):
method reverse (line 36) | def reverse(self, head):
method reverse_next_kth (line 45) | def reverse_next_kth(self, head, k):
FILE: lintcode/453_flatten_binary_tree_to_linked_list.py
class Solution (line 32) | class Solution:
method flatten (line 37) | def flatten(self, root):
FILE: lintcode/457_classical_binary_search.py
class Solution (line 1) | class Solution:
method findPosition (line 7) | def findPosition(self, A, target):
FILE: lintcode/458_last_position_of_target.py
class Solution (line 1) | class Solution:
method lastPosition (line 7) | def lastPosition(self, nums, target):
FILE: lintcode/459_closest_number_in_sorted_array.py
class Solution (line 1) | class Solution:
method closestNumber (line 7) | def closestNumber(self, A, target):
FILE: lintcode/45_maximum_subarray_difference.py
class Solution (line 1) | class Solution:
method maxDiffSubArrays (line 6) | def maxDiffSubArrays(self, A):
method get_sum (line 27) | def get_sum(self, A, scope, factor):
FILE: lintcode/460_k_closest_numbers_in_sorted_array.py
class Solution (line 1) | class Solution:
method kClosestNumbers (line 8) | def kClosestNumbers(self, A, target, k):
FILE: lintcode/461_kth_smallest_numbers_in_unsorted_array.py
class Solution (line 1) | class Solution:
method kthSmallest (line 7) | def kthSmallest(self, K, A):
method quick_select (line 13) | def quick_select(self, k, A, start, end):
FILE: lintcode/462_total_occurrence_of_target.py
class Solution (line 1) | class Solution:
method totalOccurrence (line 2) | def totalOccurrence(self, A, target):
FILE: lintcode/465_kth_smallest_sum_in_two_sorted_arrays.py
class Solution (line 17) | class Solution:
method kthSmallestSum (line 25) | def kthSmallestSum(self, A, B, k):
FILE: lintcode/469_identical_binary_tree.py
class Solution (line 10) | class Solution:
method isIdentical (line 16) | def isIdentical(self, A, B):
FILE: lintcode/471_top_k_frequent_words.py
class Solution (line 1) | class Solution:
method topKFrequentWords (line 7) | def topKFrequentWords(self, words, k):
FILE: lintcode/472_binary_tree_path_sum_iii.py
class Solution (line 10) | class Solution:
method binaryTreePathSum3 (line 16) | def binaryTreePathSum3(self, root, target):
method dfs (line 26) | def dfs(self, node, target, ans):
method find_path (line 35) | def find_path(self, node, start, remaining, ans, path):
FILE: lintcode/473_add_and_search_word.py
class Trie (line 1) | class Trie:
method __init__ (line 2) | def __init__(self):
method insert (line 5) | def insert(self, string):
method search (line 17) | def search(self, string):
method search_in_regex (line 28) | def search_in_regex(self, string):
method _search_in_regex (line 33) | def _search_in_regex(self, string, parent, i):
class WordDictionary (line 46) | class WordDictionary:
method __init__ (line 47) | def __init__(self):
method addWord (line 54) | def addWord(self, word):
method search (line 63) | def search(self, word):
FILE: lintcode/474_lowest_common_ancestor_ii.py
class Solution (line 14) | class Solution:
method lowestCommonAncestorII (line 15) | def lowestCommonAncestorII(self, root, a, b):
FILE: lintcode/475_binary_tree_maximum_path_sum_ii.py
class Solution (line 10) | class Solution:
method maxPathSum2 (line 11) | def maxPathSum2(self, root):
FILE: lintcode/479_second_max_of_array.py
class Solution (line 1) | class Solution:
method secondMax (line 6) | def secondMax(self, A):
FILE: lintcode/480_binary_tree_paths.py
class Solution (line 10) | class Solution:
method binaryTreePaths (line 11) | def binaryTreePaths(self, root):
method dfs (line 24) | def dfs(self, node, ans, path):
FILE: lintcode/486_merge_k_sorted_arrays.py
class Solution (line 4) | class Solution:
method mergekSortedArrays (line 9) | def mergekSortedArrays(self, G):
FILE: lintcode/494_implement_stack_by_two_queues.py
class Stack (line 4) | class Stack:
method __init__ (line 5) | def __init__(self):
method push (line 12) | def push(self, x):
method pop (line 21) | def pop(self):
method top (line 31) | def top(self):
method isEmpty (line 39) | def isEmpty(self):
FILE: lintcode/496_toy_factory.py
class Toy (line 7) | class Toy:
method talk (line 8) | def talk(self):
class Dog (line 12) | class Dog(Toy):
method talk (line 13) | def talk(self):
class Cat (line 17) | class Cat(Toy):
method talk (line 18) | def talk(self):
class ToyFactory (line 22) | class ToyFactory:
method getToy (line 25) | def getToy(self, type):
FILE: lintcode/497_shape_factory.py
class Shape (line 7) | class Shape:
method draw (line 8) | def draw(self):
class Triangle (line 12) | class Triangle(Shape):
method draw (line 13) | def draw(self):
class Rectangle (line 19) | class Rectangle(Shape):
method draw (line 20) | def draw(self):
class Square (line 26) | class Square(Shape):
method draw (line 27) | def draw(self):
class ShapeFactory (line 34) | class ShapeFactory:
method getShape (line 37) | def getShape(self, shapeType):
FILE: lintcode/498_parking_lot.py
class Vehicle (line 8) | class Vehicle:
method __init__ (line 9) | def __init__(self):
method unpark (line 15) | def unpark(self):
class Motorcycle (line 26) | class Motorcycle(Vehicle):
method __init__ (line 27) | def __init__(self):
class Car (line 32) | class Car(Vehicle):
method __init__ (line 33) | def __init__(self):
class Bus (line 38) | class Bus(Vehicle):
method __init__ (line 39) | def __init__(self):
class Level (line 44) | class Level:
method __init__ (line 45) | def __init__(self, id, m, n):
method get_range (line 51) | def get_range(self, vehicle_type):
method park_vehicle (line 62) | def park_vehicle(self, vehicle):
class ParkingLot (line 93) | class ParkingLot:
method __init__ (line 94) | def __init__(self, k, m, n):
method park_vehicle (line 102) | def park_vehicle(self, vehicle):
method unpark_vehicle (line 115) | def unpark_vehicle(self, vehicle):
FILE: lintcode/499_word_count.py
class WordCount (line 1) | class WordCount:
method mapper (line 4) | def mapper(self, _, line):
method reducer (line 10) | def reducer(self, key, values):
FILE: lintcode/4_ugly_number_ii.py
class Solution (line 11) | class Solution:
method nthUglyNumber (line 12) | def nthUglyNumber(self, n):
FILE: lintcode/500_inverted_index.py
class Solution (line 8) | class Solution:
method invertedIndex (line 11) | def invertedIndex(self, docs):
FILE: lintcode/501_mini_twitter.py
class MiniTwitter (line 11) | class MiniTwitter:
method __init__ (line 12) | def __init__(self):
method postTweet (line 22) | def postTweet(self, user_id, tweet_text):
method getNewsFeed (line 38) | def getNewsFeed(self, user_id):
method getTimeline (line 59) | def getTimeline(self, user_id):
method follow (line 70) | def follow(self, from_id, to_id):
method unfollow (line 84) | def unfollow(self, from_id, to_id):
FILE: lintcode/502_mini_cassandra.py
class MiniCassandra (line 10) | class MiniCassandra:
method insert (line 20) | def insert(self, raw_key, column_key, column_value):
method query (line 32) | def query(self, raw_key, column_start, column_end):
FILE: lintcode/503_anagram_map_reduce.py
class Anagram (line 1) | class Anagram:
method mapper (line 4) | def mapper(self, _, line):
method reducer (line 10) | def reducer(self, key, values):
FILE: lintcode/504_inverted_index_map_reduce.py
class InvertedIndex (line 8) | class InvertedIndex:
method mapper (line 11) | def mapper(self, _, value):
method reducer (line 17) | def reducer(self, key, values):
FILE: lintcode/505_web_logger.py
class WebLogger (line 1) | class WebLogger:
method __init__ (line 2) | def __init__(self):
method hit (line 12) | def hit(self, timestamp):
method get_hit_count_in_last_5_minutes (line 25) | def get_hit_count_in_last_5_minutes(self, timestamp):
FILE: lintcode/509_mini_yelp.py
class MiniYelp (line 67) | class MiniYelp:
method add_restaurant (line 82) | def add_restaurant(self, name, location):
method remove_restaurant (line 94) | def remove_restaurant(self, restaurant_id):
method neighbors (line 106) | def neighbors(self, location, k):
method get_length (line 129) | def get_length(self, k):
method get_restr_hashcode (line 138) | def get_restr_hashcode(self, restaurant):
method add_restaurant (line 216) | def add_restaurant(self, name, location):
method remove_restaurant (line 228) | def remove_restaurant(self, restaurant_id):
method neighbors (line 239) | def neighbors(self, location, k):
method get_length (line 258) | def get_length(self, k):
method get_restr_hashcode (line 267) | def get_restr_hashcode(self, restaurant):
class Trie (line 151) | class Trie:
method __init__ (line 152) | def __init__(self):
method __repr__ (line 155) | def __repr__(self):
method put (line 158) | def put(self, key):
method pick (line 170) | def pick(self, key):
method get_keys_by_prefix (line 182) | def get_keys_by_prefix(self, prefix):
method _new_node (line 194) | def _new_node(self):
class MiniYelp (line 201) | class MiniYelp:
method add_restaurant (line 82) | def add_restaurant(self, name, location):
method remove_restaurant (line 94) | def remove_restaurant(self, restaurant_id):
method neighbors (line 106) | def neighbors(self, location, k):
method get_length (line 129) | def get_length(self, k):
method get_restr_hashcode (line 138) | def get_restr_hashcode(self, restaurant):
method add_restaurant (line 216) | def add_restaurant(self, name, location):
method remove_restaurant (line 228) | def remove_restaurant(self, restaurant_id):
method neighbors (line 239) | def neighbors(self, location, k):
method get_length (line 258) | def get_length(self, k):
method get_restr_hashcode (line 267) | def get_restr_hashcode(self, restaurant):
FILE: lintcode/510_maximal_rectangle.py
class Solution (line 1) | class Solution:
method maximalRectangle (line 2) | def maximalRectangle(self, G):
method maximalRectangle (line 90) | def maximalRectangle(self, G):
method largestRectangleArea (line 116) | def largestRectangleArea(self, H):
class Solution (line 89) | class Solution:
method maximalRectangle (line 2) | def maximalRectangle(self, G):
method maximalRectangle (line 90) | def maximalRectangle(self, G):
method largestRectangleArea (line 116) | def largestRectangleArea(self, H):
FILE: lintcode/512_decode_ways.py
class Solution (line 1) | class Solution:
method numDecodings (line 6) | def numDecodings(self, s):
FILE: lintcode/513_perfect_squares.py
class Solution (line 8) | class Solution:
method numSquares (line 13) | def numSquares(self, n):
FILE: lintcode/515_paint_house.py
class Solution (line 1) | class Solution:
method minCost (line 6) | def minCost(self, costs):
FILE: lintcode/516_paint_house_ii.py
class Solution (line 19) | class Solution:
method minCostII (line 24) | def minCostII(self, C):
FILE: lintcode/517_ugly_number.py
class Solution (line 1) | class Solution:
method isUgly (line 2) | def isUgly(self, num):
FILE: lintcode/518_super_ugly_number.py
class Solution (line 1) | class Solution:
method nthSuperUglyNumber (line 2) | def nthSuperUglyNumber(self, n, primes):
FILE: lintcode/519_consistent_hashing.py
class Solution (line 1) | class Solution:
method consistentHashing (line 6) | def consistentHashing(self, n):
FILE: lintcode/51_previous_permutation.py
class Solution (line 15) | class Solution:
method previousPermuation (line 16) | def previousPermuation(self, nums):
FILE: lintcode/520_consistent_hashing_ii.py
class Solution (line 4) | class Solution:
method create (line 11) | def create(cls, n, k):
method addMachine (line 23) | def addMachine(self, machine_id):
method getMachineIdByHashCode (line 39) | def getMachineIdByHashCode(self, hashcode):
FILE: lintcode/521_remove_duplicate_numbers_in_array.py
class Solution (line 5) | class Solution:
method deduplication (line 10) | def deduplication(self, nums):
method deduplication (line 33) | def deduplication(self, nums):
class Solution (line 28) | class Solution:
method deduplication (line 10) | def deduplication(self, nums):
method deduplication (line 33) | def deduplication(self, nums):
FILE: lintcode/522_tiny_url_ii.py
class TinyUrl2 (line 4) | class TinyUrl2:
method __init__ (line 5) | def __init__(self):
method createCustom (line 18) | def createCustom(self, url, key):
method longToShort (line 43) | def longToShort(self, url):
method shortToLong (line 63) | def shortToLong(self, url):
method get_tiny_url (line 80) | def get_tiny_url(self, hash_key):
method get_hash_key (line 83) | def get_hash_key(self, size):
FILE: lintcode/523_url_parser.py
class HtmlParser (line 3) | class HtmlParser:
method parseUrls (line 8) | def parseUrls(self, content):
FILE: lintcode/525_mini_uber.py
class MiniUber (line 18) | class MiniUber:
method report (line 27) | def report(self, driver_id, lat, lng):
method request (line 43) | def request(self, rider_id, lat, lng):
method _new_location (line 65) | def _new_location(self, lat, lng):
FILE: lintcode/526_load_balancer.py
class LoadBalancer (line 4) | class LoadBalancer:
method __init__ (line 5) | def __init__(self):
method add (line 13) | def add(self, server_id):
method remove (line 21) | def remove(self, server_id):
method pick (line 37) | def pick(self):
FILE: lintcode/527_trie_serialization.py
class Solution (line 10) | class Solution:
method serialize (line 32) | def serialize(self, root):
method deserialize (line 48) | def deserialize(self, data):
FILE: lintcode/528_flatten_nested_list_iterator.py
class NestedIterator (line 27) | class NestedIterator(object):
method __init__ (line 28) | def __init__(self, nestedList):
method next (line 32) | def next(self):
method hasNext (line 42) | def hasNext(self):
FILE: lintcode/529_geohash.py
class GeoHash (line 6) | class GeoHash:
method encode (line 15) | def encode(self, latitude, longitude, precision=5):
method _loc_to_bins (line 35) | def _loc_to_bins(self, location, times, left, right):
method get_base32_list (line 50) | def get_base32_list(self):
FILE: lintcode/52_next_permutation.py
class Solution (line 15) | class Solution:
method nextPermutation (line 16) | def nextPermutation(self, nums):
FILE: lintcode/530_geohash_ii.py
class GeoHash (line 6) | class GeoHash:
method decode (line 13) | def decode(self, geohash):
method _bins_to_loc (line 34) | def _bins_to_loc(self, bins, left, right):
method _oct_to_bins (line 46) | def _oct_to_bins(self, val_in_oct):
method get_base32_list (line 57) | def get_base32_list(self):
FILE: lintcode/531_six_degrees.py
class Solution (line 10) | class Solution:
method sixDegrees (line 17) | def sixDegrees(self, graph, s, t):
FILE: lintcode/532_reverse_pairs.py
class Solution (line 1) | class Solution:
method reversePairs (line 6) | def reversePairs(self, A):
method merge_sort (line 11) | def merge_sort(self, A, start, end, tmp):
FILE: lintcode/533_two_sum_closest_to_target.py
class Solution (line 1) | class Solution:
method twoSumClosest (line 7) | def twoSumClosest(self, nums, target):
FILE: lintcode/534_house_robber_ii.py
class Solution (line 28) | class Solution:
method houseRobber2 (line 33) | def houseRobber2(self, A):
method houseRobber (line 46) | def houseRobber(self, A, start, dp):
method houseRobber2 (line 67) | def houseRobber2(self, A):
method houseRobber (line 86) | def houseRobber(self, A, start, dp):
method houseRobber2 (line 102) | def houseRobber2(self, A):
method rob_in_line (line 118) | def rob_in_line(self, A, start, end):
class Solution (line 62) | class Solution:
method houseRobber2 (line 33) | def houseRobber2(self, A):
method houseRobber (line 46) | def houseRobber(self, A, start, dp):
method houseRobber2 (line 67) | def houseRobber2(self, A):
method houseRobber (line 86) | def houseRobber(self, A, start, dp):
method houseRobber2 (line 102) | def houseRobber2(self, A):
method rob_in_line (line 118) | def rob_in_line(self, A, start, end):
class Solution (line 101) | class Solution:
method houseRobber2 (line 33) | def houseRobber2(self, A):
method houseRobber (line 46) | def houseRobber(self, A, start, dp):
method houseRobber2 (line 67) | def houseRobber2(self, A):
method houseRobber (line 86) | def houseRobber(self, A, start, dp):
method houseRobber2 (line 102) | def houseRobber2(self, A):
method rob_in_line (line 118) | def rob_in_line(self, A, start, end):
FILE: lintcode/538_memcache.py
class Memcache (line 1) | class Memcache:
method get (line 12) | def get(self, curtTime, key):
method set (line 29) | def set(self, curtTime, key, value, ttl):
method delete (line 40) | def delete(self, curtTime, key):
method incr (line 50) | def incr(self, curtTime, key, delta):
method decr (line 67) | def decr(self, curtTime, key, delta):
method _new_item (line 70) | def _new_item(self, key, value, expired_at):
FILE: lintcode/539_move_zeroes.py
class Solution (line 1) | class Solution:
method moveZeroes (line 2) | def moveZeroes(self, nums):
FILE: lintcode/53_reverse_words_in_a_string.py
class Solution (line 1) | class Solution:
method reverseWords (line 6) | def reverseWords(self, s):
FILE: lintcode/540_zigzag_iterator.py
class ZigzagIterator (line 9) | class ZigzagIterator:
method __init__ (line 14) | def __init__(self, v1, v2):
method next (line 23) | def next(self):
method hasNext (line 37) | def hasNext(self):
method __init__ (line 60) | def __init__(self, v1, v2):
method next (line 66) | def next(self):
method hasNext (line 81) | def hasNext(self):
class ZigzagIterator (line 55) | class ZigzagIterator:
method __init__ (line 14) | def __init__(self, v1, v2):
method next (line 23) | def next(self):
method hasNext (line 37) | def hasNext(self):
method __init__ (line 60) | def __init__(self, v1, v2):
method next (line 66) | def next(self):
method hasNext (line 81) | def hasNext(self):
FILE: lintcode/541_zigzag_iterator_ii.py
class ZigzagIterator2 (line 9) | class ZigzagIterator2:
method __init__ (line 13) | def __init__(self, vecs):
method next (line 22) | def next(self):
method hasNext (line 36) | def hasNext(self):
method __init__ (line 58) | def __init__(self, vecs):
method next (line 64) | def next(self):
method hasNext (line 79) | def hasNext(self):
class ZigzagIterator2 (line 54) | class ZigzagIterator2:
method __init__ (line 13) | def __init__(self, vecs):
method next (line 22) | def next(self):
method hasNext (line 36) | def hasNext(self):
method __init__ (line 58) | def __init__(self, vecs):
method next (line 64) | def next(self):
method hasNext (line 79) | def hasNext(self):
FILE: lintcode/543_kth_largest_in_n_arrays.py
class Solution (line 3) | class Solution:
method KthInArrays (line 10) | def KthInArrays(self, arrays, k):
FILE: lintcode/544_top_k_largest_numbers.py
class Solution (line 4) | class Solution:
method topk (line 10) | def topk(self, nums, k):
FILE: lintcode/545_top_k_largest_numbers_ii.py
class Solution (line 4) | class Solution:
method __init__ (line 8) | def __init__(self, k):
method add (line 16) | def add(self, num):
method topk (line 27) | def topk(self):
FILE: lintcode/547_intersection_of_two_arrays.py
class Solution (line 1) | class Solution:
method intersection (line 2) | def intersection(self, a, b):
method intersection (line 24) | def intersection(self, a, b):
class Solution (line 23) | class Solution:
method intersection (line 2) | def intersection(self, a, b):
method intersection (line 24) | def intersection(self, a, b):
FILE: lintcode/548_intersection_of_two_arrays_ii.py
class Solution (line 1) | class Solution:
method intersect (line 2) | def intersect(self, a, b):
method intersect (line 29) | def intersect(self, a, b):
class Solution (line 28) | class Solution:
method intersect (line 2) | def intersect(self, a, b):
method intersect (line 29) | def intersect(self, a, b):
FILE: lintcode/54_string_to_integer_ii.py
class Solution (line 1) | class Solution:
method atoi (line 6) | def atoi(self, s):
FILE: lintcode/551_nested_list_weight_sum.py
class Solution (line 22) | class Solution(object):
method depthSum (line 25) | def depthSum(self, L):
method dfs (line 28) | def dfs(self, L, depth):
method depthSum (line 44) | def depthSum(self, L):
class Solution (line 41) | class Solution(object):
method depthSum (line 25) | def depthSum(self, L):
method dfs (line 28) | def dfs(self, L, depth):
method depthSum (line 44) | def depthSum(self, L):
FILE: lintcode/552_create_maximum_number.py
class Solution (line 1) | class Solution:
method maxNumber (line 2) | def maxNumber(self, a, b, k):
method get_max (line 23) | def get_max(self, a, size):
method merge (line 40) | def merge(self, a, b):
FILE: lintcode/553_bomb_enemy.py
class Solution (line 28) | class Solution:
method maxKilledEnemies (line 33) | def maxKilledEnemies(self, grid):
method maxKilledEnemies (line 82) | def maxKilledEnemies(self, grid):
method get_killed_cnt (line 101) | def get_killed_cnt(self, grid, i, j):
class Solution (line 77) | class Solution:
method maxKilledEnemies (line 33) | def maxKilledEnemies(self, grid):
method maxKilledEnemies (line 82) | def maxKilledEnemies(self, grid):
method get_killed_cnt (line 101) | def get_killed_cnt(self, grid, i, j):
FILE: lintcode/555_counting_bloom_filter.py
class HashFunc (line 4) | class HashFunc:
method __init__ (line 5) | def __init__(self, cap, seed):
method hash (line 9) | def hash(self, key):
class CountingBloomFilter (line 20) | class CountingBloomFilter:
method __init__ (line 21) | def __init__(self, k):
method add (line 36) | def add(self, word):
method remove (line 45) | def remove(self, word):
method contains (line 54) | def contains(self, word):
FILE: lintcode/556_standard_bloom_filter.py
class HashFunc (line 4) | class HashFunc:
method __init__ (line 5) | def __init__(self, cap, seed):
method hash (line 9) | def hash(self, key):
class StandardBloomFilter (line 20) | class StandardBloomFilter:
method __init__ (line 21) | def __init__(self, k):
method add (line 36) | def add(self, word):
method contains (line 45) | def contains(self, word):
FILE: lintcode/559_trie_service.py
class TrieService (line 9) | class TrieService:
method __init__ (line 11) | def __init__(self):
method get_root (line 14) | def get_root(self):
method insert (line 22) | def insert(self, word, frequency):
FILE: lintcode/560_friendship_service.py
class FriendshipService (line 1) | class FriendshipService:
method __init__ (line 2) | def __init__(self):
method getFollowers (line 6) | def getFollowers(self, user_id):
method getFollowings (line 9) | def getFollowings(self, user_id):
method get_followers (line 16) | def get_followers(self, user_id):
method get_followings (line 26) | def get_followings(self, user_id):
method follow (line 37) | def follow(self, to_id, from_id):
method unfollow (line 51) | def unfollow(self, to_id, from_id):
FILE: lintcode/563_backpack_v.py
class Solution (line 4) | class Solution:
method backPackV (line 10) | def backPackV(self, A, target):
method backPackV (line 36) | def backPackV(self, A, target):
class Solution (line 30) | class Solution:
method backPackV (line 10) | def backPackV(self, A, target):
method backPackV (line 36) | def backPackV(self, A, target):
FILE: lintcode/564_backpack_vi.py
class Solution (line 1) | class Solution:
method backPackVI (line 7) | def backPackVI(self, A, target):
FILE: lintcode/565_heart_beat.py
class HeartBeat (line 1) | class HeartBeat:
method __init__ (line 3) | def __init__(self):
method initialize (line 11) | def initialize(self, slaves_ip_list, k):
method ping (line 20) | def ping(self, timestamp, slave_ip):
method getDiedSlaves (line 28) | def getDiedSlaves(self, timestamp):
FILE: lintcode/566_gfs_client.py
class GFSClient (line 11) | class GFSClient(BaseGFSClient):
method __init__ (line 15) | def __init__(self, chunkSize):
method read (line 24) | def read(self, filename):
method write (line 38) | def write(self, filename, content):
FILE: lintcode/56_two_sum.py
class Solution (line 7) | class Solution:
method twoSum (line 13) | def twoSum(self, A, target):
method twoSum (line 43) | def twoSum(self, A, target):
class Solution (line 37) | class Solution:
method twoSum (line 13) | def twoSum(self, A, target):
method twoSum (line 43) | def twoSum(self, A, target):
FILE: lintcode/573_build_post_office_ii.py
class Solution (line 11) | class Solution:
method shortestDistance (line 25) | def shortestDistance(self, grid):
method bfs (line 52) | def bfs(self, grid, x, y, times, steps):
method shortestDistance (line 100) | def shortestDistance(self, grid):
method dfs (line 130) | def dfs(self, grid, x, y, id, ids, steps, step):
class Solution (line 88) | class Solution:
method shortestDistance (line 25) | def shortestDistance(self, grid):
method bfs (line 52) | def bfs(self, grid, x, y, times, steps):
method shortestDistance (line 100) | def shortestDistance(self, grid):
method dfs (line 130) | def dfs(self, grid, x, y, id, ids, steps, step):
FILE: lintcode/574_build_post_office.py
class Solution (line 8) | class Solution:
method shortestDistance (line 29) | def shortestDistance(self, grid):
method get_step (line 73) | def get_step(self, ps, axis, pos):
method shortestDistance (line 109) | def shortestDistance(self, grid):
method get_step (line 156) | def get_step(self, houses, x, y):
method shortestDistance (line 176) | def shortestDistance(self, grid):
method bfs (line 203) | def bfs(self, grid, x, y, steps):
class Solution (line 97) | class Solution:
method shortestDistance (line 29) | def shortestDistance(self, grid):
method get_step (line 73) | def get_step(self, ps, axis, pos):
method shortestDistance (line 109) | def shortestDistance(self, grid):
method get_step (line 156) | def get_step(self, houses, x, y):
method shortestDistance (line 176) | def shortestDistance(self, grid):
method bfs (line 203) | def bfs(self, grid, x, y, steps):
class Solution (line 165) | class Solution:
method shortestDistance (line 29) | def shortestDistance(self, grid):
method get_step (line 73) | def get_step(self, ps, axis, pos):
method shortestDistance (line 109) | def shortestDistance(self, grid):
method get_step (line 156) | def get_step(self, houses, x, y):
method shortestDistance (line 176) | def shortestDistance(self, grid):
method bfs (line 203) | def bfs(self, grid, x, y, steps):
FILE: lintcode/575_expression_expand.py
class Solution (line 1) | class Solution:
method expressionExpand (line 2) | def expressionExpand(self, s):
FILE: lintcode/578_lowest_common_ancestor_iii.py
class Solution (line 14) | class Solution:
method lowestCommonAncestor3 (line 15) | def lowestCommonAncestor3(self, root, a, b):
method divide_conquer (line 29) | def divide_conquer(self, node, a, b):
FILE: lintcode/57_3sum.py
class Solution (line 1) | class Solution:
method threeSum (line 2) | def threeSum(self, nums):
FILE: lintcode/582_word_break_ii.py
class Solution (line 1) | class Solution:
method wordBreak (line 5) | def wordBreak(self, s, words):
method dfs (line 13) | def dfs(self, s, words, memo):
method wordBreak (line 48) | def wordBreak(self, s, words):
method dfs (line 63) | def dfs(self, s, words, ans, path):
class Solution (line 40) | class Solution:
method wordBreak (line 5) | def wordBreak(self, s, words):
method dfs (line 13) | def dfs(self, s, words, memo):
method wordBreak (line 48) | def wordBreak(self, s, words):
method dfs (line 63) | def dfs(self, s, words, ans, path):
FILE: lintcode/584_drop_eggs_ii.py
class Solution (line 6) | class Solution:
method dropEggs2 (line 12) | def dropEggs2(self, m, n):
FILE: lintcode/585_maximum_number_in_mountain_sequence.py
class Solution (line 1) | class Solution:
method mountainSequence (line 6) | def mountainSequence(self, nums):
FILE: lintcode/586_sqrtx_ii.py
class Solution (line 1) | class Solution:
method sqrt (line 6) | def sqrt(self, x):
FILE: lintcode/587_two_sum_unique_pairs.py
class Solution (line 1) | class Solution:
method twoSum6 (line 7) | def twoSum6(self, nums, target):
FILE: lintcode/589_connecting_graph.py
class ConnectingGraph (line 1) | class ConnectingGraph:
method __init__ (line 5) | def __init__(self, n):
method find (line 13) | def find(self, a):
method connect (line 25) | def connect(self, a, b):
method query (line 36) | def query(self, a, b):
FILE: lintcode/58_4sum.py
class Solution (line 1) | class Solution:
method fourSum (line 2) | def fourSum(self, nums, target):
FILE: lintcode/590_connecting_graph_ii.py
class ConnectingGraph2 (line 1) | class ConnectingGraph2:
method __init__ (line 5) | def __init__(self, n):
method find (line 14) | def find(self, a):
method connect (line 25) | def connect(self, a, b):
method query (line 37) | def query(self, a):
FILE: lintcode/591_connecting_graph_iii.py
class ConnectingGraph3 (line 1) | class ConnectingGraph3:
method __init__ (line 5) | def __init__(self, n):
method find (line 13) | def find(self, a):
method connect (line 24) | def connect(self, a, b):
method query (line 34) | def query(self):
FILE: lintcode/594_strstr_ii.py
class Solution (line 34) | class Solution:
method strStr2 (line 35) | def strStr2(self, S, T):
FILE: lintcode/595_binary_tree_longest_consecutive_sequence.py
class Solution (line 13) | class Solution:
method longestConsecutive (line 17) | def longestConsecutive(self, root):
method divide_conquer (line 27) | def divide_conquer(self, node):
method longestConsecutive (line 58) | def longestConsecutive(self, root):
method divide_conquer (line 68) | def divide_conquer(self, node, parent_val, _size):
class Solution (line 54) | class Solution:
method longestConsecutive (line 17) | def longestConsecutive(self, root):
method divide_conquer (line 27) | def divide_conquer(self, node):
method longestConsecutive (line 58) | def longestConsecutive(self, root):
method divide_conquer (line 68) | def divide_conquer(self, node, parent_val, _size):
FILE: lintcode/596_minimum_subtree.py
class Solution (line 10) | class Solution:
method findSubtree (line 18) | def findSubtree(self, root):
method _traversal (line 22) | def _traversal(self, node):
FILE: lintcode/597_subtree_with_maximum_average.py
class Solution (line 19) | class Solution:
method findSubtree2 (line 27) | def findSubtree2(self, root):
method _traversal (line 31) | def _traversal(self, node):
FILE: lintcode/598_zombie_in_matrix.py
class Solution (line 1) | class Solution:
method zombie (line 10) | def zombie(self, grid):
FILE: lintcode/599_insert_into_a_cyclic_sorted_list.py
class Solution (line 11) | class Solution:
method insert (line 17) | def insert(self, node, x):
FILE: lintcode/59_3sum_closest.py
class Solution (line 1) | class Solution:
method threeSumClosest (line 2) | def threeSumClosest(self, nums, target):
FILE: lintcode/5_kth_largest_element.py
class Solution (line 1) | class Solution:
method kthLargestElement (line 3) | def kthLargestElement(self, k, nums):
FILE: lintcode/600_smallest_rectangle_enclosing_black_pixels.py
class Solution (line 1) | class Solution:
method minArea (line 2) | def minArea(self, image, x, y):
method binary_search (line 21) | def binary_search(self, image, start, end, is_empty):
method is_empty_row (line 39) | def is_empty_row(self, image, x):
method is_empty_col (line 45) | def is_empty_col(self, image, y):
FILE: lintcode/601_flatten_2d_vector.py
class Vector2D (line 8) | class Vector2D:
method __init__ (line 10) | def __init__(self, vec2d):
method next (line 16) | def next(self):
method hasNext (line 29) | def hasNext(self):
FILE: lintcode/602_russian_doll_envelopes.py
class Solution (line 9) | class Solution:
method maxEnvelopes (line 14) | def maxEnvelopes(self, E):
method maxEnvelopes (line 39) | def maxEnvelopes(self, E):
class Solution (line 34) | class Solution:
method maxEnvelopes (line 14) | def maxEnvelopes(self, E):
method maxEnvelopes (line 39) | def maxEnvelopes(self, E):
FILE: lintcode/603_largest_divisible_subset.py
class Solution (line 1) | class Solution:
method largestDivisibleSubset (line 2) | def largestDivisibleSubset(self, A):
FILE: lintcode/604_window_sum.py
class Solution (line 1) | class Solution:
method winSum (line 7) | def winSum(self, A, k):
FILE: lintcode/605_sequence_reconstruction.py
class Solution (line 10) | class Solution:
method sequenceReconstruction (line 11) | def sequenceReconstruction(self, org, seqs):
FILE: lintcode/606_kth_largest_element_ii.py
class Solution (line 4) | class Solution:
method kthLargestElement2 (line 10) | def kthLargestElement2(self, nums, k):
FILE: lintcode/607_two_sum_data_structure_design.py
class TwoSum (line 1) | class TwoSum:
method add (line 8) | def add(self, number):
method find (line 18) | def find(self, value):
FILE: lintcode/608_two_sum_input_array_is_sorted.py
class Solution (line 5) | class Solution:
method twoSum (line 11) | def twoSum(self, A, target):
method twoSum (line 38) | def twoSum(self, A, target):
class Solution (line 32) | class Solution:
method twoSum (line 11) | def twoSum(self, A, target):
method twoSum (line 38) | def twoSum(self, A, target):
FILE: lintcode/609_two_sum_less_than_or_equal_to_target.py
class Solution (line 1) | class Solution:
method twoSum5 (line 7) | def twoSum5(self, nums, target):
FILE: lintcode/610_two_sum_difference_equals_to_target.py
class Solution (line 7) | class Solution:
method twoSum7 (line 13) | def twoSum7(self, A, target):
method twoSum7 (line 57) | def twoSum7(self, A, target):
class Solution (line 51) | class Solution:
method twoSum7 (line 13) | def twoSum7(self, A, target):
method twoSum7 (line 57) | def twoSum7(self, A, target):
FILE: lintcode/611_knight_shortest_path.py
class Solution (line 10) | class Solution:
method shortestPath (line 28) | def shortestPath(self, G, S, T):
FILE: lintcode/612_k_closest_points.py
class Solution (line 11) | class Solution:
method kClosest (line 15) | def kClosest(self, points, origin, k):
method get_distance (line 38) | def get_distance(self, p, q):
method kClosest (line 51) | def kClosest(self, points, origin, k):
method get_distance (line 77) | def get_distance(self, p, q):
class Solution (line 47) | class Solution:
method kClosest (line 15) | def kClosest(self, points, origin, k):
method get_distance (line 38) | def get_distance(self, p, q):
method kClosest (line 51) | def kClosest(self, points, origin, k):
method get_distance (line 77) | def get_distance(self, p, q):
FILE: lintcode/613_high_five.py
class Solution (line 11) | class Solution:
method highFive (line 15) | def highFive(self, results):
FILE: lintcode/614_binary_tree_longest_consecutive_sequence_ii.py
class Solution (line 17) | class Solution:
method longestConsecutive2 (line 21) | def longestConsecutive2(self, root):
method divide_conquer (line 31) | def divide_conquer(self, node):
FILE: lintcode/615_course_schedule.py
class Solution (line 1) | class Solution:
method canFinish (line 2) | def canFinish(self, n, P):
FILE: lintcode/616_course_schedule_ii.py
class Solution (line 1) | class Solution:
method findOrder (line 2) | def findOrder(self, n, prerequisites):
FILE: lintcode/617_maximum_average_subarray.py
class Solution (line 32) | class Solution:
method maxAverage (line 33) | def maxAverage(self, nums, k):
method is_valid (line 64) | def is_valid(self, nums, k, mid, s):
FILE: lintcode/618_search_graph_nodes.py
class Solution (line 18) | class Solution:
method searchNode (line 26) | def searchNode(self, graph, values, node, target):
FILE: lintcode/619_binary_tree_longest_consecutive_sequence_iii.py
class Solution (line 13) | class Solution:
method longestConsecutive3 (line 17) | def longestConsecutive3(self, root):
method divide_conquer (line 27) | def divide_conquer(self, node):
FILE: lintcode/61_search_for_a_range.py
class Solution (line 1) | class Solution:
method searchRange (line 7) | def searchRange(self, A, target):
FILE: lintcode/620_maximum_subarray_iv.py
class Solution (line 1) | class Solution:
method maxSubarray4 (line 7) | def maxSubarray4(self, A, k):
FILE: lintcode/621_maximum_subarray_v.py
class Solution (line 15) | class Solution:
method maxSubarray5 (line 22) | def maxSubarray5(self, A, k1, k2):
FILE: lintcode/622_frog_jump.py
class Solution (line 4) | class Solution:
method canCross (line 5) | def canCross(self, stones):
method canCross (line 40) | def canCross(self, stones):
class Solution (line 39) | class Solution:
method canCross (line 5) | def canCross(self, stones):
method canCross (line 40) | def canCross(self, stones):
FILE: lintcode/623_k_edit_distance.py
class TrieNode (line 1) | class TrieNode:
method __init__ (line 2) | def __init__(self):
class Trie (line 7) | class Trie:
method __init__ (line 8) | def __init__(self):
method put (line 11) | def put(self, word):
class Solution (line 26) | class Solution:
method kDistance (line 27) | def kDistance(self, words, target, k):
method dfs (line 46) | def dfs(self, node, k, target, ans, pre):
FILE: lintcode/624_remove_substrings.py
class Solution (line 1) | class Solution:
method minLength (line 7) | def minLength(self, s, D):
FILE: lintcode/625_partition_array_ii.py
class Solution (line 4) | class Solution:
method partition2 (line 11) | def partition2(self, A, low, high):
FILE: lintcode/630_knight_shortest_path_ii.py
class Solution (line 4) | class Solution:
method shortestPath2 (line 9) | def shortestPath2(self, G):
method shortestPath2 (line 50) | def shortestPath2(self, G):
class Solution (line 45) | class Solution:
method shortestPath2 (line 9) | def shortestPath2(self, G):
method shortestPath2 (line 50) | def shortestPath2(self, G):
FILE: lintcode/633_find_the_duplicate_number.py
class Solution (line 10) | class Solution:
method findDuplicate (line 11) | def findDuplicate(self, A):
method after_dup (line 34) | def after_dup(self, A, mid):
method findDuplicate (line 70) | def findDuplicate(self, A):
class Solution (line 65) | class Solution:
method findDuplicate (line 11) | def findDuplicate(self, A):
method after_dup (line 34) | def after_dup(self, A, mid):
method findDuplicate (line 70) | def findDuplicate(self, A):
FILE: lintcode/634_word_squares.py
class Solution (line 10) | class Solution:
method wordSquares (line 11) | def wordSquares(self, words):
method dfs (line 24) | def dfs(self, words, n, ans, path):
method is_valid (line 38) | def is_valid(self, path):
FILE: lintcode/635_boggle_game.py
class TrieNode (line 1) | class TrieNode:
method __init__ (line 2) | def __init__(self):
class Solution (line 7) | class Solution:
method boggleGame (line 8) | def boggleGame(self, board, words):
method dfs (line 36) | def dfs(self, board, i, j, root, visited, cnt):
method find_next_words (line 55) | def find_next_words(self, board, x, y, visited, cnt, node, next_words,...
method put (line 84) | def put(self, root, word):
FILE: lintcode/636_132_pattern.py
class Solution (line 1) | class Solution:
method find132pattern (line 6) | def find132pattern(self, A):
FILE: lintcode/646_first_position_unique_character.py
class Solution (line 1) | class Solution:
method firstUniqChar (line 6) | def firstUniqChar(self, s):
FILE: lintcode/647_substring_anagrams.py
class Solution (line 6) | class Solution:
method findAnagrams (line 7) | def findAnagrams(self, s, t):
FILE: lintcode/64_merge_sorted_array.py
class Solution (line 1) | class Solution:
method mergeSortedArray (line 2) | def mergeSortedArray(self, a, m, b, n):
FILE: lintcode/654_sparse_matrix_multiplication.py
class Solution (line 1) | class Solution:
method multiply (line 7) | def multiply(self, A, B):
FILE: lintcode/655_big_integer_addition.py
class Solution (line 1) | class Solution:
method addStrings (line 2) | def addStrings(self, a, b):
FILE: lintcode/656_big_integer_multiplication.py
class Solution (line 1) | class Solution:
method multiply (line 2) | def multiply(self, a, b):
FILE: lintcode/65_median_of_two_sorted_arrays.py
class Solution (line 7) | class Solution:
method findMedianSortedArrays (line 8) | def findMedianSortedArrays(self, a, b):
method findMedianSortedArrays (line 51) | def findMedianSortedArrays(self, A, B):
method find_kth (line 61) | def find_kth(self, A, i, B, j, k):
class Solution (line 45) | class Solution:
method findMedianSortedArrays (line 8) | def findMedianSortedArrays(self, a, b):
method findMedianSortedArrays (line 51) | def findMedianSortedArrays(self, A, B):
method find_kth (line 61) | def find_kth(self, A, i, B, j, k):
FILE: lintcode/662_guess_number_game.py
class Solution (line 9) | class Solution:
method guessNumber (line 10) | def guessNumber(self, n):
FILE: lintcode/664_counting_bits.py
class Solution (line 1) | class Solution:
method countBits (line 6) | def countBits(self, num):
FILE: lintcode/667_longest_palindromic_subsequence.py
class Solution (line 1) | class Solution:
method longestPalindromeSubseq (line 6) | def longestPalindromeSubseq(self, s):
FILE: lintcode/668_ones_and_zeroes.py
class Solution (line 4) | class Solution:
method findMaxForm (line 11) | def findMaxForm(self, strs, m, n):
method findMaxForm (line 50) | def findMaxForm(self, strs, m, n):
class Solution (line 43) | class Solution:
method findMaxForm (line 11) | def findMaxForm(self, strs, m, n):
method findMaxForm (line 50) | def findMaxForm(self, strs, m, n):
FILE: lintcode/669_coin_change.py
class Solution (line 1) | class Solution:
method coinChange (line 5) | def coinChange(self, coins, amount):
method coinChange (line 44) | def coinChange(self, coins, amount):
class Solution (line 40) | class Solution:
method coinChange (line 5) | def coinChange(self, coins, amount):
method coinChange (line 44) | def coinChange(self, coins, amount):
FILE: lintcode/66_binary_tree_preorder_traversal.py
class Solution (line 10) | class Solution:
method preorderTraversal (line 15) | def preorderTraversal(self, root):
method _traversal (line 22) | def _traversal(self, node, res):
FILE: lintcode/676_decode_ways_ii.py
class Solution (line 1) | class Solution:
method numDecodings (line 6) | def numDecodings(self, s):
FILE: lintcode/67_binary_tree_inorder_traversal.py
class Solution (line 10) | class Solution:
method inorderTraversal (line 15) | def inorderTraversal(self, root):
method _traversal (line 22) | def _traversal(self, node, res):
FILE: lintcode/689_two_sum_bst_edtion.py
class Solution (line 10) | class Solution:
method twoSum (line 16) | def twoSum(self, root, n):
method pre (line 34) | def pre(self):
method nxt (line 56) | def nxt(self):
FILE: lintcode/68_binary_tree_postorder_traversal.py
class Solution (line 10) | class Solution:
method postorderTraversal (line 15) | def postorderTraversal(self, root):
FILE: lintcode/69_binary_tree_level_order_traversal.py
class Solution (line 17) | class Solution:
method levelOrder (line 18) | def levelOrder(self, root):
FILE: lintcode/6_merge_two_sorted_arrays.py
class Solution (line 1) | class Solution:
method mergeSortedArray (line 7) | def mergeSortedArray(self, A, B):
FILE: lintcode/70_binary_tree_level_order_traversal_ii.py
class Solution (line 10) | class Solution:
method levelOrderBottom (line 15) | def levelOrderBottom(self, root):
method dfs (line 33) | def dfs(self, node, ans, preorder, parent_at):
FILE: lintcode/717_tree_longest_path_with_same_value.py
class Solution (line 6) | class Solution:
method LongestPathWithSameValue (line 7) | def LongestPathWithSameValue(self, a, e):
method dfs (line 28) | def dfs(self, root, curr, a, neibs):
FILE: lintcode/718_repeat_string.py
class Solution (line 1) | class Solution:
method repeatedString (line 2) | def repeatedString(self, a, b):
FILE: lintcode/71_binary_tree_zigzag_level_order_traversal.py
class Solution (line 10) | class Solution:
method zigzagLevelOrder (line 15) | def zigzagLevelOrder(self, root):
FILE: lintcode/724_minimum_partition.py
class Solution (line 1) | class Solution:
method findMin (line 2) | def findMin(self, nums):
FILE: lintcode/725_boolean_parenthesization.py
class Solution (line 6) | class Solution:
method countParenth (line 7) | def countParenth(self, symb, oper):
FILE: lintcode/729_last_digit_by_factorial_divide.py
class Solution (line 1) | class Solution:
method computeLastDigit (line 2) | def computeLastDigit(self, a, b):
FILE: lintcode/745_palindromic_ranges.py
class Solution (line 1) | class Solution:
method PalindromicRanges (line 2) | def PalindromicRanges(self, left, right):
method is_palindrome (line 31) | def is_palindrome(self, num):
FILE: lintcode/74_first_bad_version.py
class Solution (line 16) | class Solution:
method findFirstBadVersion (line 17) | def findFirstBadVersion(self, n):
FILE: lintcode/752_rogue_knight_sven.py
class Solution (line 1) | class Solution:
method getNumberOfWays (line 2) | def getNumberOfWays(self, n, m, limit, cost):
FILE: lintcode/75_find_peak_element.py
class Solution (line 1) | class Solution:
method findPeak (line 2) | def findPeak(self, nums):
FILE: lintcode/76_longest_increasing_subsequence.py
class Solution (line 4) | class Solution:
method longestIncreasingSubsequence (line 5) | def longestIncreasingSubsequence(self, A):
method binary_search (line 39) | def binary_search(self, P, a):
method longestIncreasingSubsequence (line 56) | def longestIncreasingSubsequence(self, A):
class Solution (line 55) | class Solution:
method longestIncreasingSubsequence (line 5) | def longestIncreasingSubsequence(self, A):
method binary_search (line 39) | def binary_search(self, P, a):
method longestIncreasingSubsequence (line 56) | def longestIncreasingSubsequence(self, A):
FILE: lintcode/772_group_anagrams.py
class Solution (line 1) | class Solution:
method groupAnagrams (line 6) | def groupAnagrams(self, s):
FILE: lintcode/775_palindrome_pairs.py
class Solution (line 9) | class Solution:
method palindromePairs (line 10) | def palindromePairs(self, words):
method is_palindrome (line 48) | def is_palindrome(self, word):
method palindromePairs (line 66) | def palindromePairs(self, words):
method is_palindrome (line 88) | def is_palindrome(self, words, i, j):
method palindromePairs (line 112) | def palindromePairs(self, words):
method is_palindrome (line 134) | def is_palindrome(self, s):
class Solution (line 65) | class Solution:
method palindromePairs (line 10) | def palindromePairs(self, words):
method is_palindrome (line 48) | def is_palindrome(self, word):
method palindromePairs (line 66) | def palindromePairs(self, words):
method is_palindrome (line 88) | def is_palindrome(self, words, i, j):
method palindromePairs (line 112) | def palindromePairs(self, words):
method is_palindrome (line 134) | def is_palindrome(self, s):
class Solution (line 111) | class Solution:
method palindromePairs (line 10) | def palindromePairs(self, words):
method is_palindrome (line 48) | def is_palindrome(self, word):
method palindromePairs (line 66) | def palindromePairs(self, words):
method is_palindrome (line 88) | def is_palindrome(self, words, i, j):
method palindromePairs (line 112) | def palindromePairs(self, words):
method is_palindrome (line 134) | def is_palindrome(self, s):
FILE: lintcode/776_strobogrammatic_number_ii.py
class Solution (line 1) | class Solution:
method findStrobogrammatic (line 2) | def findStrobogrammatic(self, n):
FILE: lintcode/77_longest_common_subsequence.py
class Solution (line 1) | class Solution:
method longestCommonSubsequence (line 7) | def longestCommonSubsequence(self, A, B):
FILE: lintcode/784_the_longest_common_prefix_ii.py
class Solution (line 1) | class Solution:
method theLongestCommonPrefix (line 7) | def theLongestCommonPrefix(self, D, target):
FILE: lintcode/790_parser.py
class Solution (line 1) | class Solution:
method canBeGenerated (line 8) | def canBeGenerated(self, S, start, end):
method dfs (line 22) | def dfs(self, N, end, s):
FILE: lintcode/791_merge_number.py
class Solution (line 4) | class Solution:
method mergeNumber (line 9) | def mergeNumber(self, A):
FILE: lintcode/792_kth_prime_number.py
class Solution (line 1) | class Solution:
method kthPrime (line 6) | def kthPrime(self, n):
FILE: lintcode/793_intersection_of_arrays.py
class Solution (line 1) | class Solution:
method intersectionOfArrays (line 6) | def intersectionOfArrays(self, A):
FILE: lintcode/7_binary_tree_serialization.py
class Solution (line 10) | class Solution:
method serialize (line 13) | def serialize(self, root):
method deserialize (line 39) | def deserialize(self, data):
FILE: lintcode/813_find_anagram_mappings.py
class Solution (line 4) | class Solution:
method anagramMappings (line 5) | def anagramMappings(self, a, b):
method anagramMappings (line 34) | def anagramMappings(self, a, b):
class Solution (line 33) | class Solution:
method anagramMappings (line 5) | def anagramMappings(self, a, b):
method anagramMappings (line 34) | def anagramMappings(self, a, b):
FILE: lintcode/81_data_stream_median.py
class Solution (line 4) | class Solution:
method medianII (line 5) | def medianII(self, nums):
FILE: lintcode/823_input_stream.py
class Solution (line 6) | class Solution:
method inputStream (line 7) | def inputStream(self, a, b):
method inputStream (line 53) | def inputStream(self, a, b):
class Solution (line 52) | class Solution:
method inputStream (line 7) | def inputStream(self, a, b):
method inputStream (line 53) | def inputStream(self, a, b):
FILE: lintcode/824_single_number_iv.py
class Solution (line 1) | class Solution:
method getSingleNumber (line 2) | def getSingleNumber(self, nums):
FILE: lintcode/826_computer_maintenance.py
class Solution (line 1) | class Solution:
method maintenance (line 8) | def maintenance(self, m, n, P):
FILE: lintcode/830_string_sort.py
class Solution (line 1) | class Solution:
method stringSort (line 6) | def stringSort(self, s):
FILE: lintcode/831_3sum_ii.py
class Solution (line 1) | class Solution:
method threeSum2 (line 6) | def threeSum2(self, n):
method threeSum2 (line 48) | def threeSum2(self, n):
class Solution (line 43) | class Solution:
method threeSum2 (line 6) | def threeSum2(self, n):
method threeSum2 (line 48) | def threeSum2(self, n):
FILE: lintcode/832_count_negative_number.py
class Solution (line 1) | class Solution:
method countNumber (line 6) | def countNumber(self, g):
FILE: lintcode/833_process_sequence.py
class Solution (line 1) | class Solution:
method numberOfProcesses (line 7) | def numberOfProcesses(self, logs, queries):
FILE: lintcode/85_insert_node_in_a_binary_search_tree.py
class Solution (line 11) | class Solution:
method insertNode (line 17) | def insertNode(self, root, node):
method insertNode (line 36) | def insertNode(self, root, node):
class Solution (line 30) | class Solution:
method insertNode (line 17) | def insertNode(self, root, node):
method insertNode (line 36) | def insertNode(self, root, node):
FILE: lintcode/86_binary_search_tree_iterator.py
class BSTIterator (line 16) | class BSTIterator:
method __init__ (line 20) | def __init__(self, root):
method hasNext (line 27) | def hasNext(self):
method next (line 33) | def next(self):
FILE: lintcode/87_remove_node_in_binary_search_tree.py
class Solution (line 14) | class Solution:
method removeNode (line 20) | def removeNode(self, root, target):
method find_min (line 43) | def find_min(self, node):
FILE: lintcode/88_lowest_common_ancestor.py
class Solution (line 14) | class Solution:
method lowestCommonAncestor (line 15) | def lowestCommonAncestor(self, root, a, b):
FILE: lintcode/89_k_sum.py
class Solution (line 1) | class Solution:
method kSum (line 8) | def kSum(self, A, K, target):
FILE: lintcode/8_rotate_string.py
class Solution (line 1) | class Solution:
method rotateString (line 7) | def rotateString(self, S, x):
method reverse (line 17) | def reverse(self, S, start, end):
FILE: lintcode/900_closest_binary_search_tree_value.py
class Solution (line 10) | class Solution:
method closestValue (line 11) | def closestValue(self, root, target):
FILE: lintcode/901_closest_binary_search_tree_value_ii.py
class Solution (line 10) | class Solution:
method closestKValues (line 11) | def closestKValues(self, root, target, k):
method inorder_traverse (line 54) | def inorder_traverse(self, root, vals):
FILE: lintcode/919_meeting_rooms_ii.py
class Solution (line 10) | class Solution:
method minMeetingRooms (line 11) | def minMeetingRooms(self, intervals):
FILE: lintcode/920_meeting_rooms.py
class Solution (line 15) | class Solution:
method canAttendMeetings (line 16) | def canAttendMeetings(self, intervals):
method canAttendMeetings (line 49) | def canAttendMeetings(self, intervals):
class Solution (line 48) | class Solution:
method canAttendMeetings (line 16) | def canAttendMeetings(self, intervals):
method canAttendMeetings (line 49) | def canAttendMeetings(self, intervals):
FILE: lintcode/92_backpack.py
class Solution (line 1) | class Solution:
method backPack (line 5) | def backPack(self, m, A):
FILE: lintcode/93_balanced_binary_tree.py
class Solution (line 10) | class Solution:
method isBalanced (line 15) | def isBalanced(self, root):
method _divide_conquer (line 18) | def _divide_conquer(self, node):
FILE: lintcode/95_validate_binary_search_tree.py
class Solution (line 17) | class Solution:
method isValidBST (line 18) | def isValidBST(self, root):
method isValidBST (line 48) | def isValidBST(self, root):
class Solution (line 44) | class Solution:
method isValidBST (line 18) | def isValidBST(self, root):
method isValidBST (line 48) | def isValidBST(self, root):
FILE: lintcode/96_partition_list.py
class Solution (line 11) | class Solution:
method partition (line 17) | def partition(self, head, x):
FILE: lintcode/97_maximum_depth_of_binary_tree.py
class Solution (line 10) | class Solution:
method maxDepth (line 15) | def maxDepth(self, root):
FILE: lintcode/98_sort_list.py
class Solution (line 11) | class Solution:
method sortList (line 16) | def sortList(self, head):
method quick_sort (line 19) | def quick_sort(self, head):
method merge_sort (line 53) | def merge_sort(self, head):
method find_middle (line 83) | def find_middle(self, head):
method get_tail (line 92) | def get_tail(self, head):
FILE: lintcode/9_fizz_buzz.py
class Solution (line 1) | class Solution:
method fizzBuzz (line 2) | def fizzBuzz(self, n):
method fizzBuzz (line 26) | def fizzBuzz(self, n):
class Solution (line 25) | class Solution:
method fizzBuzz (line 2) | def fizzBuzz(self, n):
method fizzBuzz (line 26) | def fizzBuzz(self, n):
FILE: other/anti_queue_reconstruction_by_height.py
function reorder (line 6) | def reorder(nums):
FILE: other/binary_tree_maximum_path_product.py
class Solution (line 66) | class Solution:
method maxPathProd (line 67) | def maxPathProd(self, root):
method divide_conquer (line 78) | def divide_conquer(self, node):
FILE: other/candy_crush.py
function _check_board_valid (line 50) | def _check_board_valid(board):
class CandyCrush (line 67) | class CandyCrush:
method __init__ (line 68) | def __init__(self, m, n, q):
method reset_board (line 85) | def reset_board(self):
method get_board (line 121) | def get_board(self):
method _check_cell_valid (line 127) | def _check_cell_valid(self, x, y):
method _print_board (line 155) | def _print_board(self):
FILE: other/card_shuffler.py
function card_shuffler (line 13) | def card_shuffler(cards, shuffles):
function get_offset (line 30) | def get_offset(start, shuffles):
function get_lcm (line 43) | def get_lcm(*nums):
function get_gcd (line 52) | def get_gcd(a, b):
FILE: other/deep_fetch.js
function deepFetch (line 1) | function deepFetch(target, path, defaultValue = undefined) {
FILE: other/find_treasure_in_maze.py
class Solution (line 40) | class Solution:
method find_treasure_in_maze (line 48) | def find_treasure_in_maze(self, maze):
method bfs (line 85) | def bfs(self, maze, queue, keys, holds, doors, visited):
method is_possible (line 131) | def is_possible(self, maze, keys, holds, doors):
FILE: other/find_ways_in_board_game.py
function find_ways_in_board_game (line 18) | def find_ways_in_board_game(n):
FILE: other/freq_iterator.py
class FreqIterator (line 45) | class FreqIterator:
method __init__ (line 46) | def __init__(self, iterator):
method next (line 54) | def next(self):
method has_next (line 71) | def has_next(self):
class ListIterator (line 75) | class ListIterator:
method __init__ (line 76) | def __init__(self, words):
method next (line 80) | def next(self):
method has_next (line 88) | def has_next(self):
FILE: other/gcd_and_lcm.py
function get_gcd (line 1) | def get_gcd(a, b):
function get_lcm (line 17) | def get_lcm(a, b):
FILE: other/get_most_popular_word.py
class Solution (line 67) | class Solution:
method __init__ (line 68) | def __init__(self, W):
method insert (line 81) | def insert(self, word):
method get_most_popular_word (line 94) | def get_most_popular_word(self):
method _add_word (line 97) | def _add_word(self, word):
method _evict_word (line 125) | def _evict_word(self):
class WordNode (line 155) | class WordNode:
method __init__ (line 156) | def __init__(self, word, freq_node=None, pre=None, nxt=None):
method link (line 162) | def link(self, pre, nxt):
method unlink (line 168) | def unlink(self):
class FreqNode (line 174) | class FreqNode:
method __init__ (line 175) | def __init__(self, freq, pre=None, nxt=None):
method unlink (line 183) | def unlink(self):
method before (line 188) | def before(self, freq_node):
method after (line 194) | def after(self, freq_node):
method is_empty (line 200) | def is_empty(self):
method append_tail (line 203) | def append_tail(self, word_node):
FILE: other/guess_secret.py
function find_secret (line 19) | def find_secret(secret, words):
class Secret (line 50) | class Secret:
method __init__ (line 51) | def __init__(self, word):
method guess (line 55) | def guess(self, word):
FILE: other/inorder_non_threaded_binary_tree_traversal.py
function inorder_traverse (line 108) | def inorder_traverse(root, *, callback):
FILE: other/is_valid_relation.py
function is_valid_relation (line 37) | def is_valid_relation(strs):
function dfs (line 79) | def dfs(graph, node, visited):
FILE: other/merge_mail.py
function merge_mail (line 1) | def merge_mail(data):
function connect (line 41) | def connect(nodes, a, b):
function find (line 48) | def find(nodes, a):
FILE: other/reservation.py
class Reservation (line 17) | class Reservation:
method __init__ (line 18) | def __init__(self, m, n):
method get_seats (line 21) | def get_seats(self, user_id, n=0):
FILE: other/robot_cleaner.py
class Dirs (line 159) | class Dirs:
class Room (line 178) | class Room:
method __init__ (line 184) | def __init__(self, grid):
method is_clear (line 202) | def is_clear(self):
method move_robot (line 208) | def move_robot(self, direction):
method clean (line 227) | def clean(self, robot):
method _get_robot (line 241) | def _get_robot(self):
method _print_room (line 245) | def _print_room(self):
class Robot (line 255) | class Robot:
method __init__ (line 256) | def __init__(self, room):
method move (line 263) | def move(self, direction=None):
method turnleft (line 273) | def turnleft(self, k=1):
method turnrigt (line 281) | def turnrigt(self, k=1):
method clean (line 290) | def clean(self):
method _get_face (line 296) | def _get_face(self):
class RobotCleanerDFS (line 301) | class RobotCleanerDFS:
method clean_room (line 306) | def clean_room(self, robot):
method dfs (line 323) | def dfs(self, x, y, to_dir, robot, visited):
class RobotCleanerDFS2 (line 372) | class RobotCleanerDFS2:
method clean_room (line 376) | def clean_room(self, robot):
method dfs (line 390) | def dfs(self, x, y, from_dir, robot, visited):
class RobotCleanerBFS (line 415) | class RobotCleanerBFS:
method clean_room (line 416) | def clean_room(self, robot):
method bfs (line 423) | def bfs(self):
FILE: other/snake_and_ladder_problem.py
function get_min_dice_throws (line 6) | def get_min_dice_throws(moves):
FILE: other/stock_stream.py
class StockStream (line 1) | class StockStream:
method __init__ (line 2) | def __init__(self, prices):
method update (line 5) | def update(self, timestamp, price):
method get_highest (line 13) | def get_highest(self):
method get_lowest (line 19) | def get_lowest(self):
method get_latest (line 25) | def get_latest(self):
FILE: other/string_abbreviation.py
function encode (line 31) | def encode(s):
function decode (line 69) | def decode(s):
FILE: other/the_point_inside_polygon.py
function get_random_point_inside_rectangle (line 19) | def get_random_point_inside_rectangle(rectangle):
function get_random_point_inside_rectangle2 (line 37) | def get_random_point_inside_rectangle2(rectangles):
function get_random_point_inside_rectangle3 (line 61) | def get_random_point_inside_rectangle3(rectangles):
function is_point_inside_polygon (line 72) | def is_point_inside_polygon(polygon, point):
FILE: other/uneven_random_get.py
function uneven_random_get (line 8) | def uneven_random_get(options, rate):
function uneven_random_get2 (line 29) | def uneven_random_get2(options, rate):
FILE: other/unique_paths_with_followups.py
function find_unique_paths (line 16) | def find_unique_paths(m, n):
function find_unique_paths1 (line 51) | def find_unique_paths1(m, n):
function find_unique_paths2 (line 89) | def find_unique_paths2(m, n, points):
function find_unique_paths3 (line 131) | def find_unique_paths3(m, n, points):
function find_unique_paths4 (line 192) | def find_unique_paths4(m, n, h):
function find_unique_paths5 (line 247) | def find_unique_paths5(m, n):
FILE: other/unique_word_abbreviation_ii.py
function find_unique_abbreviations (line 47) | def find_unique_abbreviations(words):
class WordIterator (line 87) | class WordIterator:
method __init__ (line 88) | def __init__(self, word):
method __iter__ (line 92) | def __iter__(self):
FILE: other/upside_down_numbers.py
function find_upside_down_numbers (line 1) | def find_upside_down_numbers(n):
function get_reversed_number (line 56) | def get_reversed_number(s, up_down_nums):
FILE: pramp/array_index_and_element_equality.py
function index_equals_value_search (line 1) | def index_equals_value_search(nums):
FILE: pramp/array_of_array_products.py
function array_of_array_products (line 14) | def array_of_array_products(nums):
FILE: pramp/award_budget_cuts.py
function find_grants_cap (line 37) | def find_grants_cap(grantsArray, newBudget):
FILE: pramp/bracket_match.py
function bracket_match (line 1) | def bracket_match(text):
FILE: pramp/busiest_time_in_the_mall.py
function find_busiest_period (line 1) | def find_busiest_period(data):
FILE: pramp/decrypt_message.py
function encrypt (line 41) | def encrypt(word):
function decrypt (line 56) | def decrypt(word):
function decrypt2 (line 72) | def decrypt2(word):
FILE: pramp/deletion_distance.py
function deletion_distance (line 17) | def deletion_distance(s, t):
function deletion_distance2 (line 48) | def deletion_distance2(s, t):
FILE: pramp/drone_flight_planner.py
function calc_drone_min_energy (line 1) | def calc_drone_min_energy(route):
FILE: pramp/find_the_duplicates.py
function find_duplicates (line 1) | def find_duplicates(arr1, arr2):
function find_duplicates2 (line 24) | def find_duplicates2(arr1, arr2):
function find_duplicates3 (line 43) | def find_duplicates3(arr1, arr2):
FILE: pramp/flatten_a_dictionary.py
function flatten_dictionary (line 1) | def flatten_dictionary(dictionary):
function dfs (line 11) | def dfs(dictionary, keys, ans):
FILE: pramp/h_tree_construction.py
function draw_line (line 1) | def draw_line(x1, y1, x2, y2):
function draw_h_tree (line 5) | def draw_h_tree(x, y, length, depth):
function draw_h_tree2 (line 35) | def draw_h_tree2(x, y, length, depth):
FILE: pramp/k_messed_array_sort.py
function sort_k_messed_array (line 4) | def sort_k_messed_array(nums, k):
FILE: pramp/largest_smaller_bst_node.py
function largest_smaller_bst_node (line 1) | def largest_smaller_bst_node(root, target):
FILE: pramp/number_of_paths.py
function num_of_paths_to_dest (line 1) | def num_of_paths_to_dest(n):
FILE: pramp/pairs_with_specific_difference.py
function find_pairs_with_given_difference (line 1) | def find_pairs_with_given_difference(arr, k):
FILE: pramp/pancake_sort.py
function pancake_sort (line 42) | def pancake_sort(nums):
function flip (line 55) | def flip(nums, k):
function get_max_index (line 76) | def get_max_index(nums, i):
FILE: pramp/root_of_number.py
function root (line 18) | def root(x, n):
function get_product (line 39) | def get_product(x, n):
FILE: pramp/sales_path.py
function get_cheapest_cost (line 69) | def get_cheapest_cost(root):
function get_cheapest_cost_paths (line 86) | def get_cheapest_cost_paths(root):
function _dfs (line 98) | def _dfs(root, target, ans, path):
FILE: pramp/sentence_reverse.py
function reverse_words (line 37) | def reverse_words(arr):
function reverse_words2 (line 44) | def reverse_words2(arr):
function reverse_in_range (line 73) | def reverse_in_range(arr, i, j):
FILE: pramp/smallest_substring_of_all_characters.py
function get_shortest_unique_substring (line 1) | def get_shortest_unique_substring(strs, s):
FILE: pramp/time_planner.py
function meeting_planner (line 1) | def meeting_planner(slots1, slots2, duration):
FILE: pramp/word_count_engine.py
function word_count_engine (line 25) | def word_count_engine(document):
function word_count_engine2 (line 57) | def word_count_engine2(document):
FILE: topic/_test/python/test_base.py
class TaskTimer (line 5) | class TaskTimer:
method __init__ (line 6) | def __init__(self):
method reset_time (line 9) | def reset_time(self):
method print_duration (line 12) | def print_duration(self):
class TestBase (line 17) | class TestBase(unittest.TestCase):
method setUpClass (line 21) | def setUpClass(cls):
method tearDownClass (line 28) | def tearDownClass(cls):
method setUp (line 34) | def setUp(self):
method tearDown (line 37) | def tearDown(self):
FILE: topic/bit_manipulation/python/calculator_in_bit.py
class Calculator (line 59) | class Calculator:
method _plus (line 63) | def _plus(cls, a, b):
method plus (line 73) | def plus(cls, a, b):
method minus (line 84) | def minus(cls, a, b):
method times (line 88) | def times(cls, a, b):
method divide (line 110) | def divide(cls, a, b):
FILE: topic/bit_manipulation/python/calculator_in_bit__test.py
class TestBitCalculator (line 5) | class TestBitCalculator(TestBase):
method test_plus_recursion (line 31) | def test_plus_recursion(self):
method test_plus_iteration (line 35) | def test_plus_iteration(self):
method test_minus (line 39) | def test_minus(self):
method test_times (line 43) | def test_times(self):
method test_divide (line 47) | def test_divide(self):
FILE: topic/graph/python/union_find.py
class UnionFind (line 1) | class UnionFind:
method __init__ (line 2) | def __init__(self):
method union (line 5) | def union(self, u, v):
method find (line 14) | def find(self, u):
FILE: topic/graph/python/union_find__test.py
class TestUnionFind (line 5) | class TestUnionFind(TestBase):
method test_init (line 6) | def test_init(self):
method test_union (line 11) | def test_union(self):
method test_compression (line 21) | def test_compression(self):
FILE: topic/hash/python/geohash.py
class GeoHash (line 19) | class GeoHash:
method __init__ (line 20) | def __init__(self):
method encode (line 33) | def encode(self, latitude, longitude, precision=5):
method decode (line 50) | def decode(self, geohash):
method _bin_to_pos (line 67) | def _bin_to_pos(self, bincode, start, end):
method _pos_to_bin (line 78) | def _pos_to_bin(self, position, digits, start, end):
FILE: topic/hash/python/geohash__test.py
class TestGeoHash (line 5) | class TestGeoHash(TestBase):
method test_encode (line 23) | def test_encode(self):
method test_decode (line 29) | def test_decode(self):
FILE: topic/hash/python/hashtable.py
class HashTable (line 1) | class HashTable:
method __init__ (line 2) | def __init__(self, cap=4000, power=31):
method __repr__ (line 8) | def __repr__(self):
method __len__ (line 16) | def __len__(self):
method __setitem__ (line 19) | def __setitem__(self, key, val):
method __getitem__ (line 22) | def __getitem__(self, key):
method __delitem__ (line 25) | def __delitem__(self, key):
method __iter__ (line 28) | def __iter__(self):
method keys (line 32) | def keys(self):
method values (line 36) | def values(self):
method items (line 40) | def items(self):
method set (line 48) | def set(self, key, val):
method get (line 67) | def get(self, key):
method remove (line 83) | def remove(self, key):
method _encode (line 106) | def _encode(self, key):
class ListNode (line 118) | class ListNode:
method __init__ (line 119) | def __init__(self, key, val, nxt=None):
FILE: topic/hash/python/hashtable__test.py
class TestHashTable (line 5) | class TestHashTable(TestBase):
method test_operation (line 6) | def test_operation(self):
method test_collision (line 33) | def test_collision(self):
FILE: topic/heap/python/binary_hash_heap.py
class BinaryHashHeap (line 4) | class BinaryHashHeap:
method __init__ (line 7) | def __init__(self, iterable=None):
method __len__ (line 15) | def __len__(self):
method __bool__ (line 18) | def __bool__(self):
method heapify (line 21) | def heapify(self, iterable):
method push (line 28) | def push(self, val):
method pop (line 35) | def pop(self):
method remove (line 54) | def remove(self, val):
method top (line 71) | def top(self):
method _siftdown (line 77) | def _siftdown(self, i):
method _siftup (line 88) | def _siftup(self, i):
method _swap (line 103) | def _swap(self, i, j):
FILE: topic/heap/python/binary_heap.py
class BinaryHeap (line 4) | class BinaryHeap:
method __init__ (line 7) | def __init__(self, iterable=None):
method __len__ (line 14) | def __len__(self):
method __bool__ (line 17) | def __bool__(self):
method heapify (line 20) | def heapify(self, iterable):
method push (line 27) | def push(self, val):
method pop (line 33) | def pop(self):
method top (line 47) | def top(self):
method _siftdown (line 53) | def _siftdown(self, i):
method _siftup (line 64) | def _siftup(self, i):
FILE: topic/heap/python/heap__test.py
class TestHeap (line 5) | class TestHeap(TestBase):
method _test_heapify (line 6) | def _test_heapify(self, Heap):
method _test_push (line 22) | def _test_push(self, Heap):
method _test_pop (line 42) | def _test_pop(self, Heap):
method _test_remove (line 58) | def _test_remove(self, Heap):
method _test_top (line 106) | def _test_top(self, Heap):
method _run_heap_test (line 121) | def _run_heap_test(self, Heap):
method _run_removable_heap_test (line 127) | def _run_removable_heap_test(self, Heap):
method test_binary_hash_heap (line 134) | def test_binary_hash_heap(self):
method test_binary_heap (line 137) | def test_binary_heap(self):
method test_lazy_removable_heapq (line 140) | def test_lazy_removable_heapq(self):
method test_removable_heapq (line 143) | def test_removable_heapq(self):
FILE: topic/heap/python/lazy_removable_heapq.py
class LazyRemovableHeapq (line 5) | class LazyRemovableHeapq:
method __init__ (line 8) | def __init__(self, iterable=None):
method __len__ (line 16) | def __len__(self):
method __bool__ (line 19) | def __bool__(self):
method heapify (line 22) | def heapify(self, iterable):
method push (line 29) | def push(self, val):
method pop (line 34) | def pop(self):
method remove (line 43) | def remove(self, val):
method top (line 50) | def top(self):
method _is_empty (line 56) | def _is_empty(self):
FILE: topic/heap/python/removable_heapq.py
class RemovableHeapq (line 11) | class RemovableHeapq:
method __init__ (line 14) | def __init__(self, iterable=None):
method __len__ (line 20) | def __len__(self):
method __bool__ (line 23) | def __bool__(self):
method heapify (line 26) | def heapify(self, iterable):
method push (line 33) | def push(self, val):
method pop (line 36) | def pop(self):
method remove (line 42) | def remove(self, val):
method top (line 62) | def top(self):
FILE: topic/linked_list/python/_helper.py
class ListNode (line 9) | class ListNode:
method __init__ (line 10) | def __init__(self, val, nxt=None):
class DoublyListNode (line 15) | class DoublyListNode:
method __init__ (line 16) | def __init__(self, val, pre=None, nxt=None):
class ListBase (line 22) | class ListBase(ABC):
method __repr__ (line 23) | def __repr__(self):
method __str__ (line 26) | def __str__(self):
method __bool__ (line 29) | def __bool__(self):
method __len__ (line 32) | def __len__(self):
method to_list (line 36) | def to_list(self):
method contains (line 42) | def contains(self, obj):
method get_first (line 53) | def get_first(self):
method get_last (line 59) | def get_last(self):
method add_first (line 65) | def add_first(self, obj):
method add_last (line 72) | def add_last(self, obj):
method remove_first (line 79) | def remove_first(self):
method remove_last (line 85) | def remove_last(self):
method _check_index (line 91) | def _check_index(self, index, raise_error=False):
method __iter__ (line 117) | def __iter__(self):
method set (line 121) | def set(self, obj, index=-1):
method get (line 130) | def get(self, index=-1):
method add (line 138) | def add(self, obj, index=-1):
method add_all (line 147) | def add_all(self, objs, index=-1):
method remove (line 157) | def remove(self, index=-1):
method index (line 165) | def index(self, obj):
method last_index (line 175) | def last_index(self, obj):
method clear (line 185) | def clear(self):
method clone (line 192) | def clone(self):
method sort (line 199) | def sort(self, key=None):
method _get_size (line 207) | def _get_size(self):
method _get_node (line 214) | def _get_node(self, index=-1):
FILE: topic/linked_list/python/cyclic_doubly_list.py
class CyclicDoublyList (line 7) | class CyclicDoublyList(ListBase):
method __init__ (line 8) | def __init__(self):
method __iter__ (line 11) | def __iter__(self):
method set (line 19) | def set(self, obj, index=-1):
method get (line 30) | def get(self, index=-1):
method add (line 38) | def add(self, obj, index=-1):
method add_all (line 59) | def add_all(self, objs, index=-1):
method remove (line 89) | def remove(self, index=-1):
method index (line 102) | def index(self, obj):
method last_index (line 120) | def last_index(self, obj):
method clear (line 138) | def clear(self):
method clone (line 147) | def clone(self):
method sort (line 153) | def sort(self, key=None):
method _get_size (line 160) | def _get_size(self):
method _get_node (line 166) | def _get_node(self, index=-1):
method _new_node (line 186) | def _new_node(self, obj, pre=None, nxt=None):
FILE: topic/linked_list/python/cyclic_list.py
class CyclicList (line 9) | class CyclicList(ListBase):
method __init__ (line 10) | def __init__(self):
method __iter__ (line 13) | def __iter__(self):
method set (line 21) | def set(self, obj, index=-1):
method get (line 32) | def get(self, index=-1):
method add (line 40) | def add(self, obj, index=-1):
method add_all (line 61) | def add_all(self, objs, index=-1):
method remove (line 89) | def remove(self, index=-1):
method index (line 102) | def index(self, obj):
method last_index (line 120) | def last_index(self, obj):
method clear (line 143) | def clear(self):
method clone (line 152) | def clone(self):
method sort (line 158) | def sort(self, key=None):
method _get_size (line 165) | def _get_size(self):
method _get_node (line 171) | def _get_node(self, index=-1):
method _get_prev_node (line 193) | def _get_prev_node(self, index=-1):
method _new_node (line 217) | def _new_node(self, obj, nxt=None):
FILE: topic/linked_list/python/dummy_tail_doubly_list.py
class DummyTailDoublyList (line 8) | class DummyTailDoublyList(ListBase):
FILE: topic/linked_list/python/dummy_tail_list.py
class DummyTailList (line 8) | class DummyTailList(ListBase):
FILE: topic/linked_list/python/head_tail_doubly_list.py
class HeadTailDoublyList (line 8) | class HeadTailDoublyList(ListBase):
FILE: topic/linked_list/python/head_tail_list.py
class HeadTailList (line 8) | class HeadTailList(ListBase):
FILE: topic/linked_list/python/linked_list__test.py
class TestLinkedList (line 5) | class TestLinkedList(TestBase):
method _get_instance (line 6) | def _get_instance(self, LinkedList):
method _test_set (line 19) | def _test_set(self, LinkedList):
method _test_get (line 39) | def _test_get(self, LinkedList):
method _test_add (line 58) | def _test_add(self, LinkedList):
method _test_add_all (line 82) | def _test_add_all(self, LinkedList):
method _test_remove (line 111) | def _test_remove(self, LinkedList):
method _test_contains (line 134) | def _test_contains(self, LinkedList):
method _test_index (line 146) | def _test_index(self, LinkedList):
method _test_last_index (line 152) | def _test_last_index(self, LinkedList):
method _test_clear (line 158) | def _test_clear(self, LinkedList):
method _test_clone (line 167) | def _test_clone(self, LinkedList):
method _test_sort (line 170) | def _test_sort(self, LinkedList):
method _run_list_test (line 173) | def _run_list_test(self, LinkedList):
method test_cyclic_list (line 186) | def test_cyclic_list(self):
method test_cyclic_doubly_list (line 189) | def test_cyclic_doubly_list(self):
FILE: topic/linked_list/python/two_dummy_doubly_list.py
class TwoDummyDoublyList (line 7) | class TwoDummyDoublyList(ListBase):
FILE: topic/linked_list/python/two_dummy_list.py
class TwoDummyList (line 7) | class TwoDummyList(ListBase):
FILE: topic/searching/python/_helper.py
class SearchBase (line 4) | class SearchBase(ABC):
method search (line 7) | def search(cls, iterable, val):
FILE: topic/sorting/python/_helper.py
class SortBase (line 5) | class SortBase(ABC):
method sort (line 8) | def sort(cls, iterable):
method _is_valid_payload (line 16) | def _is_valid_payload(iterable):
FILE: topic/sorting/python/merge_sort.py
class MergeSort (line 4) | class MergeSort(SortBase):
method sort (line 6) | def sort(cls, iterable):
method _divide_conquer (line 20) | def _divide_conquer(cls, arr, start, end, tmp):
FILE: topic/sorting/python/quick_sort.py
class QuickSort (line 4) | class QuickSort(SortBase):
method sort (line 11) | def sort(cls, iterable):
method _divide_conquer (line 25) | def _divide_conquer(cls, arr, start, end):
FILE: topic/sorting/python/sorting__test.py
class TestSorting (line 5) | class TestSorting(TestBase):
method _run_sorting_test (line 18) | def _run_sorting_test(self, Sort):
method test_quick_sort (line 27) | def test_quick_sort(self):
method test_merge_sort (line 30) | def test_merge_sort(self):
FILE: topic/traversal/python/_helper.py
class TraversalBase (line 4) | class TraversalBase(ABC):
method preorder_traverse (line 7) | def preorder_traverse(cls, root, callback=None):
method inorder_traverse (line 17) | def inorder_traverse(cls, root, callback=None):
method postorder_traverse (line 27) | def postorder_traverse(cls, root, callback=None):
FILE: topic/traversal/python/binary_tree_traversal__test.py
class TestBinaryTreeTraversal (line 6) | class TestBinaryTreeTraversal(TestBase):
method setUp (line 22) | def setUp(self):
method _run_traversal_test (line 30) | def _run_traversal_test(self, Traversal):
method test_recursive_traversal (line 46) | def test_recursive_traversal(self):
method test_iterative_traversal (line 49) | def test_iterative_traversal(self):
method test_morris_traversal (line 52) | def test_morris_traversal(self):
FILE: topic/traversal/python/iterative_traversal.py
class IterativeTraversal (line 4) | class IterativeTraversal(TraversalBase):
method preorder_traverse (line 6) | def preorder_traverse(cls, root, callback=None):
method inorder_traverse (line 25) | def inorder_traverse(cls, root, callback=None):
method postorder_traverse (line 44) | def postorder_traverse(cls, root, callback=None):
FILE: topic/traversal/python/morris_traversal.py
class MorrisTraversal (line 5) | class MorrisTraversal(TraversalBase):
method preorder_traverse (line 11) | def preorder_traverse(cls, root, callback=None):
method inorder_traverse (line 39) | def inorder_traverse(cls, root, callback=None):
method postorder_traverse (line 67) | def postorder_traverse(cls, root, callback=None):
method _postorder_reverse_visit (line 98) | def _postorder_reverse_visit(cls, from_node, to_node, callback):
method _postorder_reverse (line 111) | def _postorder_reverse(cls, from_node, to_node):
FILE: topic/traversal/python/recursive_traversal.py
class RecursiveTraversal (line 4) | class RecursiveTraversal(TraversalBase):
method preorder_traverse (line 6) | def preorder_traverse(cls, root, callback=None):
method inorder_traverse (line 20) | def inorder_traverse(cls, root, callback=None):
method postorder_traverse (line 34) | def postorder_traverse(cls, root, callback=None):
FILE: topic/tree/python/binary_tree.py
class TreeNode (line 1) | class TreeNode:
method __init__ (line 2) | def __init__(self, val):
class BinaryTree (line 7) | class BinaryTree:
method serialize (line 12) | def serialize(cls, root):
method deserialize (line 38) | def deserialize(cls, data):
FILE: topic/tree/python/binary_tree__test.py
class TestBinaryTree (line 5) | class TestBinaryTree(TestBase):
method test_serialization (line 6) | def test_serialization(self):
FILE: topic/tree/python/trie.py
class TrieNode (line 4) | class TrieNode:
method __init__ (line 5) | def __init__(self):
class Trie (line 10) | class Trie:
method __init__ (line 11) | def __init__(self):
method __repr__ (line 14) | def __repr__(self):
method put (line 17) | def put(self, word):
method has_word (line 28) | def has_word(self, word):
method has_prefix (line 34) | def has_prefix(self, word):
method get_node (line 40) | def get_node(self, char, node=None):
method _search (line 47) | def _search(self, word):
method _is_str (line 61) | def _is_str(self, word):
FILE: topic/tree/python/trie__test.py
class TestTrie (line 5) | class TestTrie(TestBase):
method test_init (line 6) | def test_init(self):
method test_put (line 16) | def test_put(self):
method test_has_word_or_prefix (line 35) | def test_has_word_or_prefix(self):
method test_invalid_put (line 73) | def test_invalid_put(self):
Condensed preview — 638 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (863K chars).
[
{
"path": ".editorconfig",
"chars": 205,
"preview": "root = true\n\n[*]\nend_of_line = lf\ninsert_final_newline = true\ncharset = utf-8\nindent_size = 2\nindent_style = space\n\n[*.p"
},
{
"path": ".gitignore",
"chars": 37,
"preview": "__pycache__\nnode_modules\n*-lock.json\n"
},
{
"path": ".travis.yml",
"chars": 305,
"preview": "matrix:\n include:\n - language: python\n python: \"3.6\"\n script:\n - $TRAVIS_BUILD_DIR/bin/test_python."
},
{
"path": "README.md",
"chars": 1832,
"preview": "Algorithm\n======\n\n[](https://travis-ci.org/jay"
},
{
"path": "bin/test_javascript.js",
"chars": 282,
"preview": "// TODO: wrap this file to a executable command\n// [Configuring Jest](https://facebook.github.io/jest/docs/en/configurat"
},
{
"path": "bin/test_python.py",
"chars": 1741,
"preview": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport os\nimport sys\nimport unittest\nimport doctest\n\nsys.path.append(os"
},
{
"path": "codewars/delete_occurrences_of_an_element_if_it_occurs_more_than_n_times.js",
"chars": 386,
"preview": "function deleteNth(nums, n) {\n const freq = {}\n\n for (let i = 0; i < nums.length; i++) {\n const num = nums[i]\n\n "
},
{
"path": "codewars/double_cola.js",
"chars": 175,
"preview": "function whoIsNext(names, r) {\n let total = names.length\n\n while (r > total) {\n r -= total\n total *= 2\n }\n\n re"
},
{
"path": "codewars/iq_test.js",
"chars": 347,
"preview": "function iqTest(nums) {\n nums = nums.split(' ').map(c => +c & 1)\n\n for (let i = 2; i < nums.length; i++) {\n if (num"
},
{
"path": "codewars/is_a_number_prime.js",
"chars": 256,
"preview": "function isPrime(num) {\n if (!num || num <= 1) return false\n\n const factors = [2, 3, 5, 7, 9, 11, 13, 17, 19].filter(b"
},
{
"path": "codewars/multiply.js",
"chars": 43,
"preview": "function multiply(a, b) {\n return a * b\n}\n"
},
{
"path": "codewars/rectangle_into_squares.js",
"chars": 384,
"preview": "function sqInRect(lng, wdth) {\n if (!lng || !wdth || lng === wdth) return null\n\n const ans = []\n\n while (lng != 1 || "
},
{
"path": "codewars/reverse_words.js",
"chars": 125,
"preview": "function reverseWords(s) {\n return s.split(' ').map(word => {\n return word.split('').reverse().join('')\n }).join(' "
},
{
"path": "codewars/simple_encryption_1_alternating_split.js",
"chars": 806,
"preview": "function encrypt(text, n) {\n if (!text || !n || n < 0) return text\n\n const TEXT_SIZE = text.length\n\n while (n--) {\n "
},
{
"path": "codewars/sudoku_solution_validator.js",
"chars": 1137,
"preview": "function validSolution(board) {\n if ( !Array.isArray(board)\n || !Array.isArray(board[0])\n || board.length !== boa"
},
{
"path": "codewars/take_a_ten_minute_walk.js",
"chars": 396,
"preview": "function isValidWalk(walk) {\n if (walk.length != 10) {\n return false\n }\n\n let dx = 0\n let dy = 0\n\n walk.forEach("
},
{
"path": "codewars/tribonacci_sequence.js",
"chars": 205,
"preview": "function tribonacci(signature, n) {\n if (!n) return []\n\n const ans = signature.slice()\n\n for (let i = 3; i < n; i++) "
},
{
"path": "codewars/unique_in_order.js",
"chars": 248,
"preview": "function uniqueInOrder(iterable) {\n if (!iterable) {\n return []\n }\n\n const ans = [iterable[0]]\n\n for (let i = 1; "
},
{
"path": "codewars/who_likes_it.js",
"chars": 432,
"preview": "function likes(names) {\n if (!Array.isArray(names) || names.length === 0) {\n return 'no one likes this'\n }\n\n switc"
},
{
"path": "leetcode/101_symmetric_tree.py",
"chars": 798,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/105_construct_binary_tree_from_preorder_and_inorder_traversal.py",
"chars": 552,
"preview": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# "
},
{
"path": "leetcode/108_convert_sorted_array_to_binary_search_tree.py",
"chars": 528,
"preview": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# sel"
},
{
"path": "leetcode/112_path_sum.py",
"chars": 664,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/113_path_sum_ii.py",
"chars": 835,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/116_populating_next_right_pointers_in_each_node.py",
"chars": 1299,
"preview": "\"\"\"\nDefinition for binary tree with next pointer.\nclass TreeLinkNode:\n def __init__(self, x):\n self.val = x\n "
},
{
"path": "leetcode/117_populating_next_right_pointers_in_each_node_ii.py",
"chars": 2225,
"preview": "\"\"\"\nDefinition for binary tree with next pointer.\nclass TreeLinkNode:\n def __init__(self, x):\n self.val = x\n "
},
{
"path": "leetcode/118_pascal_s_triangle.py",
"chars": 937,
"preview": "class Solution:\n def generate(self, num_rows):\n \"\"\"\n :type num_rows: int\n :rtype: List[List[int]"
},
{
"path": "leetcode/11_container_with_most_water.py",
"chars": 475,
"preview": "class Solution:\n def maxArea(self, H):\n \"\"\"\n :type H: List[int]\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/124_binary_tree_maximum_path_sum.py",
"chars": 1374,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/134_gas_station.py",
"chars": 1557,
"preview": "class Solution:\n \"\"\"\n Main Concept:\n\n if the tank is enough, go to next, otherwise back to previous to get gas\n"
},
{
"path": "leetcode/136_single_number.py",
"chars": 207,
"preview": "class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n "
},
{
"path": "leetcode/149_max_points_on_a_line.py",
"chars": 1130,
"preview": "# Definition for a point.\n# class Point:\n# def __init__(self, a=0, b=0):\n# self.x = a\n# self.y = b\n\n"
},
{
"path": "leetcode/14_longest_common_prefix.py",
"chars": 368,
"preview": "class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n "
},
{
"path": "leetcode/150_evaluate_reverse_polish_notation.py",
"chars": 615,
"preview": "class Solution:\n def evalRPN(self, E):\n \"\"\"\n :type E: List[str]\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/157_read_n_characters_given_read4.py",
"chars": 1004,
"preview": "\"\"\"\nThe read4 API is already defined for you.\n@param buf, a list of characters\n@return an integer\n\ndef read4(buf):\n p"
},
{
"path": "leetcode/160_intersection_of_two_linked_lists.py",
"chars": 643,
"preview": "# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# "
},
{
"path": "leetcode/165_compare_version_numbers.py",
"chars": 881,
"preview": "class Solution:\n def compareVersion(self, version1, version2):\n \"\"\"\n :type version1: str\n :type "
},
{
"path": "leetcode/166_fraction_to_recurring_decimal.py",
"chars": 822,
"preview": "class Solution:\n def fractionToDecimal(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rt"
},
{
"path": "leetcode/169_majority_element.py",
"chars": 1047,
"preview": "class Solution:\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n "
},
{
"path": "leetcode/171_excel_sheet_column_number.py",
"chars": 310,
"preview": "class Solution:\n def titleToNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/172_factorial_trailing_zeroes.py",
"chars": 277,
"preview": "class Solution:\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/174_dungeon_game.py",
"chars": 547,
"preview": "class Solution:\n def calculateMinimumHP(self, G):\n \"\"\"\n :type G: List[List[int]]\n :rtype: int\n "
},
{
"path": "leetcode/179_largest_number.py",
"chars": 346,
"preview": "\"\"\"\nREF: https://leetcode.com/articles/largest-number/\n\"\"\"\n\n\nclass LgSort(str):\n def __lt__(a, b):\n return a +"
},
{
"path": "leetcode/17_letter_combinations_of_a_phone_number.py",
"chars": 694,
"preview": "class Solution:\n def letterCombinations(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n "
},
{
"path": "leetcode/190_reverse_bits.py",
"chars": 781,
"preview": "# Reverse bit every 4 bits\nclass Solution:\n # @param n, an integer\n # @return an integer\n def reverseBits(self,"
},
{
"path": "leetcode/191_number_of_1_bits.py",
"chars": 262,
"preview": "class Solution:\n def hammingWeight(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/19_remove_nth_node_from_end_of_list.py",
"chars": 674,
"preview": "\"\"\"\nDefinition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next"
},
{
"path": "leetcode/202_happy_number.py",
"chars": 544,
"preview": "class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n slow"
},
{
"path": "leetcode/204_count_primes.py",
"chars": 698,
"preview": "\"\"\"\nREF: https://discuss.leetcode.com/topic/14036/fast-python-solution\n\nCount the number of prime numbers LESS THAN a no"
},
{
"path": "leetcode/208_implement_trie_prefix_tree.py",
"chars": 1524,
"preview": "class TrieNode:\n def __init__(self, val=None):\n self.end_at = val\n self.children = {}\n\n\nclass Trie:\n "
},
{
"path": "leetcode/20_valid_parentheses.py",
"chars": 426,
"preview": "class Solution:\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n stac"
},
{
"path": "leetcode/215_kth_largest_element_in_an_array.py",
"chars": 341,
"preview": "from heapq import heappop, heappush\n\n\nclass Solution:\n def findKthLargest(self, A, k):\n \"\"\"\n :type A: L"
},
{
"path": "leetcode/217_contains_duplicate.py",
"chars": 301,
"preview": "class Solution:\n def containsDuplicate(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n "
},
{
"path": "leetcode/218_the_skyline_problem.py",
"chars": 1652,
"preview": "\"\"\"\nREF: https://briangordon.github.io/2014/08/the-skyline-problem.html\n\"\"\"\nimport heapq\n\n\nclass HashHeapq:\n def __in"
},
{
"path": "leetcode/224_basic_calculator.py",
"chars": 2795,
"preview": "class Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if "
},
{
"path": "leetcode/227_basic_calculator_ii.py",
"chars": 3202,
"preview": "class Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if "
},
{
"path": "leetcode/229_majority_element_ii.py",
"chars": 825,
"preview": "class Solution:\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]"
},
{
"path": "leetcode/22_generate_parentheses.py",
"chars": 628,
"preview": "class Solution:\n def generateParenthesis(self, n):\n \"\"\"\n :type n: int\n :rtype: list[str]\n "
},
{
"path": "leetcode/230_kth_smallest_element_in_a_bst.py",
"chars": 646,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/234_palindrome_linked_list.py",
"chars": 1124,
"preview": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# sel"
},
{
"path": "leetcode/235_lowest_common_ancestor_of_a_binary_search_tree.py",
"chars": 617,
"preview": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# "
},
{
"path": "leetcode/236_lowest_common_ancestor_of_a_binary_tree.py",
"chars": 700,
"preview": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# "
},
{
"path": "leetcode/237_delete_node_in_a_linked_list.py",
"chars": 454,
"preview": "# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# "
},
{
"path": "leetcode/242_valid_anagram.py",
"chars": 487,
"preview": "class Solution:\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: boo"
},
{
"path": "leetcode/269_alien_dictionary.py",
"chars": 1727,
"preview": "class Solution:\n def alienOrder(self, words):\n \"\"\"\n :type words: list[str]\n :rtype: str\n "
},
{
"path": "leetcode/277_find_the_celebrity.py",
"chars": 483,
"preview": "\"\"\"\nREF: https://discuss.leetcode.com/topic/25720/java-python-o-n-calls-o-1-space-easy-to-understand-solution\n\"\"\"\n\n\nclas"
},
{
"path": "leetcode/280_wiggle_sort.py",
"chars": 469,
"preview": "class Solution:\n def wiggleSort(self, nums):\n \"\"\"\n :type nums: list[int]\n :rtype: void, Do not r"
},
{
"path": "leetcode/282_expression_add_operators.py",
"chars": 1184,
"preview": "\"\"\"\nMain Concept:\n\nin product case, needs to remove product in last recursion, and adds the product in current.\n\"\"\"\n\n\ncl"
},
{
"path": "leetcode/285_inorder_successor_in_bst.py",
"chars": 5087,
"preview": "\"\"\"\nDefinition for a binary tree node.\n>>> class TreeNode:\n... def __init__(self, x):\n... self.val = x\n... "
},
{
"path": "leetcode/288_unique_word_abbreviation.py",
"chars": 1122,
"preview": "\"\"\"\nYour ValidWordAbbr object will be instantiated and called as such:\nvwa = ValidWordAbbr(dictionary)\nvwa.isUnique(\"wor"
},
{
"path": "leetcode/289_game_of_life.py",
"chars": 2876,
"preview": "\"\"\"\nREF: https://leetcode.com/problems/game-of-life/discuss/73223\n\nlives < 2 => 1 -> 0\nlives == 2 or 3 => 1 -> 1\nl"
},
{
"path": "leetcode/295_find_median_from_data_stream.py",
"chars": 1252,
"preview": "\"\"\"\nYour MedianFinder object will be instantiated and called as such:\nobj = MedianFinder()\nobj.addNum(num)\nparam_2 = obj"
},
{
"path": "leetcode/299_bulls_and_cows.py",
"chars": 1388,
"preview": "class Solution:\n def getHint(self, secret, guess):\n \"\"\"\n :type secret: str\n :type guess: str\n "
},
{
"path": "leetcode/303_range_sum_query_immutable.py",
"chars": 748,
"preview": "\"\"\"\nYour NumArray object will be instantiated and called as such:\nobj = NumArray(nums)\nparam_1 = obj.sumRange(i,j)\n\"\"\"\n\n"
},
{
"path": "leetcode/304_range_sum_query_2d_immutable.py",
"chars": 1422,
"preview": "\"\"\"\nYour NumMatrix object will be instantiated and called as such:\nobj = NumMatrix(matrix)\nparam_1 = obj.sumRegion(x1, y"
},
{
"path": "leetcode/307_range_sum_query_mutable.py",
"chars": 1378,
"preview": "\"\"\"\nREF: https://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was"
},
{
"path": "leetcode/308_range_sum_query_2d_mutable.py",
"chars": 1674,
"preview": "\"\"\"\nYour NumMatrix object will be instantiated and called as such:\nobj = NumMatrix(matrix)\nobj.update(x,y,val)\nparam_1 ="
},
{
"path": "leetcode/30_substring_with_concatenation_of_all_words.py",
"chars": 1251,
"preview": "class Solution:\n def findSubstring(self, s, S):\n \"\"\"\n :type s: str\n :type S: List[str]\n :"
},
{
"path": "leetcode/315_count_of_smaller_numbers_after_self.py",
"chars": 1309,
"preview": "class Solution:\n \"\"\"\n REF: https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76657/\n \"\""
},
{
"path": "leetcode/323_number_of_connected_components_in_an_undirected_graph.py",
"chars": 2007,
"preview": "\"\"\"\nTesting:\n>>> gotcha = []\n>>> for s in (Solution(), Solution2()):\n... for _in, _out in (\n... ((5, [[0, 1]"
},
{
"path": "leetcode/324_wiggle_sort_ii.py",
"chars": 469,
"preview": "\"\"\"\nFollow Up: https://discuss.leetcode.com/topic/32929/o-n-o-1-after-median-virtual-indexing\n\"\"\"\n\n\nclass Solution:\n "
},
{
"path": "leetcode/326_power_of_three.py",
"chars": 269,
"preview": "class Solution:\n def isPowerOfThree(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n "
},
{
"path": "leetcode/329_longest_increasing_path_in_a_matrix.py",
"chars": 1068,
"preview": "class Solution:\n def longestIncreasingPath(self, G):\n \"\"\"\n :type G: List[List[int]]\n :rtype: int"
},
{
"path": "leetcode/334_increasing_triplet_subsequence.py",
"chars": 378,
"preview": "class Solution:\n def increasingTriplet(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n "
},
{
"path": "leetcode/33_search_in_rotated_sorted_array.py",
"chars": 857,
"preview": "class Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n"
},
{
"path": "leetcode/340_longest_substring_with_at_most_k_distinct_characters.py",
"chars": 823,
"preview": "\"\"\"\n- count chars: minimum length: `while cnt == k` to reduce window size if possible\n- count chars: maximum length: `wh"
},
{
"path": "leetcode/344_reverse_string.py",
"chars": 149,
"preview": "class Solution:\n def reverseString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n "
},
{
"path": "leetcode/347_top_k_frequent_elements.py",
"chars": 449,
"preview": "class Solution:\n def topKFrequent(self, A, k):\n \"\"\"\n :type A: List[int]\n :type k: int\n :r"
},
{
"path": "leetcode/348_design_tic_tac_toe.py",
"chars": 1237,
"preview": "class TicTacToe(object):\n PLER_A = 1\n PLER_B = 2\n\n def __init__(self, n):\n \"\"\"\n Initialize your d"
},
{
"path": "leetcode/353_design_snake_game.py",
"chars": 3440,
"preview": "\"\"\"\n0. self.height is for `m`, self.width is for `n`\n1. note that, REMOVE FIRST,\n MUST remove the snake tail **BEFORE*"
},
{
"path": "leetcode/36_valid_sudoku.py",
"chars": 1345,
"preview": "class Solution:\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: boo"
},
{
"path": "leetcode/377_combination_sum_iv.py",
"chars": 2833,
"preview": "\"\"\"\n- item can only pick once (even diff item with same val): num loop -> amount loop, amount from end to start, + break"
},
{
"path": "leetcode/378_kth_smallest_element_in_a_sorted_matrix.py",
"chars": 566,
"preview": "from heapq import heappop, heappush\n\n\nclass Solution:\n def kthSmallest(self, G, k):\n \"\"\"\n :type G: List"
},
{
"path": "leetcode/37_sudoku_solver.py",
"chars": 1525,
"preview": "class Solution:\n def solveSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void "
},
{
"path": "leetcode/380_insert_delete_getrandom_o1.py",
"chars": 1195,
"preview": "\"\"\"\nYour RandomizedSet object will be instantiated and called as such:\nobj = RandomizedSet()\nparam = obj.insert(val)\npar"
},
{
"path": "leetcode/381_insert_delete_getrandom_o1_duplicates_allowed.py",
"chars": 1306,
"preview": "import random\n\n\nclass RandomizedCollection:\n def __init__(self):\n self.A = []\n self.I = {}\n\n def ins"
},
{
"path": "leetcode/382_linked_list_random_node.py",
"chars": 849,
"preview": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# sel"
},
{
"path": "leetcode/384_shuffle_an_array.py",
"chars": 808,
"preview": "from random import randrange\n\n\nclass Solution:\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n "
},
{
"path": "leetcode/386_lexicographical_numbers.py",
"chars": 525,
"preview": "class Solution:\n def lexicalOrder(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n "
},
{
"path": "leetcode/387_first_unique_character_in_a_string.py",
"chars": 343,
"preview": "class Solution:\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/388_longest_absolute_file_path.py",
"chars": 992,
"preview": "\"\"\"\nMain Concept:\n\nif meet file, record the maximum size of the abs path `root/dir/file`\nif meet dir, save current size "
},
{
"path": "leetcode/389_find_the_difference.py",
"chars": 829,
"preview": "class Solution:\n def findTheDifference(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rt"
},
{
"path": "leetcode/38_count_and_say.py",
"chars": 605,
"preview": "class Solution:\n def countAndSay(self, N):\n \"\"\"\n :type N: int\n :rtype: str\n \"\"\"\n q"
},
{
"path": "leetcode/390_elimination_game.py",
"chars": 404,
"preview": "class Solution:\n def lastRemaining(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/391_perfect_rectangle.py",
"chars": 1003,
"preview": "import collections\n\n\nclass Solution:\n def isRectangleCover(self, recs):\n \"\"\"\n :type recs: List[List[int"
},
{
"path": "leetcode/395_longest_substring_with_at_least_k_repeating_characters.py",
"chars": 1015,
"preview": "class Solution:\n def longestSubstring(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rty"
},
{
"path": "leetcode/398_random_pick_index.py",
"chars": 595,
"preview": "from random import randint\n\n\nclass Solution:\n def __init__(self, A):\n \"\"\"\n :type A: List[int]\n \""
},
{
"path": "leetcode/399_evaluate_division.py",
"chars": 1463,
"preview": "import collections\n\n\nclass Solution:\n def calcEquation(self, equations, values, queries):\n \"\"\"\n :type e"
},
{
"path": "leetcode/406_queue_reconstruction_by_height.py",
"chars": 1582,
"preview": "\"\"\"\nMain Concept:\n\n1. group the mans with same height and record origin index\n2. record all heights\n3. sort heights and "
},
{
"path": "leetcode/416_partition_equal_subset_sum.py",
"chars": 689,
"preview": "\"\"\"\nREF: https://leetcode.com/problems/partition-equal-subset-sum/discuss/90592\n\n\n`dp[s]` means the specific sum `s` can"
},
{
"path": "leetcode/417_pacific_atlantic_water_flow.py",
"chars": 2657,
"preview": "class Solution:\n \"\"\"\n BFS\n\n 1. for both p-side and a-side, init with queue and visit set\n 2. add the edge an"
},
{
"path": "leetcode/41_first_missing_positive.py",
"chars": 936,
"preview": "\"\"\"\nREF: http://www.cnblogs.com/yuzhangcmu/p/4200096.html\n\"\"\"\n\n\nclass Solution:\n def firstMissingPositive(self, A):\n "
},
{
"path": "leetcode/437_path_sum_iii.py",
"chars": 1593,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/454_4sum_ii.py",
"chars": 560,
"preview": "class Solution:\n def fourSumCount(self, A, B, C, D):\n \"\"\"\n :type A: List[int]\n :type B: List[int"
},
{
"path": "leetcode/461_hamming_distance.py",
"chars": 307,
"preview": "class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtyp"
},
{
"path": "leetcode/480_sliding_window_median.py",
"chars": 2393,
"preview": "import heapq\n\n\nclass HashHeapq:\n def __init__(self):\n self.__heap = []\n\n def __repr__(self):\n return"
},
{
"path": "leetcode/486_predict_the_winner.py",
"chars": 1018,
"preview": "\"\"\"\nDP:\ntime: O(n^2)\nspace: O(n)\n\"\"\"\nclass Solution:\n def PredictTheWinner(self, nums):\n \"\"\"\n :type num"
},
{
"path": "leetcode/48_rotate_image.py",
"chars": 1236,
"preview": "class Solution:\n def rotate(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do "
},
{
"path": "leetcode/490_the_maze.py",
"chars": 1430,
"preview": "class Solution:\n def hasPath(self, maze, start, destination):\n \"\"\"\n :type maze: List[List[int]]\n "
},
{
"path": "leetcode/494_target_sum.py",
"chars": 1083,
"preview": "\"\"\"\nREF: https://leetcode.com/problems/target-sum/discuss/97334\n\nP: children used in positive,\nN: children used in negat"
},
{
"path": "leetcode/499_the_maze_iii.py",
"chars": 3976,
"preview": "class Solution:\n \"\"\"\n BFS\n \"\"\"\n def findShortestWay(self, maze, ball, hole):\n \"\"\"\n :type maze:"
},
{
"path": "leetcode/505_the_maze_ii.py",
"chars": 3069,
"preview": "class Solution:\n \"\"\"\n BFS\n \"\"\"\n def shortestDistance(self, maze, start, destination):\n \"\"\"\n :t"
},
{
"path": "leetcode/518_coin_change_2.py",
"chars": 665,
"preview": "class Solution:\n def change(self, amount, coins):\n \"\"\"\n :type amount: int\n :type coins: List[int"
},
{
"path": "leetcode/51_n_queens.py",
"chars": 1331,
"preview": "class Solution:\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n "
},
{
"path": "leetcode/524_longest_word_in_dictionary_through_deleting.py",
"chars": 1814,
"preview": "class Solution:\n \"\"\"\n 1. to check the word in list is subsequence of given s\n 2. ignoring if the length less th"
},
{
"path": "leetcode/52_n_queens_ii.py",
"chars": 876,
"preview": "class Solution:\n def totalNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/530_minimum_absolute_difference_in_bst.py",
"chars": 676,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/542_01_matrix.py",
"chars": 954,
"preview": "class Solution:\n def updateMatrix(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: Li"
},
{
"path": "leetcode/54_spiral_matrix.py",
"chars": 872,
"preview": "class Solution:\n def spiralOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: Lis"
},
{
"path": "leetcode/592_fraction_addition_and_subtraction.py",
"chars": 930,
"preview": "import re\n\n\nclass Solution:\n def fractionAddition(self, E):\n \"\"\"\n :type E: str\n :rtype: str\n "
},
{
"path": "leetcode/593_valid_square.py",
"chars": 958,
"preview": "class Solution:\n def validSquare(self, p1, p2, p3, p4):\n \"\"\"\n :type p1: List[int]\n :type p2: Lis"
},
{
"path": "leetcode/59_spiral_matrix_ii.py",
"chars": 767,
"preview": "class Solution:\n def generateMatrix(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[int]]\n "
},
{
"path": "leetcode/5_longest_palindromic_substring.py",
"chars": 777,
"preview": "class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n "
},
{
"path": "leetcode/616_add_bold_tag_in_string.py",
"chars": 1439,
"preview": "\"\"\"\n>>> gotcha = []\n>>> for s in (Solution(),):\n... for _in, _out in (\n... (('', ['']), ''),\n... (('"
},
{
"path": "leetcode/643_maximum_average_subarray_i.py",
"chars": 1384,
"preview": "class Solution:\n def findMaxAverage(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n "
},
{
"path": "leetcode/66_plus_one.py",
"chars": 1001,
"preview": "class Solution:\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n "
},
{
"path": "leetcode/676_implement_magic_dictionary.py",
"chars": 1446,
"preview": "\"\"\"\nYour MagicDictionary object will be instantiated and called as such:\nobj = MagicDictionary()\nobj.buildDict(dict)\npar"
},
{
"path": "leetcode/679_24_game.py",
"chars": 1171,
"preview": "class Solution:\n EPS = 1e-6\n OP = (\n lambda a, b: a + b,\n lambda a, b: a * b,\n lambda a, b: a"
},
{
"path": "leetcode/681_next_closest_time.py",
"chars": 2012,
"preview": "\"\"\"\nit's very similar with `next permutation`\njust a `next combination`\n\n1. `digits` save unique num and in order\n2. `id"
},
{
"path": "leetcode/682_baseball_game.py",
"chars": 493,
"preview": "class Solution:\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/683_k_empty_slots.py",
"chars": 1795,
"preview": "\"\"\"\n>>> gotcha = []\n>>> for s in (Solution(), Solution2()):\n... for _in, _out in (\n... (([1,3,2], 1), 2),\n.."
},
{
"path": "leetcode/684_redundant_connection.py",
"chars": 1785,
"preview": "\"\"\"\ngiven input is an undirected graph\n\n1. iterate edges\n2. if u and v are connected before we add edge in nodes (graph)"
},
{
"path": "leetcode/685_redundant_connection_ii.py",
"chars": 1749,
"preview": "\"\"\"\ngiven input is an directed graph\n\n3 corner cases:\n\n1. There is a loop in the graph, and no vertex has more than 1 pa"
},
{
"path": "leetcode/688_knight_probability_in_chessboard.py",
"chars": 2265,
"preview": "import collections\n\n\nclass Solution:\n \"\"\"\n DP:\n 1. init the first pos as 1\n 2. keep simulate the process and"
},
{
"path": "leetcode/689_maximum_sum_of_3_non_overlapping_subarrays.py",
"chars": 1521,
"preview": "\"\"\"\nREF: https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/108231\n\"\"\"\n\n\nclass Solution:\n "
},
{
"path": "leetcode/697_degree_of_an_array.py",
"chars": 562,
"preview": "class Solution:\n def findShortestSubArray(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n "
},
{
"path": "leetcode/719_find_k_th_smallest_pair_distance.py",
"chars": 878,
"preview": "class Solution:\n def smallestDistancePair(self, A, k):\n \"\"\"\n :type A: List[int]\n :type k: int\n "
},
{
"path": "leetcode/721_accounts_merge.py",
"chars": 955,
"preview": "class Solution:\n def accountsMerge(self, A):\n \"\"\"\n :type A: List[List[str]]\n :rtype: List[List[s"
},
{
"path": "leetcode/734_sentence_similarity.py",
"chars": 1162,
"preview": "\"\"\"\n>>> pairs = [['great', 'fine'], ['acting', 'drama'], ['skills', 'talent']]\n>>> gotcha = []\n>>> s = Solution()\n>>> fo"
},
{
"path": "leetcode/737_sentence_similarity_ii.py",
"chars": 2790,
"preview": "\"\"\"\n>>> pairs = [['great', 'fine'], ['acting', 'drama'], ['skills', 'talent']]\n>>> gotcha = []\n>>> for s in (Solution(),"
},
{
"path": "leetcode/744_find_smallest_letter_greater_than_target.py",
"chars": 522,
"preview": "class Solution:\n def nextGreatestLetter(self, L, target):\n \"\"\"\n :type L: List[str]\n :type target"
},
{
"path": "leetcode/746_min_cost_climbing_stairs.py",
"chars": 635,
"preview": "class Solution:\n def minCostClimbingStairs(self, cost):\n \"\"\"\n :type cost: List[int]\n :rtype: int"
},
{
"path": "leetcode/747_largest_number_at_least_twice_of_others.py",
"chars": 482,
"preview": "class Solution:\n def dominantIndex(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n\n"
},
{
"path": "leetcode/748_shortest_completing_word.py",
"chars": 1071,
"preview": "class Solution:\n def shortestCompletingWord(self, P, words):\n \"\"\"\n :type P: str\n :type words: Li"
},
{
"path": "leetcode/749_contain_virus.py",
"chars": 2726,
"preview": "\"\"\"\nTest Case:\n\n[[1,1,1], [1,0,1], [1,1,1]]\n\n[[1,1,1,0,0,0,0,0,0], [1,0,1,0,1,1,1,1,1], [1,1,1,0,0,0,0,0,0]]\n\n# In the p"
},
{
"path": "leetcode/750_number_of_corner_rectangles.py",
"chars": 1147,
"preview": "class Solution:\n def countCornerRectangles(self, G):\n \"\"\"\n :type G: List[List[int]]\n :rtype: int"
},
{
"path": "leetcode/758_bold_words_in_string.py",
"chars": 1437,
"preview": "\"\"\"\n>>> gotcha = []\n>>> for s in (Solution(),):\n... for _in, _out in (\n... (([''], ''), ''),\n... ((["
},
{
"path": "leetcode/769_max_chunks_to_make_sorted.py",
"chars": 1304,
"preview": "\"\"\"\nMain Concept:\ngiven nums: 0, 2, 1, 4, 3, 5, 7, 6\n\n1. the sorted nums is just its index\n2. maintain a `M` to record, "
},
{
"path": "leetcode/776_split_bst.py",
"chars": 664,
"preview": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# sel"
},
{
"path": "leetcode/777_swap_adjacent_in_lr_string.py",
"chars": 822,
"preview": "class Solution:\n def canTransform(self, start, end):\n \"\"\"\n :type start: str\n :type end: str\n "
},
{
"path": "leetcode/778_swim_in_rising_water.py",
"chars": 888,
"preview": "from heapq import heappush, heappop\n\n\nclass Solution:\n def swimInWater(self, G):\n \"\"\"\n :type G: List[Li"
},
{
"path": "leetcode/779_k_th_symbol_in_grammar.py",
"chars": 458,
"preview": "class Solution:\n def kthGrammar(self, N, K):\n \"\"\"\n :type N: int\n :type K: int\n :rtype: in"
},
{
"path": "leetcode/783_minimum_distance_between_bst_nodes.py",
"chars": 1299,
"preview": "\"\"\"\nDefinition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left"
},
{
"path": "leetcode/784_letter_case_permutation.py",
"chars": 552,
"preview": "class Solution:\n def letterCasePermutation(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n "
},
{
"path": "leetcode/785_is_graph_bipartite.py",
"chars": 481,
"preview": "class Solution:\n def isBipartite(self, graph):\n \"\"\"\n :type graph: List[List[int]]\n :rtype: bool\n"
},
{
"path": "leetcode/786_k_th_smallest_prime_fraction.py",
"chars": 709,
"preview": "\"\"\"\nMain Concept:\njust like found kth smallest num in matrix\n\nexample: [1, 2, 5, 7]\n\n 7 5 2 1\n1 1/7 1/5 1/2 1/"
},
{
"path": "leetcode/787_cheapest_flights_within_k_stops.py",
"chars": 1563,
"preview": "class Solution:\n def findCheapestPrice(self, n, flights, src, dst, K):\n \"\"\"\n :type n: int\n :type"
},
{
"path": "leetcode/788_rotated_digits.py",
"chars": 498,
"preview": "class Solution:\n def rotatedDigits(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n "
},
{
"path": "leetcode/789_escape_the_ghosts.py",
"chars": 426,
"preview": "class Solution:\n def escapeGhosts(self, ghosts, target):\n \"\"\"\n :type ghosts: List[List[int]]\n :t"
},
{
"path": "leetcode/790_domino_and_tromino_tiling.py",
"chars": 339,
"preview": "class Solution:\n def numTilings(self, N):\n \"\"\"\n :type N: int\n :rtype: int\n \"\"\"\n if"
},
{
"path": "leetcode/791_custom_sort_string.py",
"chars": 199,
"preview": "class Solution:\n def customSortString(self, S, T):\n \"\"\"\n :type S: str\n :type T: str\n :rty"
},
{
"path": "leetcode/7_reverse_integer.py",
"chars": 392,
"preview": "class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n ans ="
},
{
"path": "leetcode/81_search_in_rotated_sorted_array_ii.py",
"chars": 305,
"preview": "class Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n"
},
{
"path": "leetcode/8_string_to_integer_atoi.py",
"chars": 737,
"preview": "class Solution:\n def myAtoi(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n ans = "
},
{
"path": "lintcode/102_linked_list_cycle.py",
"chars": 830,
"preview": "\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n "
},
{
"path": "lintcode/103_linked_list_cycle_ii.py",
"chars": 1733,
"preview": "\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n "
},
{
"path": "lintcode/104_merge_k_sorted_lists.py",
"chars": 818,
"preview": "\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n "
},
{
"path": "lintcode/105_copy_list_with_random_pointer.py",
"chars": 1941,
"preview": "\"\"\"\nDefinition for singly-linked list with a random pointer.\nclass RandomListNode:\n def __init__(self, x):\n se"
},
{
"path": "lintcode/107_word_break.py",
"chars": 699,
"preview": "class Solution:\n \"\"\"\n `dp[i]` means `s[:i]` is segmented by words\n \"\"\"\n def wordBreak(self, s, words):\n "
},
{
"path": "lintcode/108_palindrome_partitioning_ii.py",
"chars": 1305,
"preview": "class Solution:\n # @param S, a string\n # @return an integer\n def minCut(self, S):\n if not S:\n "
},
{
"path": "lintcode/109_triangle.py",
"chars": 3062,
"preview": "\"\"\"\nDP: Memory Searching\n\"\"\"\nclass Solution:\n \"\"\"\n @param: triangle: a list of lists of integers\n @return: An i"
},
{
"path": "lintcode/10_string_permutation_ii.py",
"chars": 568,
"preview": "class Solution:\n \"\"\"\n @param: S: A string\n @return: all permutations\n \"\"\"\n def stringPermutation2(self, S"
},
{
"path": "lintcode/110_minimum_path_sum.py",
"chars": 803,
"preview": "class Solution:\n \"\"\"\n @param: grid: a list of lists of integers\n @return: An integer, minimizes the sum of all "
},
{
"path": "lintcode/111_climbing_stairs.py",
"chars": 1119,
"preview": "\"\"\"\nDP: rolling array with `n + 1`\n\"\"\"\nclass Solution:\n \"\"\"\n @param n: An integer\n @return: An integer\n \"\"\"\n"
},
{
"path": "lintcode/114_unique_paths.py",
"chars": 329,
"preview": "class Solution:\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: i"
},
{
"path": "lintcode/115_unique_paths_ii.py",
"chars": 811,
"preview": "class Solution:\n \"\"\"\n @param: G: A list of lists of integers\n @return: An integer\n \"\"\"\n def uniquePathsWi"
},
{
"path": "lintcode/116_jump_game.py",
"chars": 1082,
"preview": "\"\"\"\nGreedy\n\nhttps://leetcode.com/articles/jump-game/\n\"\"\"\nclass Solution:\n def canJump(self, A):\n \"\"\"\n :"
},
{
"path": "lintcode/117_jump_game_ii.py",
"chars": 999,
"preview": "\"\"\"\nGreedy\n\"\"\"\nclass Solution:\n \"\"\"\n @param: A: A list of integers\n @return: An integer\n \"\"\"\n def jump(se"
},
{
"path": "lintcode/118_distinct_subsequences.py",
"chars": 1195,
"preview": "class Solution:\n \"\"\"\n @param: : A string\n @param: : A string\n @return: Count the number of distinct subseque"
},
{
"path": "lintcode/119_edit_distance.py",
"chars": 1257,
"preview": "class Solution:\n def minDistance(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: i"
},
{
"path": "lintcode/11_search_range_in_binary_search_tree.py",
"chars": 661,
"preview": "\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self."
},
{
"path": "lintcode/120_word_ladder.py",
"chars": 1485,
"preview": "\"\"\"\nTest Case:\n\n\"a\"\n\"a\"\n[\"b\"]\n=> should check again words in queue\n\"\"\"\n\n\nclass Solution:\n def ladderLength(self, s, e"
},
{
"path": "lintcode/121_word_ladder_ii.py",
"chars": 2060,
"preview": "\"\"\"\nMain Concept:\n\n1. building `next_words` in advance to speed up\n2. using BFS from `B` to `A` to calculate the distanc"
},
{
"path": "lintcode/122_largest_rectangle_in_histogram.py",
"chars": 1952,
"preview": "\"\"\"\nREF: https://aaronice.gitbooks.io/lintcode/content/data_structure/largest_rectangle_in_histogram.html\n\"\"\"\n\n\n\"\"\"\nBrut"
},
{
"path": "lintcode/123_word_search.py",
"chars": 1120,
"preview": "class Solution:\n V = (\n (-1, 0),\n ( 1, 0),\n ( 0, -1),\n ( 0, 1),\n )\n\n \"\"\"\n @pa"
},
{
"path": "lintcode/124_longest_consecutive_sequence.py",
"chars": 1406,
"preview": "class Solution:\n \"\"\"\n maintain a set to record if there is unused cands\n \"\"\"\n def longestConsecutive(self, n"
},
{
"path": "lintcode/125_backpack_ii.py",
"chars": 1598,
"preview": "\"\"\"\nRolling Array\n\"\"\"\nclass Solution:\n \"\"\"\n @param: m: An integer m denotes the size of a backpack\n @param: A: "
},
{
"path": "lintcode/126_max_tree.py",
"chars": 932,
"preview": "\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self."
},
{
"path": "lintcode/127_topological_sorting.py",
"chars": 952,
"preview": "\"\"\"\nDefinition for a Directed graph node\nclass DirectedGraphNode:\n def __init__(self, x):\n self.label = x\n "
},
{
"path": "lintcode/128_hash_function.py",
"chars": 373,
"preview": "class Solution:\n \"\"\"\n @param: key: A string you should hash\n @param: HASH_SIZE: An integer\n @return: An inte"
}
]
// ... and 438 more files (download for full content)
About this extraction
This page contains the full source code of the jaychsu/algorithm GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 638 files (761.9 KB), approximately 235.0k tokens, and a symbol index with 2088 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.