├── .gitignore ├── LICENSE ├── README.md ├── code-of-conduct.md ├── contributing.md ├── extras └── cheat sheets │ ├── C Reference Card (ANSI) 2.2.pdf │ ├── Coding Interview Python Language Essentials.pdf │ ├── Cpp_reference.pdf │ ├── STL Quick Reference 1.29.pdf │ ├── big-o-cheatsheet.pdf │ ├── bits-cheat-sheet.pdf │ ├── python-cheat-sheet-v1.pdf │ └── system-design.pdf ├── faang-codingexercises ├── Dockerfile ├── LICENSE ├── Pipfile ├── Pipfile.lock ├── README.md ├── _config.yml ├── archive_test_reports.py ├── bash_scripts │ ├── datetime.dat │ └── datetime_epoc.sh ├── codechallenge_001.py ├── codechallenge_002.py ├── codechallenge_003.py ├── codechallenge_004.py ├── codechallenge_005.py ├── codechallenge_006.py ├── codechallenge_007.py ├── codechallenge_008.py ├── codechallenge_009.py ├── codechallenge_010.py ├── codechallenge_011.py ├── codechallenge_012.py ├── codechallenge_013.py ├── codechallenge_015.py ├── codechallenge_016.py ├── codechallenge_017.py ├── codechallenge_018.py ├── codechallenge_019.py ├── codechallenge_020.py ├── codechallenge_021.py ├── codechallenge_022.py ├── codechallenge_023.py ├── codechallenge_025.py ├── codechallenge_026.py ├── codechallenge_027.py ├── codechallenge_028.py ├── codechallenge_029.py ├── codechallenge_030.py ├── codechallenge_031.py ├── codechallenge_032.py ├── codechallenge_033.py ├── codechallenge_034.py ├── codechallenge_035.py ├── codechallenge_036.py ├── codechallenge_038.py ├── codechallenge_039.py ├── codechallenge_040.py ├── codechallenge_041.py ├── codechallenge_042.py ├── codechallenge_044.py ├── codechallenge_045.py ├── codechallenge_100.py ├── codechallenge_101.py ├── codechallenge_102.py ├── codechallenge_103.py ├── codechallenge_104.py ├── codechallenge_105.py ├── codechallenge_106.py ├── codechallenge_107.py ├── codechallenge_108.py ├── codechallenge_109.py ├── codility │ └── codility_0001.py ├── module_unittests.py ├── node_modules │ ├── numpy │ │ ├── LICENSE │ │ ├── README.md │ │ └── package.json │ └── unittest │ │ ├── index.js │ │ ├── model │ │ ├── Auth.js │ │ └── User.js │ │ ├── package.json │ │ └── test │ │ └── testUser.js ├── package-lock.json ├── resources │ └── bkg-blu.jpg ├── run.sh ├── test_reports │ └── test_results.xml ├── tests.py └── tests_output.txt ├── img ├── All-The-Worlds-Brands.jpg ├── faang-stocks.png └── fangvaasm.jpg ├── leetcode-part-1 ├── LICENSE ├── README.md ├── cpp │ ├── 1248_count_number_of_nice_sub_arrays.cpp │ ├── 1310_XOR_Queries_of_a_Subarray.cpp │ ├── 201_bitwise_and_of_numbers_range.cpp │ ├── 204_Count_Primes.cpp │ ├── 206_Reverse_Linked_List.cpp │ ├── 282_Expression_Add_Operators.cpp │ ├── 412_Fizz_Buzz.cpp │ ├── 668_Kth_Smallest_Number_in_Multiplication_Table.cpp │ └── 923_3_sum_with_multiplicity.cpp ├── create_empty_files.py ├── java │ ├── 001_Two_Sum.java │ ├── 002_Add_Two_Numbers.java │ ├── 003_Longest_Substring_Without_Repeating_Characters.java │ ├── 004_Median_of_Two_Sorted_Arrays.java │ ├── 005_Longest_Palindromic_Substring.java │ ├── 006_ZigZag_Conversion.java │ ├── 007_Reverse_Integer.java │ ├── 008_String_to_Integer(atoi).java │ ├── 009_Palindrome_Number.java │ ├── 011_Container_With_Most_Water.java │ ├── 012_Integer_to_Roman.java │ ├── 013_Roman_to_Integer.java │ ├── 019_Remove_Nth_Node_From_End_of_List.java │ ├── 066_Plus_One.java │ ├── 1064_Fixed_Point.java │ ├── 1089_Duplicate_Zeros.java │ ├── 1108_Defanging_an_IP_Address.java │ ├── 1189_Maximum_Number_of_Balloons.java │ ├── 1260_Shift_2D_Grid.java │ ├── 1304_Find_N_Unique_Integers_Sum_up_to_Zero.java │ ├── 1310_XOR_Queries_of_a_Subarray.java │ ├── 1323_Maximum_69_Number.java │ ├── 1337_The_K_Weakest_Rows_in_a_Matrix.java │ ├── 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.java │ ├── 1480_Running_Sum_of_1d_Array.java │ ├── 1539_Kth_Missing_Positive_Number.java │ ├── 155_Min_Stack.java │ ├── 179_Largest_Number.java │ ├── 1981_Minimize_the_Difference_Between_Target_and_Chosen_Elements.java │ ├── 204_Count_Primes.java │ ├── 206_Reverse_Linked_List.java │ ├── 215_Kth_Largest_Element_in_an_Array.java │ ├── 223_Rectangle_Area.java │ ├── 236_Lowest_Common_Ancestor_of_a_Binary_Tree.java │ ├── 238_Product_of_Array_Except_Self.java │ ├── 253_Meeting_Rooms_II.java │ ├── 268_Missing_Number.java │ ├── 273_Integer_to_English_Words.java │ ├── 336_Palindrome_Pairs.java │ ├── 347_Top_K_Frequent_Elements.java │ ├── 367_Valid_Perfect_Square.java │ ├── 383_Ransom_Note.java │ ├── 387_First_Unique_Character_in_a_String.java │ ├── 389_Find_the_Difference.java │ ├── 400_Nth_Digit.java │ ├── 401_Binary_Watch.java │ ├── 404_Sum_of_Left_Leaves.java │ ├── 405_Convert_a_Number_to_Hexadecimal.java │ ├── 409_Longest_Palindrome.java │ ├── 412_Fizz_Buzz.java │ ├── 414_Third_Maximum_Number.java │ ├── 415_Add_Strings.java │ ├── 434_Number_of_Segments_in_a_String.java │ ├── 437_Path_Sum_III.java │ ├── 438_Find_All_Anagrams_in_a_String.java │ ├── 443_String_Compression.java │ ├── 448_Find_All_Numbers_Disappeared_in_an_Array.java │ ├── 453_Minimum_Moves_to_Equal_Array_Elements.java │ ├── 458_Poor_Pigs.java │ ├── 461_Hamming_Distance.java │ ├── 463_Island_Perimeter.java │ ├── 475_Heaters.java │ ├── 479_Largest_Palindrome_Product.java │ ├── 482_License_Key_Formatting.java │ ├── 485_Max_Consecutive_Ones.java │ ├── 509_Fibonacci_Number.java │ ├── 538_Convert_BST_to_Greater_Tree.java │ ├── 541_Reverse_String_II.java │ ├── 543_Diameter_of_Binary_Tree.java │ ├── 547_Friend_Circles.java │ ├── 557_Reverse_Words_in_a_String_III.java │ ├── 560_Subarray_Sum_Equals_K.java │ ├── 572_Subtree_of_Another_Tree.java │ ├── 581_Shortest_Unsorted_Continuous_Subarray.java │ ├── 605_Can_Place_Flowers.java │ ├── 617_Merge_Two_Binary_Trees.java │ ├── 628_Maximum_Product_of_Three_Numbers.java │ ├── 654_Maximum_Binary_Tree.java │ ├── 665_Non-decreasing_Array.java │ ├── 668_Kth_Smallest_Number_in_Multiplication_Table.java │ ├── 671_Second_Minimum_Node_In_a_Binary_Tree.java │ ├── 674_Longest_Continuous_Increasing_Subsequence.java │ ├── 680_Valid_Palindrome_II.java │ ├── 692_Top_K_Frequent_Words.java │ ├── 695_Max_Area_of_Island.java │ ├── 697_Degree_of_an_Array.java │ ├── 700_Search_in_a_Binary_Search_Tree.java │ ├── 703_Kth_Largest_Element_in_a_Stream.java │ ├── 706_Design_HashMap.java │ ├── 709_To_Lower_Case.java │ ├── 716_Max_Stack.java │ ├── 717_1-bit_and_2-bit_Characters.java │ ├── 720_Longest_Word_in_Dictionary.java │ ├── 724_Find_Pivot_Index.java │ ├── 728_Self_Dividing_Numbers.java │ ├── 733_Flood_Fill.java │ ├── 743_Network_Delay_Time.java │ ├── 751_IP_to_CIDR.java │ ├── 760_Find_Anagram_Mappings.java │ ├── 766_Toeplitz_Matrix.java │ ├── 771_Jewels_and_Stones.java │ ├── 784_Letter_Case_Permutation.java │ ├── 804_Unique_Morse_Code_Words.java │ ├── 811_Subdomain_Visit_Count.java │ ├── 819_Most_Common_Word.java │ ├── 832_Flipping_an_Image.java │ ├── 836_Rectangle_Overlap.java │ ├── 844_Backspace_String_Compare.java │ ├── 852_Peak_Index_in_a_Mountain_Array.java │ ├── 867_Transpose_Matrix.java │ ├── 868_Binary_Gap.java │ ├── 872_Leaf-Similar_Trees.java │ ├── 876_Middle_of_the_Linked_List.java │ ├── 904_Fruit_Into_Baskets.java │ ├── 905_Sort_Array_By_Parity.java │ ├── 922_Sort_Array_By_Parity_II.java │ ├── 929_Unique_Email_Addresses.java │ ├── 933_Number_of_Recent_Calls.java │ ├── 937_Reorder_Log_Files.java │ ├── 945_Minimum_Increment_to_Make_Array_Unique.java │ ├── 946_Validate_Stack_Sequences.java │ ├── 953_Verifying_an_Alien_Dictionary.java │ ├── 954_Array_of_Doubled_Pairs.java │ ├── 961_N-Repeated_Element_in_Size_2N_Array.java │ ├── 962_Maximum_Width_Ramp.java │ ├── 973_K_Closest_Points_to_Origin.java │ └── 977_Squares_of_a_Sorted_Array.java └── python │ ├── 001_Two_Sum.py │ ├── 002_Add_Two_Numbers.py │ ├── 003_Longest_Substring_Without_Repeating_Characters.py │ ├── 004_Median_of_Two_Sorted_Arrays.py │ ├── 005_Longest_Palindromic_Substring.py │ ├── 006_ZigZag_Conversion.py │ ├── 007_Reverse_Integer.py │ ├── 008_String_to_Integer(atoi).py │ ├── 009_Palindrome_Number.py │ ├── 010_Regular_Expression_Matching.py │ ├── 011_Container_With_Most_Water.py │ ├── 012_Integer_to_Roman.py │ ├── 013_Roman_to_Integer.py │ ├── 014_Longest_Common_Prefix.py │ ├── 015_3Sum.py │ ├── 016_3Sum_Closest.py │ ├── 017_Letter_Combinations_of_a_Phone_Number.py │ ├── 018_4Sum.py │ ├── 019_Remove_Nth_Node_From_End_of_List.py │ ├── 020_Valid_Parentheses.py │ ├── 021_Merge_Two_Sorted_Lists.py │ ├── 022_Generate_Parentheses.py │ ├── 023_Merge_k_Sorted_Lists.py │ ├── 024_Swap_Nodes_in_Pairs.py │ ├── 025_Reverse_Nodes_i_ k-Group.py │ ├── 026_Remove_Duplicates_from_Sorted_Array.py │ ├── 027_Remove_Element.py │ ├── 028_Implement_strStr().py │ ├── 029_Divide_Two_Integers.py │ ├── 030_Substring_with_Concatenation_of_All_Words.py │ ├── 031_Next_Permutation.py │ ├── 032_Longest_Valid_Parentheses.py │ ├── 033_Search_in_Rotated_Sorted_Array.py │ ├── 034_Search_for_a_Range.py │ ├── 035_Search_Insert_Position.py │ ├── 036_Valid Sudoku.py │ ├── 037_Sudoku_Solver.py │ ├── 038_Count_and_Say.py │ ├── 039_Combination_Sum.py │ ├── 040_Combination_Sum_II.py │ ├── 041_First_Missing_Positive.py │ ├── 042_Trapping_Rain_Water.py │ ├── 043_Multiply_Strings.py │ ├── 044_Wildcard_Matching.py │ ├── 045_Jump_Game_II.py │ ├── 046_Permutations.py │ ├── 047_Permutations_II.py │ ├── 048_Rotate_Image.py │ ├── 049_Group_Anagrams.py │ ├── 050_Pow(x, n).py │ ├── 051_N-Queens.py │ ├── 052_N-Queens II.py │ ├── 053_Maximum_Subarray.py │ ├── 054_Spiral_Matrix.py │ ├── 055_Jump_Game.py │ ├── 056_Merge_Intervals.py │ ├── 057_Insert_Interval.py │ ├── 058_Length_of_Last_Word.py │ ├── 059_Spiral_Matrix_II.py │ ├── 060_Permutation_Sequence.py │ ├── 061_Rotate_List.py │ ├── 062_Unique_Paths.py │ ├── 063_Unique_Paths_II.py │ ├── 064_Minimum_Path_Sum.py │ ├── 065_Valid_Number.py │ ├── 066_Plus_One.py │ ├── 067_Add_Binary.py │ ├── 068_Text_Justification.py │ ├── 069_Sqrt(x).py │ ├── 070_Climbing_Stairs.py │ ├── 071_Simplify_Path.py │ ├── 072_Edit_Distance.py │ ├── 073_Set_Matrix_Zeroes.py │ ├── 074_Search_a_2D_Matrix.py │ ├── 075_Sort_Colors.py │ ├── 076_Minimum_Window_Substring.py │ ├── 077_Combinations.py │ ├── 078_Subsets.py │ ├── 079_Word_Search.py │ ├── 080_Remove_Duplicates_from_Sorted_Array_II.py │ ├── 081_Search_in_Rotated_Sorted_Array_II.py │ ├── 083_Remove_Duplicates_from_Sorted_List.py │ ├── 084_Largest_Rectangle_in_Histogram.py │ ├── 085_Maximal_Rectangle.py │ ├── 086_Partition_List.py │ ├── 087_Scramble_String.py │ ├── 088_Merge_Sorted_Array.py │ ├── 089_Gray_Code.py │ ├── 090_Subsets_II.py │ ├── 091_Decode_Ways.py │ ├── 092_Reverse_Linked_Lis_ II.py │ ├── 093_Restore_IP_Addresses.py │ ├── 094_Binary_Tree_Inorder_Traversal.py │ ├── 095_Unique_Binary_Search_Trees_II.py │ ├── 096_Unique_Binary_Search_Trees.py │ ├── 097_Interleaving_String.py │ ├── 098_Validate_Binary_Search_Tree.py │ ├── 099_Recover_Binary_Search_Tree.py │ ├── 100_Same_Tree.py │ ├── 101_Symmetric_Tree.py │ ├── 102_Binary_Tree_Level_Order_Traversal.py │ ├── 103_Binary_Tree_Zigzag_Level_Order_Traversal.py │ ├── 104_Maximum_Depth_of_Binary_Tree.py │ ├── 105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py │ ├── 1064_Fixed_Point.py │ ├── 106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py │ ├── 107_Binary_Tree_Level_Order_Traversal_II.py │ ├── 1089_Duplicate_Zeros.py │ ├── 108_Convert_Sorted_Array_to_Binary_Search_Tree.py │ ├── 109_Convert_Sorted_List_to_Binary_Search_Tree.py │ ├── 1108_Defanging_an_IP_Address.py │ ├── 110_Balanced_Binary_Tree.py │ ├── 111_Minimum_Depth_of_Binary_Tree.py │ ├── 112_Path_Sum.py │ ├── 113_Path_Sum_II.py │ ├── 114_Flatten_Binary_Tree_to_Linked_List.py │ ├── 115_Distinct_Subsequences.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 │ ├── 119_Pascal's_Triangle_II.py │ ├── 120_Triangle.py │ ├── 121_Best_Time_to_Buy_and_Sell_Stock.py │ ├── 122_Best_Time_to_Buy_and_Sell_Stock_II.py │ ├── 123_Best_Time_to_Buy_and_Sell_Stock_III.py │ ├── 124_Binary_Tree_Maximum_Path_Sum.py │ ├── 125_Valid_Palindrome.py │ ├── 1260_Shift_2D_Grid.py │ ├── 126_Word_Ladder_II.py │ ├── 127_Word_Ladder.py │ ├── 128_Longest_Consecutive_Sequence.py │ ├── 1290_Convert_Binary_Number_in_a_Linked_List_to_Integer.py │ ├── 129_Sum_Root_to_Leaf_Numbers.py │ ├── 1304_Find_N_Unique_Integers_Sum_up_to_Zero.py │ ├── 130_Surrounded_Regions.py │ ├── 1310_XOR_Queries_of_a_Subarray.py │ ├── 131_Palindrome_Partitioning.py │ ├── 1323_Maximum_69_Number.py │ ├── 132_Palindrome_Partitioning_II.py │ ├── 1337_The_K_Weakest_Rows_in_a_Matrix.py │ ├── 133_Clone_Graph.py │ ├── 1342_Number_of_Steps_to_Reduce_a_Number_to_Zero.py │ ├── 134_Gas_Station.py │ ├── 135_Candy.py │ ├── 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py │ ├── 136_Single_Number.py │ ├── 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py │ ├── 137_Single_Number_II.py │ ├── 138_Copy_List_with_Random_Pointer.py │ ├── 139_Word_Break.py │ ├── 140_Word_Break_II.py │ ├── 141_Linked_List_Cycle.py │ ├── 142_Linked_List_Cycle_II.py │ ├── 143_Reorder_List.py │ ├── 144_Binary_Tree_Preorder_Traversal.py │ ├── 145_Binary_Tree_Postorder_Traversal.py │ ├── 146_LRU_Cache.py │ ├── 147_Insertion_Sort_List.py │ ├── 1480_Running_Sum_of_1d_Array.py │ ├── 149_Max_Points_on_a_Line.py │ ├── 150_Evaluate_Reverse_Polish_Notation.py │ ├── 151_Reverse_Words_in_a_String.py │ ├── 152_Maximum_Product_Subarray.py │ ├── 153_Find_Minimum_in_Rotated_Sorted_Array.py │ ├── 154_Find_Minimum_in_Rotated_Sorted_Array_II.py │ ├── 155_Min_Stack.py │ ├── 156_Binary_Tree_Upside_Down.py │ ├── 157_Read_N_Characters_Given_Read4.py │ ├── 158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py │ ├── 1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py │ ├── 159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py │ ├── 160_Intersection_of_Two_Linked_Lists.py │ ├── 161_One_Edit_Distance.py │ ├── 162_Find_Peak_Element.py │ ├── 163_Missing_Ranges.py │ ├── 165_Compare_Version_Numbers.py │ ├── 166_Fraction_to_Recurring_Decimal.py │ ├── 167_Two_Sum_II_Input_array_is_sorted.py │ ├── 168_Excel_Sheet_Column_Title.py │ ├── 170_Two_Sum_III-Data_structure_design.py │ ├── 179_Largest_Number.py │ ├── 186_Reverse_Words_in_a_String_II.py │ ├── 191_Number_of_1_Bits.py │ ├── 198_House_Robber.py │ ├── 200_Number_of_Islands.py │ ├── 202_Happy_Number.py │ ├── 203_Remove_Linked_List_Elements.py │ ├── 204_Count_Primes.py │ ├── 205_Isomorphic_Strings.py │ ├── 206_Reverse_Linked_List.py │ ├── 207_Course_Schedule.py │ ├── 208_Implement_Trie_(Prefix_Tree).py │ ├── 213_House_Robber_II.py │ ├── 215_Kth_Largest_Element_in_an_Array.py │ ├── 216_Combination_Sum_III.py │ ├── 217_Contains_Duplicate.py │ ├── 219_Contains_Duplicate_II.py │ ├── 220_Contains_Duplicate_III.py │ ├── 221_Maximal_Square.py │ ├── 223_Rectangle Area.py │ ├── 225_Implement_Stack_using_Queues.py │ ├── 226_Invert_Binary_Tree.py │ ├── 228_Summary_Ranges.py │ ├── 229_Majority_Element_II.py │ ├── 231_Power_of_Two.py │ ├── 232_Implement_Queue_using_Stacks.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 │ ├── 238_Product_of_Array_Except_Self.py │ ├── 242_Valid_Anagram.py │ ├── 243_Shortest_Word_Distance.py │ ├── 246_Strobogrammatic_Number.py │ ├── 249_Group_Shifted_Strings.py │ ├── 252_Meeting_Rooms.py │ ├── 253_Meeting_Rooms_II.py │ ├── 257_Binary_Tree_Paths.py │ ├── 258_Add_Digits.py │ ├── 259_3Sum_Smaller.py │ ├── 263_Ugly_Number.py │ ├── 264_Ugly_Number_II.py │ ├── 266_Palindrome_Permutation.py │ ├── 267_Palindrome_Permutation_II.py │ ├── 268_Missing_Number.py │ ├── 270_Closest_Binary_Search_Tree_Value.py │ ├── 273_Integer_to_English_Words.py │ ├── 274_H-Index.py │ ├── 276_Paint_Fence.py │ ├── 278_First_Bad_Version.py │ ├── 280_Wiggle_Sort.py │ ├── 283_Move Zeroes.py │ ├── 286_Walls_and_Gates.py │ ├── 288_Unique_Word_Abbreviation.py │ ├── 290_Word_Pattern.py │ ├── 292_Nim_Game.py │ ├── 293_Flip_Game.py │ ├── 294_Flip_Game_II.py │ ├── 296_Best_Meeting_Point.py │ ├── 298_Binary_Tree_Longest_Consecutive_Sequence.py │ ├── 299_Bulls_and_Cows.py │ ├── 303_Range_Sum_Query_Immutable.py │ ├── 304_Range_Sum_Query_2D_Immutable.py │ ├── 305_Number_of_Islands_II.py │ ├── 307_Range_Sum_Query_Mutable.py │ ├── 322_Coin_Change.py │ ├── 326_Power_of_Three.py │ ├── 328_Odd_Even_Linked_List.py │ ├── 336_Palindrome_Pairs.py │ ├── 337_House_Robber_III.py │ ├── 338_Counting_Bits.py │ ├── 339_Nested_List_Weight_Sum.py │ ├── 340_Longest_Substring_with_At_Most_K_Distinct_Characters.py │ ├── 342_Power_of_Four.py │ ├── 344_Reverse_String.py │ ├── 345_Reverse_Vowels_of_a_String.py │ ├── 346_Moving_Average_from_Data_Stream.py │ ├── 347_Top_K_Frequent_Elements.py │ ├── 349_Intersection_of_Two_Arrays.py │ ├── 350_Intersection_of_Two_Arrays_II.py │ ├── 351_Android_Unlock_Patterns.py │ ├── 359_Logger_Rate_Limiter.py │ ├── 366_Find_Leaves_of_Binary_Tree.py │ ├── 367_Valid_Perfect_Square.py │ ├── 368_Largest_Divisible_Subset.py │ ├── 369_Plus_One_Linked_List.py │ ├── 370_Range_Addition.py │ ├── 371_Sum_of_Two_Integers.py │ ├── 372_Super_Pow.py │ ├── 373_Find_K_Pairs_with_Smallest_Sums.py │ ├── 374_Guess_Number_Higher_or_Lower.py │ ├── 375_Guess_Number_Higher_or_Lower_II.py │ ├── 380_Insert_Delete_GetRandom.py │ ├── 383_Ransom_Note.py │ ├── 384_Shuffle_an_Array.py │ ├── 387_First_Unique_Character_in_a_String.py │ ├── 388_Longest_Absolute_File_Path.py │ ├── 389_Find_the_Difference.py │ ├── 400_Nth_Digit.py │ ├── 401_Binary_Watch.py │ ├── 404_Sum_of_Left_Leaves.py │ ├── 405_Convert_a_Number_to_Hexadecimal.py │ ├── 408_Valid_Word_Abbreviation.py │ ├── 409_Longest_Palindrome.py │ ├── 412_Fizz_Buzz.py │ ├── 414_Third_Maximum_Number.py │ ├── 415_Add_Strings.py │ ├── 416_Partition_Equal_Subset_Sum.py │ ├── 421_Maximum_XOR_of_Two_Numbers_in_an_Array.py │ ├── 422_Valid_Word_Square.py │ ├── 434_Number_of_Segments_in_a_String.py │ ├── 437_Path_Sum_III.py │ ├── 438_Find_All_Anagrams_in_a_String.py │ ├── 441_Arranging_Coins.py │ ├── 443_String_Compression.py │ ├── 448_Find_All_Numbers_Disappeared_in_an_Array.py │ ├── 453_Minimum_Moves_to_Equal_Array_Elements.py │ ├── 457_Circular_Array_Loop.py │ ├── 458_Poor_Pigs.py │ ├── 461_Hamming_Distance.py │ ├── 463_Island_Perimeter.py │ ├── 475_Heaters.py │ ├── 479_Largest_Palindrome_Product.py │ ├── 482_License_Key_Formatting.py │ ├── 485_Max_Consecutive_Ones.py │ ├── 509_Fibonacci_Number.py │ ├── 538_Convert_BST_to_Greater_Tree.py │ ├── 541_Reverse_String_II.py │ ├── 543_Diameter_of_Binary_Tree.py │ ├── 547_Friend_Circles.py │ ├── 557_Reverse_Words_in_a_String_III.py │ ├── 560_Subarray_Sum_Equals_K.py │ ├── 572_Subtree_of_Another_Tree.py │ ├── 581_Shortest_Unsorted_Continuous_Subarray.py │ ├── 605_Can_Place_Flowers.py │ ├── 617_Merge_Two_Binary_Trees.py │ ├── 628_Maximum_Product_of_Three_Numbers.py │ ├── 654_Maximum_Binary_Tree.py │ ├── 665_Non-decreasing_Array.py │ ├── 668_Kth_Smallest_Number_in_Multiplication_Table.py │ ├── 671_Second_Minimum_Node_In_a_Binary_Tree.py │ ├── 674_Longest_Continuous_Increasing_Subsequence.py │ ├── 680_Valid_Palindrome_II.py │ ├── 692_Top_K_Frequent_Words.py │ ├── 695_Max_Area_of_Island.py │ ├── 697_Degree_of_an_Array.py │ ├── 700_Search_in_a_Binary_Search_Tree.py │ ├── 703_Kth_Largest_Element_in_a_Stream.py │ ├── 706_Design_HashMap.py │ ├── 709_To_Lower_Case.py │ ├── 716_Max_Stack.py │ ├── 717_1-bit_and_2-bit_Characters.py │ ├── 720_Longest_Word_in_Dictionary.py │ ├── 724_Find_Pivot_Index.py │ ├── 728_Self_Dividing_Numbers.py │ ├── 733_Flood_Fill.py │ ├── 743_Network_Delay_Time.py │ ├── 751_IP_to_CIDR.py │ ├── 760_Find_Anagram_Mappings.py │ ├── 766_Toeplitz_Matrix.py │ ├── 771_Jewels_and_Stones.py │ ├── 784_Letter_Case_Permutation.py │ ├── 804_Unique_Morse_Code_Words.py │ ├── 811_Subdomain_Visit_Count.py │ ├── 819_Most_Common_Word.py │ ├── 832_Flipping_an_Image.py │ ├── 836_Rectangle_Overlap.py │ ├── 844_Backspace_String_Compare.py │ ├── 852_Peak_Index_in_a_Mountain_Array.py │ ├── 867_Transpose_Matrix.py │ ├── 868_Binary_Gap.py │ ├── 872_Leaf-Similar_Trees.py │ ├── 876_Middle_of_the_Linked_List.py │ ├── 904_Fruit_Into_Baskets.py │ ├── 905_Sort_Array_By_Parity.py │ ├── 922_Sort_Array_By_Parity_II.py │ ├── 929_Unique_Email_Addresses.py │ ├── 933_Number_of_Recent_Calls.py │ ├── 937_Reorder_Log_Files.py │ ├── 945_Minimum_Increment_to_Make_Array_Unique.py │ ├── 946_Validate_Stack_Sequences.py │ ├── 953_Verifying_an_Alien_Dictionary.py │ ├── 954_Array_of_Doubled_Pairs.py │ ├── 961_N-Repeated_Element_in_Size_2N_Array.py │ ├── 962_Maximum_Width_Ramp.py │ ├── 973_K_Closest_Points_to_Origin.py │ ├── 977_Squares_of_a_Sorted_Array.py │ ├── 981_Time_Based_Store.py │ ├── 997_Find_The_Town_Judge.py │ └── __init__.py ├── leetcode-part-2 ├── LeetCode.iml ├── array │ ├── BestTimeToBuyAndSellStock.java │ ├── ContainsDuplicatesII.java │ ├── FindAllNumbersDisappearedInAnArray.java │ ├── FindTheCelebrity.java │ ├── GameOfLife.java │ ├── IncreasingTripletSubsequence.java │ ├── InsertDeleteGetRandomO1.java │ ├── InsertInterval.java │ ├── LongestConsecutiveSequence.java │ ├── MajorityElement.java │ ├── MaximumProductSubarray.java │ ├── MaximumSubarray.java │ ├── MergeIntervals.java │ ├── MinCostClimbingStairs.java │ ├── MinimumPathSum.java │ ├── MissingRanges.java │ ├── PlusOne.java │ ├── ProductofArrayExceptSelf.java │ ├── RemoveElement.java │ ├── RotateImage.java │ ├── SearchInRotatedSortedArray.java │ ├── SpiralMatrix.java │ ├── SpiralMatrixII.java │ ├── Subsets.java │ ├── SubsetsII.java │ ├── SummaryRanges.java │ ├── UniquePaths.java │ ├── WiggleSort.java │ └── WordSearch.java ├── backtracking │ ├── AndroidUnlockPatterns.java │ ├── GeneralizedAbbreviation.java │ ├── GenerateParentheses.java │ ├── LetterCombinationsOfAPhoneNumber.java │ └── Permutations.java ├── binary-search │ ├── ClosestBinarySearchTreeValue.java │ ├── FirstBadVersion.java │ ├── GuessNumberHigherOrLower.java │ ├── PowerOfXToTheN.java │ └── SquareRootX.java ├── bit-manipulation │ ├── BinaryWatch.java │ ├── CountingBits.java │ ├── HammingDistance.java │ ├── MaximumProductOfWordLengths.java │ ├── NumberOfOneBits.java │ ├── PowerOfTwo.java │ ├── SumOfTwoInteger.java │ └── Utf8Validation.java ├── brainteaser │ └── BulbSwitcher.java ├── breadth-first-search │ ├── BinaryTreeLevelOrderTraversal.java │ ├── CloneGraph.java │ ├── PacificAtlanticWaterFlow.java │ ├── RemoveInvalidParentheses.java │ ├── ShortestDistanceFromAllBuildings.java │ ├── SymmetricTree.java │ └── WallsAndGates.java ├── depth-first-search │ ├── BalancedBinaryTree.java │ ├── BattleshipsInABoard.java │ ├── ConvertSortedArrayToBinarySearchTree.java │ ├── MaximumDepthOfABinaryTree.java │ ├── NumberOfIslands.java │ ├── PopulatingNextRightPointersInEachNode.java │ └── SameTree.java ├── design │ ├── InsertDeleteGetRandomO1.java │ ├── MinStack.java │ └── ZigZagIterator.java ├── divide-and-conquer │ ├── ExpressionAddOperators.java │ └── KthLargestElementInAnArray.java ├── dynamic-programming │ ├── BombEnemy.java │ ├── ClimbingStairs.java │ ├── CoinChange.java │ ├── CombinationSumIV.java │ ├── CountingBits.java │ ├── EditDistance.java │ ├── HouseRobber.java │ ├── HouseRobberII.java │ ├── LongestIncreasingSubsequence.java │ ├── MinCostClimbingStairs.java │ ├── MinimumPathSum.java │ ├── PaintFence.java │ ├── PaintHouse.java │ ├── PaintHouseII.java │ ├── PalindromicSubstrings.java │ ├── RegularExpressionMatching.java │ ├── SentenceScreenFitting.java │ ├── UniqueBinarySearchTrees.java │ ├── UniquePaths.java │ └── WordBreak.java ├── greedy │ └── BestTimeToBuyAndSellStockII.java ├── hash-table │ ├── BinaryTreeVerticalOrderTraversal.java │ ├── BullsAndCows.java │ ├── ContainsDuplicate.java │ ├── ContainsDuplicatesII.java │ ├── DailyTemperatures.java │ ├── EncodeAndDecodeTinyURL.java │ ├── FindAnagramMappings.java │ ├── FindTheDifference.java │ ├── FirstUniqueCharacterInAString.java │ ├── GroupAnagrams.java │ ├── GroupShiftedStrings.java │ ├── InsertDeleteGetRandomO1.java │ ├── IslandPerimeter.java │ ├── JewelsAndStones.java │ ├── LoggerRateLimiter.java │ ├── MaximumSizeSubarraySumEqualsK.java │ ├── MinimumWindowSubstring.java │ ├── SingleNumberII.java │ ├── SparseMatrixMultiplication.java │ ├── StrobogrammaticNumber.java │ ├── TwoSum.java │ ├── UniqueWordAbbreviation.java │ ├── ValidAnagram.java │ └── ValidSudoku.java ├── linked-list │ ├── AddTwoNumbers.java │ ├── DeleteNodeInALinkedList.java │ ├── LinkedListCycle.java │ ├── MergeKSortedLists.java │ ├── PalindromeLinkedList.java │ ├── PlusOneLinkedList.java │ └── ReverseLinkedList.java ├── math │ ├── AddDigits.java │ ├── BulbSwitcher.java │ ├── EncodeAndDecodeTinyURL.java │ ├── PalindromeNumber.java │ ├── PlusOne.java │ ├── PoorPigs.java │ └── PowerOfTwo.java ├── queue │ └── MovingAverageFromDataStream.java ├── sort │ ├── MeetingRooms.java │ └── MeetingRoomsII.java ├── stack │ ├── BinarySearchTreeIterator.java │ ├── DailyTemperatures.java │ ├── DecodeString.java │ ├── ExclusiveTimeOfFunctions.java │ ├── FlattenNestedListIterator.java │ ├── MinStack.java │ └── TrappingRainWater.java ├── string │ ├── AddBinary.java │ ├── CountAndSay.java │ ├── DecodeWays.java │ ├── EditDistance.java │ ├── FirstUniqueCharacterInAString.java │ ├── GenerateParentheses.java │ ├── IntegerToEnglishWords.java │ ├── JudgeRouteCircle.java │ ├── LongestCommonPrefix.java │ ├── LongestPalindrome.java │ ├── LongestPalindromicSubstring.java │ ├── LongestSubstringWithAtMostKDistinctCharacters.java │ ├── MinimumWindowSubstring.java │ ├── MultiplyStrings.java │ ├── OneEditDistance.java │ ├── PalindromePermutation.java │ ├── PalindromicSubstrings.java │ ├── ReverseVowelsOfAString.java │ ├── ReverseWordsInAString.java │ ├── RomanToInteger.java │ ├── ValidPalindrome.java │ └── ValidParentheses.java ├── tree │ ├── BinaryTreeMaximumPathSum.java │ ├── BinaryTreePaths.java │ ├── InorderSuccessorInBST.java │ ├── InvertBinaryTree.java │ ├── LowestCommonAncestorOfABinaryTree.java │ ├── SumOfLeftLeaves.java │ ├── TrimABinarySearchTree.java │ └── ValidateBinarySearchTree.java ├── trie │ ├── AddAndSearchWordDataStructureDesign.java │ ├── ImplementTrie.java │ └── WordSquares.java └── two-pointers │ ├── 3Sum.java │ ├── 3SumSmaller.java │ ├── LinkedListCycle.java │ ├── MergeSortedArray.java │ ├── MinimumSizeSubarraySum.java │ ├── MoveZeros.java │ ├── RemoveDuplicatesFromSortedArray.java │ ├── RemoveElement.java │ ├── ReverseString.java │ └── SortColors.java ├── leetcode-part-3 ├── Company.iml ├── adobe │ ├── AddDigits.java │ └── MajorityElement.java ├── airbnb │ ├── AddTwoNumbers.java │ ├── ContainsDuplicate.java │ ├── ContainsDuplicatesII.java │ ├── ConvertSortedArrayToBinarySearchTree.java │ ├── HouseRobber.java │ ├── MergeKSortedLists.java │ ├── RegularExpressionMatching.java │ ├── TwoSum.java │ └── ValidParentheses.java ├── amazon │ ├── 3Sum.java │ ├── AddTwoNumbers.java │ ├── BestTimeToBuyAndSellStock.java │ ├── BinaryTreeLevelOrderTraversal.java │ ├── EncodeAndDecodeTinyURL.java │ ├── FirstUniqueCharacterInAString.java │ ├── GroupAnagrams.java │ ├── InsertDeleteGetRandomO1.java │ ├── KthLargestElementInAnArray.java │ ├── LetterCombinationsOfAPhoneNumber.java │ ├── LinkedListCycle.java │ ├── LongestPalindromicSubstring.java │ ├── LowestCommonAncestorOfABinaryTree.java │ ├── MergeKSortedLists.java │ ├── MinCostClimbingStairs.java │ ├── MinStack.java │ ├── NumberOfIslands.java │ ├── PalindromeLinkedList.java │ ├── ProductOfArrayExceptSelf.java │ ├── ReverseLinkedList.java │ ├── RotateImage.java │ ├── Subsets.java │ ├── TrappingRainWater.java │ ├── TwoSum.java │ ├── ValidParentheses.java │ ├── ValidateBinarySearchTree.java │ └── WordBreak.java ├── apple │ ├── ReverseWordsInAString.java │ └── ValidSudoku.java ├── bloomberg │ ├── FirstUniqueCharacterInAString.java │ ├── LinkedListCycle.java │ ├── LongestPalindromicSubstring.java │ ├── MinStack.java │ ├── ReverseWordsInAString.java │ └── UniquePaths.java ├── facebook │ ├── 3Sum.java │ ├── AddAndSearchWordDataStructureDesign.java │ ├── AddBinary.java │ ├── BestTimeToBuyAndSellStock.java │ ├── BinarySearchTreeIterator.java │ ├── BinaryTreeLevelOrderTraversal.java │ ├── BinaryTreePaths.java │ ├── BinaryTreeVerticalOrderTraversal.java │ ├── CloneGraph.java │ ├── CombinationSumIV.java │ ├── CountAndSay.java │ ├── DecodeWays.java │ ├── EncodeAndDecodeTinyURL.java │ ├── ExclusiveTimeOfFunctions.java │ ├── ExpressionAddOperators.java │ ├── FindTheCelebrity.java │ ├── FirstBadVersion.java │ ├── FlattenNestedListIterator.java │ ├── GroupAnagrams.java │ ├── HammingDistance.java │ ├── ImplementTrie.java │ ├── InorderSuccessorInBST.java │ ├── InsertDeleteGetRandomO1.java │ ├── InsertInterval.java │ ├── IntegerToEnglishWords.java │ ├── KthLargestElementInAnArray.java │ ├── LetterCombinationsOfAPhoneNumber.java │ ├── LongestConsecutiveSequence.java │ ├── LowestCommonAncestorOfABinaryTree.java │ ├── MaximumSizeSubarraySumEqualsK.java │ ├── MeetingRooms.java │ ├── MergeIntervals.java │ ├── MergeKSortedLists.java │ ├── MergeSortedArray.java │ ├── MinStack.java │ ├── MinimumSizeSubarraySum.java │ ├── MinimumWindowSubstring.java │ ├── MoveZeros.java │ ├── MultiplyStrings.java │ ├── NumberOfIslands.java │ ├── OneEditDistance.java │ ├── PaintHouseII.java │ ├── PalindromeLinkedList.java │ ├── PalindromicSubstrings.java │ ├── PowerOfXToTheN.java │ ├── ProductOfArrayExceptSelf.java │ ├── RegularExpressionMatching.java │ ├── RemoveDuplicatesFromSortedArray.java │ ├── RemoveInvalidParentheses.java │ ├── ReverseLinkedList.java │ ├── RomanToInteger.java │ ├── SearchInRotatedSortedArray.java │ ├── SortColors.java │ ├── SparseMatrixMultiplication.java │ ├── SquareRootX.java │ ├── Subsets.java │ ├── SubsetsII.java │ ├── SumOfLeftLeaves.java │ ├── TwoSum.java │ ├── ValidPalindrome.java │ ├── ValidParentheses.java │ ├── ValidateBinarySearchTree.java │ ├── WallsAndGates.java │ ├── WordBreak.java │ └── WordSearch.java ├── google │ ├── 3SumSmaller.java │ ├── AndroidUnlockPatterns.java │ ├── BinarySearchTreeIterator.java │ ├── BinaryTreePaths.java │ ├── BinaryTreeVerticalOrderTraversal.java │ ├── BinaryWatch.java │ ├── BombEnemy.java │ ├── BullsAndCows.java │ ├── CloneGraph.java │ ├── ClosestBinarySearchTreeValue.java │ ├── CombinationSumIV.java │ ├── DailyTemperatures.java │ ├── DecodeString.java │ ├── EncodeAndDecodeTinyURL.java │ ├── ExpressionAddOperators.java │ ├── FindAllNumbersDisappearedInAnArray.java │ ├── FindTheDifference.java │ ├── FirstUniqueCharacterInAString.java │ ├── FlattenNestedListIterator.java │ ├── GameOfLife.java │ ├── GeneralizedAbbreviation.java │ ├── GenerateParentheses.java │ ├── GroupShiftedStrings.java │ ├── GuessNumberHigherOrLower.java │ ├── ImplementTrie.java │ ├── InsertDeleteGetRandomO1.java │ ├── InsertInterval.java │ ├── IslandPerimeter.java │ ├── JudgeRouteCircle.java │ ├── LetterCombinationsOfAPhoneNumber.java │ ├── LoggerRateLimiter.java │ ├── LongestConsecutiveSequence.java │ ├── LongestSubstringWithAtMostKDistinctCharacters.java │ ├── MaximumProductOfWordLengths.java │ ├── MergeIntervals.java │ ├── MinStack.java │ ├── MissingRanges.java │ ├── MovingAverageFromDataStream.java │ ├── NumberOfIslands.java │ ├── PacificAtlanticWaterFlow.java │ ├── PaintFence.java │ ├── PlusOne.java │ ├── PlusOneLinkedList.java │ ├── PowerOfTwo.java │ ├── PowerOfXToTheN.java │ ├── RegularExpressionMatching.javaa │ ├── ReverseVowelsOfAString.java │ ├── SentenceScreenFitting.java │ ├── ShortestDistanceFromAllBuildings.java │ ├── SpiralMatrix.java │ ├── StrobogrammaticNumber.java │ ├── SummaryRanges.java │ ├── TrappingRainWater.java │ ├── UniqueWordAbbreviation.java │ ├── Utf8Validation.java │ ├── ValidParentheses.java │ ├── WallsAndGates.java │ ├── WiggleSort.java │ ├── WordBreak.java │ ├── WordSquares.java │ └── ZigZagIterator.java ├── linkedin │ ├── BinarySearchTreeIterator.java │ ├── BinaryTreeLevelOrderTraversal.java │ ├── FindTheCelebrity.java │ ├── HouseRobber.java │ ├── InsertInterval.java │ ├── LowestCommonAncestorOfABinaryTree.java │ ├── MaximumDepthOfABinaryTree.java │ ├── MaximumProductSubarray.java │ ├── MaximumSubarray.java │ ├── MergeIntervals.java │ ├── MergeKSortedLists.java │ ├── MinimumWindowSubstring.java │ ├── PaintHouse.java │ ├── PalindromicSubstrings.java │ ├── Permutations.java │ ├── PowerOfXToTheN.java │ ├── ProductOfArrayExceptSelf.java │ ├── SearchInRotatedSortedArray.java │ ├── SparseMatrixMultiplication.java │ ├── SymmetricTree.java │ └── TwoSum.java ├── microsoft │ ├── AddDigits.java │ ├── FirstUniqueCharacterInAString.java │ ├── HouseRobberII.java │ ├── LinkedListCycle.java │ ├── LongestIncreasingSubsequence.java │ ├── LongestPalindromicSubstring.java │ ├── Permutations.java │ ├── ReverseWordsInAString.java │ └── SpiralMatrix.java ├── palantir │ ├── ContainsDuplicate.java │ └── ContainsDuplicatesII.java ├── snapchat │ ├── MinStack.java │ ├── ReverseWordsInAString.java │ └── ValidSudoku.java ├── twitter │ ├── FlattenNestedListIterator.java │ ├── ImplementTrie.java │ ├── InsertDeleteGetRandomO1.java │ ├── LowestCommonAncestorOfABinaryTree.java │ ├── MergeIntervals.java │ ├── MergeKSortedLists.java │ ├── MultiplyStrings.java │ ├── OneEditDistance.java │ ├── RegularExpressionMatching.java │ ├── ReverseLinkedList.java │ ├── TrappingRainWater.java │ └── ValidParentheses.java ├── uber │ ├── BestTimeToBuyOrSellStock.java │ ├── CloneGraph.java │ ├── DecodeWays.java │ ├── EncodeAndDecodeTinyURL.java │ ├── ExclusiveTimeOfFunctions.java │ ├── GenerateParentheses.java │ ├── GroupAnagrams.java │ ├── GroupShiftedStrings.java │ ├── ImplementTrie.java │ ├── InsertDeleteGetRandomO1.java │ ├── LetterCombinationsOfAPhoneNumber.java │ ├── MaximumDepthOfABinaryTree.java │ ├── MergeKSortedLists.java │ ├── MinStack.java │ ├── MinimumWindowSubstring.java │ ├── OneEditDistance.java │ ├── PalindromePermutation.java │ ├── RegularExpressionMatching.java │ ├── ReverseLinkedList.java │ ├── RomanToInteger.java │ ├── SearchInRotatedSortedArray.java │ ├── SpiralMatrix.java │ ├── Subsets.java │ ├── TwoSum.java │ ├── ValidPalindrome.java │ ├── ValidSudoku.java │ └── WordBreak.java ├── yahoo │ ├── ContainsDuplicate.java │ └── LinkedListCycle.java └── yelp │ ├── InsertDeleteGetRandomO1.java │ └── ReverseWordsInAString.java ├── leetcode ├── README.md ├── algorithms │ ├── cpp │ │ ├── 3Sum │ │ │ └── 3Sum.cpp │ │ ├── 3SumClosest │ │ │ └── 3SumClosest.cpp │ │ ├── 4Sum │ │ │ └── 4Sum.cpp │ │ ├── FindValidMatrixGivenRowAndColumnSums │ │ │ └── FindValidMatrixGivenRowAndColumnSums.cpp │ │ ├── LRUCache │ │ │ └── LRUCache.cpp │ │ ├── NumberOfWaysToSplitString │ │ │ └── NumberOfWaysToSplitString.cpp │ │ ├── UTF8Validation │ │ │ └── UTF8Validation.cpp │ │ ├── accountsMerge │ │ │ └── AccountsMerge.cpp │ │ ├── addAndSearchWord │ │ │ └── AddAndSearchWord.cpp │ │ ├── addBinary │ │ │ └── addBinary.cpp │ │ ├── addDigits │ │ │ └── addDigits.cpp │ │ ├── addStrings │ │ │ └── AddStrings.cpp │ │ ├── addToArrayFormOfInteger │ │ │ └── AddToArrayFormOfInteger.cpp │ │ ├── addTwoNumbers │ │ │ └── addTwoNumbers.cpp │ │ ├── additiveNumber │ │ │ └── AdditiveNumber.cpp │ │ ├── anagrams │ │ │ ├── GroupAnagrams.cpp │ │ │ └── ValidAnagram.cpp │ │ ├── arithmeticSlices │ │ │ └── ArithmeticSlices.cpp │ │ ├── backspaceStringCompare │ │ │ └── BackspaceStringCompare.cpp │ │ ├── balancedBinaryTree │ │ │ └── balancedBinaryTree.cpp │ │ ├── basicCalculator │ │ │ ├── BasicCalculator.II.cpp │ │ │ └── BasicCalculator.cpp │ │ ├── bestTimeToBuyAndSellStock │ │ │ ├── BestTimeToBuyAndSellStockWithCooldown.cpp │ │ │ ├── BestTimeToBuyAndSellStockWithTransactionFee.cpp │ │ │ ├── bestTimeToBuyAndSellStock.II.cpp │ │ │ ├── bestTimeToBuyAndSellStock.III.cpp │ │ │ ├── bestTimeToBuyAndSellStock.IV.cpp │ │ │ └── bestTimeToBuyAndSellStock.cpp │ │ ├── binarySearchTreeIterator │ │ │ └── binarySearchTreeIterator.cpp │ │ ├── binaryTreeInorderTraversal │ │ │ └── binaryTreeInorderTraversal.cpp │ │ ├── binaryTreeLevelOrderTraversal │ │ │ ├── binaryTreeLevelOrderTraversal.II.cpp │ │ │ └── binaryTreeLevelOrderTraversal.cpp │ │ ├── binaryTreeMaximumPathSum │ │ │ └── binaryTreeMaximumPathSum.cpp │ │ ├── binaryTreePaths │ │ │ └── binaryTreePaths.cpp │ │ ├── binaryTreePostorderTraversal │ │ │ └── binaryTreePostorderTraversal.cpp │ │ ├── binaryTreePreorderTraversal │ │ │ └── binaryTreePreorderTraversal.cpp │ │ ├── binaryTreeRightSideView │ │ │ └── binaryTreeRightSideView.cpp │ │ ├── binaryTreeUpsideDown │ │ │ └── binaryTreeUpsideDown.cpp │ │ ├── binaryTreeZigzagLevelOrderTraversal │ │ │ └── binaryTreeZigzagLevelOrderTraversal.cpp │ │ ├── binaryWatch │ │ │ └── BinaryWatch.cpp │ │ ├── bitwiseANDOfNumbersRange │ │ │ └── BitwiseAndOfNumbersRange.cpp │ │ ├── brokenCalculator │ │ │ └── BrokenCalculator.cpp │ │ ├── buddyStrings │ │ │ └── BuddyStrings.cpp │ │ ├── buildingBoxes │ │ │ └── BuildingBoxes.cpp │ │ ├── bulbSwitcher │ │ │ ├── BulbSwitcher.II.cpp │ │ │ ├── BulbSwitcher.III.cpp │ │ │ ├── BulbSwitcher.IV.cpp │ │ │ └── bulbSwitcher.cpp │ │ ├── bullsAndCows │ │ │ └── bullsAndCows.cpp │ │ ├── burstBalloons │ │ │ └── BurstBalloons.cpp │ │ ├── calculateMoneyInLeetcodeBank │ │ │ └── CalculateMoneyInLeetcodeBank.cpp │ │ ├── candy │ │ │ └── candy.cpp │ │ ├── checkIfArrayIsSortedAndRotated │ │ │ └── CheckIfArrayIsSortedAndRotated.cpp │ │ ├── checkIfBinaryStringHasAtMostOneSegmentOfOnes │ │ │ └── CheckIfBinaryStringHasAtMostOneSegmentOfOnes.cpp │ │ ├── checkIfNumberIsASumOfPowersOfThree │ │ │ └── CheckIfNumberIsASumOfPowersOfThree.cpp │ │ ├── checkIfOneStringSwapCanMakeStringsEqual │ │ │ └── CheckIfOneStringSwapCanMakeStringsEqual.cpp │ │ ├── checkIfTheSentenceIsPangram │ │ │ └── CheckIfTheSentenceIsPangram.cpp │ │ ├── checkIfWordEqualsSummationOfTwoWords │ │ │ └── CheckIfWordEqualsSummationOfTwoWords.cpp │ │ ├── climbStairs │ │ │ └── climbStairs.cpp │ │ ├── cloneGraph │ │ │ └── cloneGraph.cpp │ │ ├── closestDessertCost │ │ │ └── ClosestDessertCost.cpp │ │ ├── closestRoom │ │ │ └── ClosestRoom.cpp │ │ ├── closestSubsequenceSum │ │ │ └── ClosestSubsequenceSum.cpp │ │ ├── coinChange │ │ │ ├── CoinChange2.cpp │ │ │ └── coinChange.cpp │ │ ├── combinationSum │ │ │ ├── combinationSum.II.cpp │ │ │ ├── combinationSum.III.cpp │ │ │ └── combinationSum.cpp │ │ ├── combinationSumIV │ │ │ └── combinationSumIV.cpp │ │ ├── combinations │ │ │ └── combinations.cpp │ │ ├── compareStringsByFrequencyOfTheSmallestCharacter │ │ │ └── CompareStringsByFrequencyOfTheSmallestCharacter.cpp │ │ ├── compareVersionNumbers │ │ │ └── compareVersionNumbers.cpp │ │ ├── constructBinaryTreeFromInorderAndPostorderTraversal │ │ │ └── constructBinaryTreeFromInorderAndPostorderTraversal.cpp │ │ ├── constructBinaryTreeFromPreorderAndInorderTraversal │ │ │ └── constructBinaryTreeFromPreorderAndInorderTraversal.cpp │ │ ├── constructTheLexicographicallyLargestValidSequence │ │ │ └── ConstructTheLexicographicallyLargestValidSequence.cpp │ │ ├── containerWithMostWater │ │ │ └── containerWithMostWater.cpp │ │ ├── containsDuplicate │ │ │ ├── ContainsDuplicate.II.cpp │ │ │ ├── ContainsDuplicate.III.cpp │ │ │ └── ContainsDuplicate.cpp │ │ ├── convertANumberToHexadecimal │ │ │ └── ConvertANumberToHexadecimal.cpp │ │ ├── convertSortedArrayToBinarySearchTree │ │ │ └── convertSortedArrayToBinarySearchTree.cpp │ │ ├── convertSortedListToBinarySearchTree │ │ │ └── convertSortedListToBinarySearchTree.cpp │ │ ├── copyListWithRandomPointer │ │ │ └── copyListWithRandomPointer.cpp │ │ ├── countAndSay │ │ │ └── countAndSay.cpp │ │ ├── countCompleteTreeNodes │ │ │ └── CountCompleteTreeNodes.cpp │ │ ├── countGoodMeals │ │ │ └── CountGoodMeals.cpp │ │ ├── countItemsMatchingARule │ │ │ └── CountItemsMatchingARule.cpp │ │ ├── countNicePairsInAnArray │ │ │ └── CountNicePairsInAnArray.cpp │ │ ├── countNumberOfHomogenousSubstrings │ │ │ └── CountNumberOfHomogenousSubstrings.cpp │ │ ├── countNumbersWithUniqueDigits │ │ │ └── CountNumbersWithUniqueDigits.cpp │ │ ├── countOddNumbersInAnIntervalRange │ │ │ └── CountOddNumbersInAnIntervalRange.cpp │ │ ├── countOfRangeSum │ │ │ └── CountOfRangeSum.cpp │ │ ├── countOfSmallerNumbersAfterSelf │ │ │ └── countOfSmallerNumbersAfterSelf.cpp │ │ ├── countPairsOfNodes │ │ │ └── CountPairsOfNodes.cpp │ │ ├── countPairsWithXorInARange │ │ │ └── CountPairsWithXorInARange.cpp │ │ ├── countPrimes │ │ │ └── CountPrimes.cpp │ │ ├── countingBits │ │ │ └── CountingBits.cpp │ │ ├── courseSchedule │ │ │ ├── CourseSchedule.II.cpp │ │ │ ├── CourseSchedule.cpp │ │ │ └── non-recursive │ │ │ │ ├── course_schedule.cpp │ │ │ │ └── main.cpp │ │ ├── cousinsInBinaryTree │ │ │ └── CousinsInBinaryTree.cpp │ │ ├── createMaximumNumber │ │ │ └── CreateMaximumNumber.cpp │ │ ├── decodeString │ │ │ └── DecodeString.cpp │ │ ├── decodeWays │ │ │ └── decodeWays.cpp │ │ ├── decodeXORedPermutation │ │ │ └── DecodeXoredPermutation.cpp │ │ ├── deleteNodeInALinkedList │ │ │ └── DeleteNodeInALinkedList.cpp │ │ ├── designAuthenticationManager │ │ │ └── DesignAuthenticationManager.cpp │ │ ├── detectCapital │ │ │ └── DetectCapital.cpp │ │ ├── determineColorOfAChessboardSquare │ │ │ └── DetermineColorOfAChessboardSquare.cpp │ │ ├── diameterOfBinaryTree │ │ │ └── diameterOfBinaryTree.cpp │ │ ├── differentWaysToAddParentheses │ │ │ └── DifferentWaysToAddParentheses.cpp │ │ ├── distinctSubsequences │ │ │ └── distinctSubsequences.cpp │ │ ├── distributeCoinsInBinaryTree │ │ │ └── DistributeCoinsInBinaryTree.cpp │ │ ├── divideTwoInt │ │ │ └── divideTwoInt.cpp │ │ ├── dungeonGame │ │ │ └── dungeonGame.cpp │ │ ├── editDistance │ │ │ └── editDistance.cpp │ │ ├── eggDropWith2EggsAndNFloors │ │ │ └── EggDropWith2EggsAndNFloors.cpp │ │ ├── eliminationGame │ │ │ └── EliminationGame.cpp │ │ ├── equalSumArraysWithMinimumNumberOfOperations │ │ │ └── EqualSumArraysWithMinimumNumberOfOperations.cpp │ │ ├── evaluateDivision │ │ │ └── EvaluateDivision.cpp │ │ ├── evaluateReversePolishNotation │ │ │ └── evaluateReversePolishNotation.cpp │ │ ├── evaluateTheBracketPairsOfAString │ │ │ └── EvaluateTheBracketPairsOfAString.cpp │ │ ├── excelSheetColumnNumber │ │ │ └── excelSheetColumnNumber.cpp │ │ ├── excelSheetColumnTitle │ │ │ └── excelSheetColumnTitle.cpp │ │ ├── expressionAddOperators │ │ │ └── ExpressionAddOperators.cpp │ │ ├── factorialTrailingZeroes │ │ │ └── factorialTrailingZeroes.cpp │ │ ├── fibonacciNumber │ │ │ └── FibonacciNumber.cpp │ │ ├── filterRestaurantsByVeganFriendlyPriceAndDistance │ │ │ └── FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp │ │ ├── findAllAnagramsInAString │ │ │ └── Find-All-Anagrams-in-a-String.cpp │ │ ├── findCenterOfStarGraph │ │ │ └── FindCenterOfStarGraph.cpp │ │ ├── findKthLargestXorCoordinateValue │ │ │ └── FindKthLargestXorCoordinateValue.cpp │ │ ├── findMedianFromDataStream │ │ │ └── FindMedianFromDataStream.cpp │ │ ├── findMinimumInRotatedSortedArray │ │ │ ├── findMinimumInRotatedSortedArray.II.cpp │ │ │ └── findMinimumInRotatedSortedArray.cpp │ │ ├── findNearestPointThatHasTheSameXOrYCoordinate │ │ │ └── FindNearestPointThatHasTheSameXOrYCoordinate.cpp │ │ ├── findPeakElement │ │ │ └── findPeakElement.cpp │ │ ├── findTheDifference │ │ │ └── FindTheDifference.cpp │ │ ├── findTheDuplicateNumber │ │ │ └── findTheDuplicateNumber.cpp │ │ ├── findTheHighestAltitude │ │ │ └── FindTheHighestAltitude.cpp │ │ ├── findTheWinnerOfAnArrayGame │ │ │ └── FindTheWinnerOfAnArrayGame.cpp │ │ ├── findTheWinnerOfTheCircularGame │ │ │ └── FindTheWinnerOfTheCircularGame.cpp │ │ ├── findXorSumOfAllPairsBitwiseAnd │ │ │ └── FindXorSumOfAllPairsBitwiseAnd.cpp │ │ ├── findingMkAverage │ │ │ └── FindingMkAverage.cpp │ │ ├── findingTheUsersActiveMinutes │ │ │ └── FindingTheUsersActiveMinutes.cpp │ │ ├── firstBadVersion │ │ │ └── FirstBadVersion.cpp │ │ ├── firstMissingPositive │ │ │ └── firstMissingPositive.cpp │ │ ├── firstUniqueCharacterInAString │ │ │ └── FirstUniqueCharacterInAString.cpp │ │ ├── fizzBuzz │ │ │ └── FizzBuzz.cpp │ │ ├── flattenBinaryTreeToLinkedList │ │ │ └── flattenBinaryTreeToLinkedList.cpp │ │ ├── flattenNestedListIterator │ │ │ └── FlattenNestedListIterator.cpp │ │ ├── formArrayByConcatenatingSubarraysOfAnotherArray │ │ │ └── FormArrayByConcatenatingSubarraysOfAnotherArray.cpp │ │ ├── fractionToRecurringDecimal │ │ │ └── fractionToRecurringDecimal.cpp │ │ ├── frequencyOfTheMostFrequentElement │ │ │ └── FrequencyOfTheMostFrequentElement.cpp │ │ ├── friendCircles │ │ │ └── FriendCircles.cpp │ │ ├── frogJump │ │ │ └── FrogJump.cpp │ │ ├── gameOfLife │ │ │ └── GameOfLife.cpp │ │ ├── gasStation │ │ │ └── gasStation.cpp │ │ ├── generateParentheses │ │ │ └── generateParentheses.cpp │ │ ├── grayCode │ │ │ └── grayCode.cpp │ │ ├── greatestCommonDivisorOfStrings │ │ │ └── GreatestCommonDivisorOfStrings.cpp │ │ ├── h-Index │ │ │ ├── h-Index.II.cpp │ │ │ └── h-Index.cpp │ │ ├── happyNumber │ │ │ └── HappyNumber.cpp │ │ ├── houseRobber │ │ │ ├── houseRobber.II.cpp │ │ │ ├── houseRobber.cpp │ │ │ └── houseRobberIII.cpp │ │ ├── implementQueueUsingStacks │ │ │ └── ImplementQueueUsingStacks.cpp │ │ ├── implementStackUsingQueues │ │ │ └── ImplementStackUsingQueues.cpp │ │ ├── implementTriePrefixTree │ │ │ └── ImplementTriePrefixTree.cpp │ │ ├── increasingTripletSubsequence │ │ │ └── increasingTripletSubsequence.cpp │ │ ├── incrementalMemoryLeak │ │ │ └── IncrementalMemoryLeak.cpp │ │ ├── insertDeleteGetRandom │ │ │ ├── InsertDeleteGetrandomO1.cpp │ │ │ └── InsertDeleteGetrandomO1DuplicatesAllowed.cpp │ │ ├── insertInterval │ │ │ └── insertInterval.cpp │ │ ├── insertionSortList │ │ │ └── insertionSortList.cpp │ │ ├── integerBreak │ │ │ └── IntegerBreak.cpp │ │ ├── integerReplacement │ │ │ └── IntegerReplacement.cpp │ │ ├── integerToEnglishWords │ │ │ └── IntegerToEnglishWords.cpp │ │ ├── integerToRoman │ │ │ └── integerToRoman.cpp │ │ ├── interleavingString │ │ │ └── interleavingString.cpp │ │ ├── intersectionOfTwoArrays │ │ │ ├── intersectionOfTwoArrays.cpp │ │ │ └── intersectionOfTwoArraysII.cpp │ │ ├── intersectionOfTwoLinkedLists │ │ │ └── intersectionOfTwoLinkedLists.cpp │ │ ├── intervalListIntersectons │ │ │ └── IntervalListIntersections.cpp │ │ ├── invertBinaryTree │ │ │ └── InvertBinaryTree.cpp │ │ ├── isSubsequence │ │ │ └── IsSubsequence.cpp │ │ ├── islandPerimeter │ │ │ └── IslandPerimeter.cpp │ │ ├── isomorphicStrings │ │ │ └── IsomorphicStrings.cpp │ │ ├── jewelsAndStones │ │ │ └── JewelsAndStones.cpp │ │ ├── jumpGame │ │ │ ├── jumpGame.II.cpp │ │ │ ├── jumpGame.VII.cpp │ │ │ └── jumpGame.cpp │ │ ├── kthLargestElementInAnArray │ │ │ └── KthLargestElementInAnArray.cpp │ │ ├── kthSmallestElementInaBST │ │ │ └── KthSmallestElementInABst.cpp │ │ ├── largestColorValueInADirectedGraph │ │ │ └── LargestColorValueInADirectedGraph.cpp │ │ ├── largestMergeOfTwoStrings │ │ │ └── LargestMergeOfTwoStrings.cpp │ │ ├── largestNumber │ │ │ └── largestNumber.cpp │ │ ├── largestNumberAfterMutatingSubstring │ │ │ └── LargestNumberAfterMutatingSubstring.cpp │ │ ├── largestPerimeterTriangle │ │ │ └── largestPerimeterTriangle.cpp │ │ ├── largestRectangleInHistogram │ │ │ └── largestRectangleInHistogram.cpp │ │ ├── largestSubmatrixWithRearrangements │ │ │ └── LargestSubmatrixWithRearrangements.cpp │ │ ├── largestSubstringBetweenTwoEqualCharacters │ │ │ └── LargestSubstringBetweenTwoEqualCharacters.cpp │ │ ├── latestTimeByReplacingHiddenDigits │ │ │ └── LatestTimeByReplacingHiddenDigits.cpp │ │ ├── lengthOfLastWord │ │ │ └── lengthOfLastWord.cpp │ │ ├── letterCombinationsOfAPhoneNumber │ │ │ └── letterCombinationsOfAPhoneNumber.cpp │ │ ├── lexicographicalNumbers │ │ │ └── LexicographicalNumbers.cpp │ │ ├── lexicographicallySmallestStringAfterApplyingOperations │ │ │ └── LexicographicallySmallestStringAfterApplyingOperations.cpp │ │ ├── linkedListCycle │ │ │ ├── linkedListCycle.II.cpp │ │ │ └── linkedListCycle.cpp │ │ ├── linkedListRandomNode │ │ │ └── LinkedListRandomNode.cpp │ │ ├── longerContiguousSegmentsOfOnesThanZeros │ │ │ └── LongerContiguousSegmentsOfOnesThanZeros.cpp │ │ ├── longestAbsoluteFilePath │ │ │ └── LongestAbsoluteFilePath.cpp │ │ ├── longestCommonPrefix │ │ │ └── longestCommonPrefix.cpp │ │ ├── longestConsecutiveSequence │ │ │ └── longestConsecutiveSequence.cpp │ │ ├── longestIncreasingPathInAMatrix │ │ │ └── LongestIncreasingPathInAMatrix.cpp │ │ ├── longestIncreasingSubsequence │ │ │ └── longestIncreasingSubsequence.cpp │ │ ├── longestNiceSubstring │ │ │ └── LongestNiceSubstring.cpp │ │ ├── longestPalindrome │ │ │ └── LongestPalindrome.cpp │ │ ├── longestPalindromicSubsequence │ │ │ └── LongestPalindromicSubsequence.cpp │ │ ├── longestPalindromicSubstring │ │ │ └── longestPalindromicSubstring.cpp │ │ ├── longestSubstringOfAllVowelsInOrder │ │ │ └── LongestSubstringOfAllVowelsInOrder.cpp │ │ ├── longestSubstringWithAtLeastKRepeatingCharacters │ │ │ └── LongestSubstringWithAtLeastKRepeatingCharacters.cpp │ │ ├── longestSubstringWithAtMostTwoDistinctCharacters │ │ │ └── longestSubstringWithAtMostTwoDistinctCharacters.cpp │ │ ├── longestSubstringWithoutRepeatingCharacters │ │ │ └── longestSubstringWithoutRepeatingCharacters.cpp │ │ ├── longestTurbulentSubarray │ │ │ └── LongestTurbulentSubarray.cpp │ │ ├── longestValidParentheses │ │ │ └── longestValidParentheses.cpp │ │ ├── lowestCommonAncestorOfABinarySearchTree │ │ │ └── LowestCommonAncestorOfABinarySearchTree.cpp │ │ ├── lowestCommonAncestorOfABinaryTree │ │ │ └── LowestCommonAncestorOfABinaryTree.cpp │ │ ├── majorityElement │ │ │ ├── majorityElement.II.cpp │ │ │ └── majorityElement.cpp │ │ ├── makeTheXorOfAllSegmentsEqualToZero │ │ │ └── MakeTheXorOfAllSegmentsEqualToZero.cpp │ │ ├── mapOfHighestPeak │ │ │ └── MapOfHighestPeak.cpp │ │ ├── matrixCellsInDistanceOrder │ │ │ └── MatrixCellsInDistanceOrder.cpp │ │ ├── maxAreaOfIsland │ │ │ └── MaxAreaOfIsland.cpp │ │ ├── maxPointsOnALine │ │ │ └── maxPointsOnALine.cpp │ │ ├── maximalRectangle │ │ │ └── maximalRectangle.cpp │ │ ├── maximalSquare │ │ │ └── MaximalSquare.cpp │ │ ├── maximizeNumberOfNiceDivisors │ │ │ └── MaximizeNumberOfNiceDivisors.cpp │ │ ├── maximizePalindromeLengthFromSubsequences │ │ │ └── MaximizePalindromeLengthFromSubsequences.cpp │ │ ├── maximizeScoreAfterNOperations │ │ │ └── MaximizeScoreAfterNOperations.cpp │ │ ├── maximumAbsoluteSumOfAnySubarray │ │ │ └── MaximumAbsoluteSumOfAnySubarray.cpp │ │ ├── maximumAscendingSubarraySum │ │ │ └── MaximumAscendingSubarraySum.cpp │ │ ├── maximumAveragePassRatio │ │ │ └── MaximumAveragePassRatio.cpp │ │ ├── maximumAverageSubarray │ │ │ └── MaximumAverageSubarray.I.cpp │ │ ├── maximumBuildingHeight │ │ │ └── MaximumBuildingHeight.cpp │ │ ├── maximumDepthOfBinaryTree │ │ │ └── maximumDepthOfBinaryTree.cpp │ │ ├── maximumDistanceBetweenAPairOfValues │ │ │ └── MaximumDistanceBetweenAPairOfValues.cpp │ │ ├── maximumElementAfterDecreasingAndRearranging │ │ │ └── MaximumElementAfterDecreasingAndRearranging.cpp │ │ ├── maximumErasureValue │ │ │ └── MaximumErasureValue.cpp │ │ ├── maximumGap │ │ │ └── maximumGap.cpp │ │ ├── maximumIceCreamBars │ │ │ └── MaximumIceCreamBars.cpp │ │ ├── maximumNumberOfBallsInABox │ │ │ └── MaximumNumberOfBallsInABox.cpp │ │ ├── maximumNumberOfConsecutiveValuesYouCanMake │ │ │ └── MaximumNumberOfConsecutiveValuesYouCanMake.cpp │ │ ├── maximumNumberOfEventsThatCanBeAttended │ │ │ ├── MaximumNumberOfEventsThatCanBeAttended.II.cpp │ │ │ └── MaximumNumberOfEventsThatCanBeAttended.cpp │ │ ├── maximumNumberOfGroupsGettingFreshDonuts │ │ │ └── MaximumNumberOfGroupsGettingFreshDonuts.cpp │ │ ├── maximumNumberOfWordsYouCanType │ │ │ └── MaximumNumberOfWordsYouCanType.cpp │ │ ├── maximumPopulationYear │ │ │ └── MaximumPopulationYear.cpp │ │ ├── maximumProductOfTwoElementsInAnArray │ │ │ └── MaximumProductOfTwoElementsInAnArray.cpp │ │ ├── maximumProductOfWordLengths │ │ │ └── MaximumProductOfWordLengths.cpp │ │ ├── maximumProductSubarray │ │ │ └── maximumProductSubarray.cpp │ │ ├── maximumScoreFromPerformingMultiplicationOperations │ │ │ └── MaximumScoreFromPerformingMultiplicationOperations.cpp │ │ ├── maximumScoreFromRemovingStones │ │ │ └── MaximumScoreFromRemovingStones.cpp │ │ ├── maximumScoreFromRemovingSubstrings │ │ │ └── MaximumScoreFromRemovingSubstrings.cpp │ │ ├── maximumScoreOfAGoodSubarray │ │ │ └── MaximumScoreOfAGoodSubarray.cpp │ │ ├── maximumSubArray │ │ │ └── maximumSubArray.cpp │ │ ├── maximumSubarrayMinProduct │ │ │ └── MaximumSubarrayMinProduct.cpp │ │ ├── maximumUnitsOnATruck │ │ │ └── MaximumUnitsOnATruck.cpp │ │ ├── maximumValueAfterInsertion │ │ │ └── MaximumValueAfterInsertion.cpp │ │ ├── maximumValueAtAGivenIndexInABoundedArray │ │ │ └── MaximumValueAtAGivenIndexInABoundedArray.cpp │ │ ├── maximumXorForEachQuery │ │ │ └── MaximumXorForEachQuery.cpp │ │ ├── medianOfTwoSortedArrays │ │ │ └── medianOfTwoSortedArrays.cpp │ │ ├── mergeIntervals │ │ │ └── mergeIntervals.cpp │ │ ├── mergeKSortedLists │ │ │ └── mergeKSortedLists.cpp │ │ ├── mergeStringsAlternately │ │ │ └── MergeStringsAlternately.cpp │ │ ├── mergeTwoSortedArray │ │ │ └── mergeTwoSortedArray.cpp │ │ ├── mergeTwoSortedList │ │ │ └── mergeTwoSortedList.cpp │ │ ├── minCostClimbingStairs │ │ │ └── MinCostClimbingStairs.cpp │ │ ├── minStack │ │ │ └── minStack.cpp │ │ ├── miniParser │ │ │ └── MiniParser.cpp │ │ ├── minimizeMaximumPairSumInArray │ │ │ └── MinimizeMaximumPairSumInArray.cpp │ │ ├── minimumASCIIDeleteSumForTwoStrings │ │ │ └── MinimumAsciiDeleteSumForTwoStrings.cpp │ │ ├── minimumAbsoluteSumDifference │ │ │ └── MinimumAbsoluteSumDifference.cpp │ │ ├── minimumAdjacentSwapsToReachTheKthSmallestNumber │ │ │ └── MinimumAdjacentSwapsToReachTheKthSmallestNumber.cpp │ │ ├── minimumChangesToMakeAlternatingBinaryString │ │ │ └── MinimumChangesToMakeAlternatingBinaryString.cpp │ │ ├── minimumCostForTickets │ │ │ └── MinimumCostForTickets.cpp │ │ ├── minimumDegreeOfAConnectedTrioInAGraph │ │ │ └── MinimumDegreeOfAConnectedTrioInAGraph.cpp │ │ ├── minimumDepthOfBinaryTree │ │ │ └── minimumDepthOfBinaryTree.cpp │ │ ├── minimumDistanceToTheTargetElement │ │ │ └── MinimumDistanceToTheTargetElement.cpp │ │ ├── minimumElementsToAddToFormAGivenSum │ │ │ └── MinimumElementsToAddToFormAGivenSum.cpp │ │ ├── minimumFallingPathSum │ │ │ └── MinimumFallingPathSum.cpp │ │ ├── minimumHeightTrees │ │ │ └── MinimumHeightTrees.cpp │ │ ├── minimumInsertionsToBalanceAParenthesesString │ │ │ └── MinimumInsertionsToBalanceAParenthesesString.cpp │ │ ├── minimumIntervalToIncludeEachQuery │ │ │ └── MinimumIntervalToIncludeEachQuery.cpp │ │ ├── minimumLengthOfStringAfterDeletingSimilarEnds │ │ │ └── MinimumLengthOfStringAfterDeletingSimilarEnds.cpp │ │ ├── minimumLimitOfBallsInABag │ │ │ └── MinimumLimitOfBallsInABag.cpp │ │ ├── minimumNumberOfOperationsToMoveAllBallsToEachBox │ │ │ └── MinimumNumberOfOperationsToMoveAllBallsToEachBox.cpp │ │ ├── minimumNumberOfOperationsToReinitializeAPermutation │ │ │ └── MinimumNumberOfOperationsToReinitializeAPermutation.cpp │ │ ├── minimumNumberOfPeopleToTeach │ │ │ └── MinimumNumberOfPeopleToTeach.cpp │ │ ├── minimumOperationsToMakeArrayEqual │ │ │ └── MinimumOperationsToMakeArrayEqual.cpp │ │ ├── minimumOperationsToMakeTheArrayIncreasing │ │ │ └── MinimumOperationsToMakeTheArrayIncreasing.cpp │ │ ├── minimumPathSum │ │ │ └── minimumPathSum.cpp │ │ ├── minimumSidewayJumps │ │ │ └── MinimumSidewayJumps.cpp │ │ ├── minimumSizeSubarraySum │ │ │ └── MinimumSizeSubarraySum.cpp │ │ ├── minimumSpeedToArriveOnTime │ │ │ └── MinimumSpeedToArriveOnTime.cpp │ │ ├── minimumWindowSubstring │ │ │ └── minimumWindowSubstring.cpp │ │ ├── mirrorReflection │ │ │ └── MirrorReflection.cpp │ │ ├── missingNumber │ │ │ └── MissingNumber.cpp │ │ ├── missingRanges │ │ │ └── missingRanges.cpp │ │ ├── mostCommonWord │ │ │ └── MostCommonWord.cpp │ │ ├── moveZeroes │ │ │ └── moveZeroes.cpp │ │ ├── multiplyStrings │ │ │ └── multiplyStrings.cpp │ │ ├── nQueens │ │ │ ├── nQueuens.II.cpp │ │ │ └── nQueuens.cpp │ │ ├── nRepeatedElementInSize2NArray │ │ │ └── N-Repeated-Element-in-Size-2N-Array.cpp │ │ ├── nextPermutation │ │ │ └── nextPermutation.cpp │ │ ├── nimGame │ │ │ └── nimGame.cpp │ │ ├── nthDigit │ │ │ └── NthDigit.cpp │ │ ├── numberOf1Bits │ │ │ └── numberOf1Bits.cpp │ │ ├── numberOfDifferentIntegersInAString │ │ │ └── NumberOfDifferentIntegersInAString.cpp │ │ ├── numberOfDifferentSubsequencesGcds │ │ │ └── NumberOfDifferentSubsequencesGcds.cpp │ │ ├── numberOfDigitOne │ │ │ └── NumberOfDigitOne.cpp │ │ ├── numberOfGoodWaysToSplitAString │ │ │ └── NumberOfGoodWaysToSplitAString.cpp │ │ ├── numberOfIslands │ │ │ └── NumberOfIslands.cpp │ │ ├── numberOfOrdersInTheBacklog │ │ │ └── NumberOfOrdersInTheBacklog.cpp │ │ ├── numberOfRecentCalls │ │ │ └── NumberOfRecentCalls.cpp │ │ ├── numberOfRectanglesThatCanFormTheLargestSquare │ │ │ └── NumberOfRectanglesThatCanFormTheLargestSquare.cpp │ │ ├── numberOfRestrictedPathsFromFirstToLastNode │ │ │ └── NumberOfRestrictedPathsFromFirstToLastNode.cpp │ │ ├── numberOfStudentsUnableToEatLunch │ │ │ └── NumberOfStudentsUnableToEatLunch.cpp │ │ ├── numberOfSubArraysWithOddSum │ │ │ └── NumberOfSubArraysWithOddSum.cpp │ │ ├── numberOfSubstringsWithOnly1s │ │ │ └── NumberOfSubstringsWithOnly1s.cpp │ │ ├── oddEvenLinkedList │ │ │ └── OddEvenLinkedList.cpp │ │ ├── oneEditDistance │ │ │ └── oneEditDistance.cpp │ │ ├── palindromeLinkedList │ │ │ └── PalindromeLinkedList.cpp │ │ ├── palindromeNumber │ │ │ └── palindromeNumber.cpp │ │ ├── palindromePairs │ │ │ └── PalindromePairs.cpp │ │ ├── palindromePartitioning │ │ │ ├── palindromePartitioning.II.cpp │ │ │ └── palindromePartitioning.cpp │ │ ├── palindromicSubstrings │ │ │ └── PalindromicSubstrings.cpp │ │ ├── partitionEqualSubsetSum │ │ │ └── PartitionEqualSubsetSum.cpp │ │ ├── partitionList │ │ │ └── partitionList.cpp │ │ ├── pascalTriangle │ │ │ ├── pascalTriangle.II.cpp │ │ │ └── pascalTriangle.cpp │ │ ├── patchingArray │ │ │ └── PatchingArray.cpp │ │ ├── pathSum │ │ │ ├── pathSum.II.cpp │ │ │ └── pathSum.cpp │ │ ├── peakIndexInAMountainArray │ │ │ └── PeakIndexInAMountainArray.cpp │ │ ├── peekingIterator │ │ │ └── PeekingIterator.cpp │ │ ├── perfectRectangle │ │ │ └── PerfectRectangle.cpp │ │ ├── perfectSquares │ │ │ └── PerfectSquares.cpp │ │ ├── permutationSequence │ │ │ └── permutationSequence.cpp │ │ ├── permutations │ │ │ ├── permutations.II.cpp │ │ │ └── permutations.cpp │ │ ├── plusOne │ │ │ └── plusOne.cpp │ │ ├── populatingNextRightPointersInEachNode │ │ │ ├── populatingNextRightPointersInEachNode.II.cpp │ │ │ └── populatingNextRightPointersInEachNode.cpp │ │ ├── pow │ │ │ └── pow.cpp │ │ ├── powerOfFour │ │ │ └── PowerOfFour.cpp │ │ ├── powerOfThree │ │ │ └── PowerOfThree.cpp │ │ ├── powerOfTwo │ │ │ └── PowerOfTwo.cpp │ │ ├── processTasksUsingServers │ │ │ └── ProcessTasksUsingServers.cpp │ │ ├── productOfArrayExceptSelf │ │ │ └── ProductOfArrayExceptSelf.cpp │ │ ├── queriesOnNumberOfPointsInsideACircle │ │ │ └── QueriesOnNumberOfPointsInsideACircle.cpp │ │ ├── queueReconstructionByHeight │ │ │ └── QueueReconstructionByHeight.cpp │ │ ├── randomPickIndex │ │ │ └── RandomPickIndex.cpp │ │ ├── randomPointInNonOverlappingRectangles │ │ │ └── randomPointInNonOverlappingRectangles.cpp │ │ ├── rangeSumQuery-Immutable │ │ │ ├── rangeSumQuery-Immutable.cpp │ │ │ └── rangeSumQuery-Mutable │ │ │ │ └── RangeSumQueryMutable.cpp │ │ ├── rangeSumQuery2D-Immutable │ │ │ └── RangeSumQuery2dImmutable.cpp │ │ ├── ransomNote │ │ │ └── RansomNote.cpp │ │ ├── readNCharactersGivenRead4 │ │ │ ├── readNCharactersGivenRead4.II.cpp │ │ │ └── readNCharactersGivenRead4.cpp │ │ ├── reconstructItinerary │ │ │ └── ReconstructItinerary.cpp │ │ ├── recoverATreeFromPreorderTraversal │ │ │ └── recoverATreeFromPreorderTraversal.cpp │ │ ├── recoverBinarySearchTree │ │ │ └── recoverBinarySearchTree.cpp │ │ ├── rectangleArea │ │ │ └── RectangleArea.cpp │ │ ├── reformatPhoneNumber │ │ │ └── ReformatPhoneNumber.cpp │ │ ├── regularExpressionMatching │ │ │ └── regularExpressionMatching.cpp │ │ ├── removeDuplicateLetters │ │ │ └── RemoveDuplicateLetters.cpp │ │ ├── removeDuplicatesFromSortedArray │ │ │ ├── removeDuplicatesFromSortedArray.II.cpp │ │ │ └── removeDuplicatesFromSortedArray.cpp │ │ ├── removeDuplicatesFromSortedList │ │ │ ├── removeDuplicatesFromSortedList.II.cpp │ │ │ └── removeDuplicatesFromSortedList.cpp │ │ ├── removeElement │ │ │ └── removeElement.cpp │ │ ├── removeInvalidParentheses │ │ │ └── RemoveInvalidParentheses.cpp │ │ ├── removeKDigits │ │ │ └── RemoveKDigits.cpp │ │ ├── removeLinkedListElements │ │ │ └── RemoveLinkedListElements.cpp │ │ ├── removeNthNodeFromEndOfList │ │ │ └── removeNthNodeFromEndOfList.cpp │ │ ├── reorderList │ │ │ └── reorderList.cpp │ │ ├── repeatedDNASequences │ │ │ └── repeatedDNASequences.cpp │ │ ├── replaceAllDigitsWithCharacters │ │ │ └── ReplaceAllDigitsWithCharacters.cpp │ │ ├── restoreIPAddresses │ │ │ └── restoreIPAddresses.cpp │ │ ├── restoreTheArrayFromAdjacentPairs │ │ │ └── RestoreTheArrayFromAdjacentPairs.cpp │ │ ├── reverseBits │ │ │ └── reverseBits.cpp │ │ ├── reverseInteger │ │ │ └── reverseInteger.cpp │ │ ├── reverseLinkedList │ │ │ ├── reverseLinkedList.II.cpp │ │ │ └── reverseLinkedList.cpp │ │ ├── reverseNodesInKGroup │ │ │ └── reverseNodesInKGroup.cpp │ │ ├── reverseString │ │ │ └── ReverseString.cpp │ │ ├── reverseVowelsOfAString │ │ │ └── reverseVowelsOfAString.cpp │ │ ├── reverseWordsInAString │ │ │ ├── reverseWordsInAString.II.cpp │ │ │ └── reverseWordsInAString.cpp │ │ ├── romanToInteger │ │ │ └── romanToInteger.cpp │ │ ├── rotateArray │ │ │ └── rotateArray.cpp │ │ ├── rotateFunction │ │ │ └── RotateFunction.cpp │ │ ├── rotateImage │ │ │ └── rotateImage.cpp │ │ ├── rotateList │ │ │ └── rotateList.cpp │ │ ├── rotatingTheBox │ │ │ └── RotatingTheBox.cpp │ │ ├── sameTree │ │ │ └── sameTree.cpp │ │ ├── satisfiabilityOfEqualityEquations │ │ │ └── SatisfiabilityOfEqualityEquations.cpp │ │ ├── scrambleString │ │ │ └── scrambleString.cpp │ │ ├── search2DMatrix │ │ │ ├── search2DMatrix.II.cpp │ │ │ └── search2DMatrix.cpp │ │ ├── searchForRange │ │ │ └── searchForRange.cpp │ │ ├── searchInRotatedSortedArray │ │ │ ├── searchInRotatedSortedArray.II.cpp │ │ │ └── searchInRotatedSortedArray.cpp │ │ ├── searchInsertPosition │ │ │ └── searchInsertPosition.cpp │ │ ├── seatReservationManager │ │ │ └── SeatReservationManager.cpp │ │ ├── secondLargestDigitInAString │ │ │ └── SecondLargestDigitInAString.cpp │ │ ├── sentenceScreenFitting │ │ │ ├── main.cpp │ │ │ ├── sentenceScreenFitting.cpp │ │ │ └── sentenceScreenFitting.h │ │ ├── sentenceSimilarity │ │ │ └── SentenceSimilarity.III.cpp │ │ ├── serializeAndDeserializeBinaryTree │ │ │ └── SerializeAndDeserializeBinaryTree.cpp │ │ ├── setMatrixZeroes │ │ │ └── setMatrixZeroes.cpp │ │ ├── shortEncodingOfWords │ │ │ └── ShortEncodingOfWords.cpp │ │ ├── shortestPalindrome │ │ │ └── ShortestPalindrome.cpp │ │ ├── shuffleAnArray │ │ │ └── ShuffleAnArray.cpp │ │ ├── shuffleString │ │ │ └── ShuffleString.cpp │ │ ├── shuffleTheArray │ │ │ └── ShuffleTheArray.cpp │ │ ├── signOfTheProductOfAnArray │ │ │ └── SignOfTheProductOfAnArray.cpp │ │ ├── simplifyPath │ │ │ └── simplifyPath.cpp │ │ ├── singleNumber │ │ │ ├── singleNumber.II.cpp │ │ │ ├── singleNumber.III.cpp │ │ │ └── singleNumber.cpp │ │ ├── singleThreadedCpu │ │ │ └── SingleThreadedCpu.cpp │ │ ├── slidingWindowMaximum │ │ │ └── SlidingWindowMaximum.cpp │ │ ├── smallestStringStartingFromLeaf │ │ │ └── SmallestStringStartingFromLeaf.cpp │ │ ├── sortArrayByParity │ │ │ ├── SortArrayByParity.II.cpp │ │ │ └── SortArrayByParity.cpp │ │ ├── sortColors │ │ │ └── sortColors.cpp │ │ ├── sortList │ │ │ └── sortList.cpp │ │ ├── sortingTheSentence │ │ │ └── SortingTheSentence.cpp │ │ ├── spiralMatrix │ │ │ ├── spiralMatrix.II.cpp │ │ │ └── spiralMatrix.cpp │ │ ├── splitArrayLargestSum │ │ │ └── SplitArrayLargestSum.cpp │ │ ├── splittingAStringIntoDescendingConsecutiveValues │ │ │ └── SplittingAStringIntoDescendingConsecutiveValues.cpp │ │ ├── sqrt │ │ │ └── sqrt.cpp │ │ ├── squaresOfASortedArray │ │ │ └── SquaresOfASortedArray.cpp │ │ ├── strStr │ │ │ └── strStr.cpp │ │ ├── stringToIntegerAtoi │ │ │ └── stringToIntegerAtoi.cpp │ │ ├── stringWithoutAAAOrBBB │ │ │ └── StringWithoutAAAOrBBB.cpp │ │ ├── subsets │ │ │ ├── subsets.II.cpp │ │ │ └── subsets.cpp │ │ ├── substringWithConcatenationOfAllWords │ │ │ └── substringWithConcatenationOfAllWords.cpp │ │ ├── substringsOfSizeThreeWithDistinctCharacters │ │ │ └── SubstringsOfSizeThreeWithDistinctCharacters.cpp │ │ ├── sudokuSolver │ │ │ └── sudokuSolver.cpp │ │ ├── sumOfBeautyOfAllSubstrings │ │ │ └── SumOfBeautyOfAllSubstrings.cpp │ │ ├── sumOfDigitsInBaseK │ │ │ └── SumOfDigitsInBaseK.cpp │ │ ├── sumOfDigitsOfStringAfterConvert │ │ │ └── SumOfDigitsOfStringAfterConvert.cpp │ │ ├── sumOfEvenNumbersAfterQueries │ │ │ └── SumOfEvenNumbersAfterQueries.cpp │ │ ├── sumOfFlooredPairs │ │ │ └── SumOfFlooredPairs.cpp │ │ ├── sumOfLeftLeaves │ │ │ └── SumOfLeftLeaves.cpp │ │ ├── sumOfTwoIntegers │ │ │ └── SumOfTwoIntegers.cpp │ │ ├── sumOfUniqueElements │ │ │ └── SumOfUniqueElements.cpp │ │ ├── sumRootToLeafNumber │ │ │ └── sumRootToLeafNumber.cpp │ │ ├── summaryRanges │ │ │ └── SummaryRanges.cpp │ │ ├── superUglyNumber │ │ │ └── SuperUglyNumber.cpp │ │ ├── surroundedRegions │ │ │ └── surroundedRegions.cpp │ │ ├── swapNodesInPairs │ │ │ └── swapNodesInPairs.cpp │ │ ├── symmetricTree │ │ │ └── symmetricTree.cpp │ │ ├── targetSum │ │ │ └── targetSum.cpp │ │ ├── textJustification │ │ │ └── textJustification.cpp │ │ ├── theSkylineProblem │ │ │ └── TheSkylineProblem.cpp │ │ ├── thirdMaximumNumber │ │ │ └── ThirdMaximumNumber.cpp │ │ ├── thousandSeparator │ │ │ └── ThousandSeparator.cpp │ │ ├── threeConsecutiveOdds │ │ │ └── ThreeConsecutiveOdds.cpp │ │ ├── timeBasedKeyValueStore │ │ │ └── TimeBasedKeyValueStore.cpp │ │ ├── timeNeededToInformAllEmployees │ │ │ └── TimeNeededToInformAllEmployees.cpp │ │ ├── topKFrequentElements │ │ │ └── topKFrequentElements.cpp │ │ ├── totalHammingDistance │ │ │ └── totalHammingDistance.cpp │ │ ├── trappingRainWater │ │ │ └── trappingRainWater.cpp │ │ ├── treeOfCoprimes │ │ │ └── TreeOfCoprimes.cpp │ │ ├── triangle │ │ │ └── triangle.cpp │ │ ├── triplesWithBitwiseANDEqualToZero │ │ │ └── TriplesWithBitwiseAndEqualToZero.cpp │ │ ├── truncateSentence │ │ │ └── TruncateSentence.cpp │ │ ├── tupleWithSameProduct │ │ │ └── TupleWithSameProduct.cpp │ │ ├── twoArraysEqualByReversingSubArrays │ │ │ └── MakeTwoArraysEqualByReversingSubArrays.cpp │ │ ├── twoCityScheduling │ │ │ └── TwoCityScheduling.cpp │ │ ├── twoSum │ │ │ ├── twoSum.II.cpp │ │ │ ├── twoSum.III.cpp │ │ │ └── twoSum.cpp │ │ ├── uglyNumber │ │ │ ├── UglyNumber.II.cpp │ │ │ └── UglyNumber.cpp │ │ ├── uniqueBinarySearchTrees │ │ │ ├── uniqueBinarySearchTrees.II.cpp │ │ │ └── uniqueBinarySearchTrees.cpp │ │ ├── uniqueEmailAddresses │ │ │ └── UniqueEmailAddresses.cpp │ │ ├── uniqueMorseCodeWords │ │ │ └── UniqueMorseCodeWords.cpp │ │ ├── uniqueNumberOfOccurrences │ │ │ └── Unique-Number-of-Occurrences.cpp │ │ ├── uniquePaths │ │ │ ├── UniquePaths.III.cpp │ │ │ ├── uniquePaths.II.cpp │ │ │ └── uniquePaths.cpp │ │ ├── validNumber │ │ │ └── validNumber.cpp │ │ ├── validPalindrome │ │ │ └── validPalindrome.cpp │ │ ├── validParentheses │ │ │ └── validParentheses.cpp │ │ ├── validPerfectSquare │ │ │ └── ValidPerfectSquare.cpp │ │ ├── validSudoku │ │ │ └── validSudoku.cpp │ │ ├── validateBinarySearchTree │ │ │ └── validateBinarySearchTree.cpp │ │ ├── verifyPreorderSerializationOfABinaryTree │ │ │ └── VerifyPreorderSerializationOfABinaryTree.cpp │ │ ├── verticalOrderTraversalOfABinaryTree │ │ │ └── VerticalOrderTraversalOfABinaryTree.cpp │ │ ├── videoStitching │ │ │ └── VideoStitching.cpp │ │ ├── waysToSplitArrayIntoThreeSubarrays │ │ │ └── WaysToSplitArrayIntoThreeSubarrays.cpp │ │ ├── wiggleSort │ │ │ └── WiggleSort.II.cpp │ │ ├── wiggleSubsequence │ │ │ └── wiggleSubsequence.cpp │ │ ├── wildcardMatching │ │ │ └── wildcardMatching.cpp │ │ ├── wordBreak │ │ │ ├── wordBreak.II.cpp │ │ │ └── wordBreak.cpp │ │ ├── wordLadder │ │ │ ├── wordLadder.II.cpp │ │ │ └── wordLadder.cpp │ │ ├── wordPattern │ │ │ └── WordPattern.cpp │ │ ├── wordSearch │ │ │ ├── wordSearch.II.cpp │ │ │ └── wordSearch.cpp │ │ └── zigZagConversion │ │ │ └── zigZagConversion.cpp │ ├── golang │ │ └── twoSum │ │ │ └── twoSum.go │ ├── java │ │ ├── algorithms-java.iml │ │ ├── junit-4.7.jar │ │ └── src │ │ │ ├── LargestNumberAfterMutatingSubstring │ │ │ └── largestNumberAfterMutatingSubstring.java │ │ │ ├── MaxSubArray │ │ │ └── MaxSubarray.java │ │ │ ├── RotateImage │ │ │ └── rotateImage.java │ │ │ ├── balancedBinaryTree │ │ │ ├── TreeNode.java │ │ │ ├── balancedBinaryTree.java │ │ │ └── balancedBinaryTreeTest.java │ │ │ ├── binarySearchTreeIterator │ │ │ ├── TreeNode.java │ │ │ ├── binarySearchTreeIterator.java │ │ │ └── binarySearchTreeIteratorTest.java │ │ │ ├── binaryTreeBFSTraversal │ │ │ ├── TreeNode.java │ │ │ ├── binaryTreeBFSTraversal.java │ │ │ └── binaryTreeBFSTraversalTest.java │ │ │ ├── binaryTreeLevelOrderTraversal │ │ │ ├── TreeNode.java │ │ │ ├── binaryTreeLevelOrderTraversal.java │ │ │ └── binaryTreeLevelOrderTraversalTest.java │ │ │ ├── binaryTreeMaximumPathSum │ │ │ ├── TreeNode.java │ │ │ ├── binaryTreeMaximumPathSum.java │ │ │ └── binaryTreeMaximumPathSumTest.java │ │ │ ├── binaryTreePreorderTraversal │ │ │ ├── TreeNode.java │ │ │ ├── binaryTreePreorderTraversal.java │ │ │ └── binaryTreePreorderTraversalTest.java │ │ │ ├── containerwithmostwater.java │ │ │ ├── countAndSay │ │ │ ├── CountAndSay.java │ │ │ └── TestCountAndSay.java │ │ │ ├── dynamicProgramming │ │ │ ├── climbStairs │ │ │ │ ├── climbStairs.java │ │ │ │ └── climbStairsTest.java │ │ │ ├── minimumPathSum │ │ │ │ ├── minimumPathSum.java │ │ │ │ └── minimumPathSumTest.java │ │ │ ├── triangle │ │ │ │ ├── triangle.java │ │ │ │ └── triangleTest.java │ │ │ └── uniquePaths │ │ │ │ ├── uniquePaths.java │ │ │ │ ├── uniquePathsII.java │ │ │ │ ├── uniquePathsIITest.java │ │ │ │ └── uniquePathsTest.java │ │ │ ├── findMinimumInRotatedSortedArray │ │ │ ├── findMinimumInRotatedSortedArray.java │ │ │ └── findMinimumInRotatedSortedArrayTest.java │ │ │ ├── findPeakElement │ │ │ ├── findPeakElement.java │ │ │ └── findPeakElementTest.java │ │ │ ├── firstBadVersion │ │ │ ├── VersionControl.java │ │ │ ├── firstBadVersion.java │ │ │ └── firstBadVersionTest.java │ │ │ ├── inorderSuccessorInBST │ │ │ ├── TreeNode.java │ │ │ ├── inorderSuccessorInBST.java │ │ │ └── inorderSuccessorInBSTTest.java │ │ │ ├── lengthOfLastWord │ │ │ ├── LengthOfLastWord.java │ │ │ └── TestLengthOfLastWord.java │ │ │ ├── lowestCommonAncestorOfABinaryTree │ │ │ ├── TreeNode.java │ │ │ ├── lowestCommonAncestorOfABinaryTree.java │ │ │ └── lowestCommonAncestorOfABinaryTreeTest.java │ │ │ ├── lruCache │ │ │ ├── LRUCache.java │ │ │ └── LRUCacheTest.java │ │ │ ├── maximumDepthOfBinaryTree │ │ │ ├── TreeNode.java │ │ │ ├── maximumDepthOfBinaryTree.java │ │ │ └── maximumDepthOfBinaryTreeTest.java │ │ │ ├── minStack │ │ │ ├── MinStack.java │ │ │ └── TestMinStack.java │ │ │ ├── myQueue │ │ │ ├── MyQueue.java │ │ │ └── TestMyQueue.java │ │ │ ├── myStack │ │ │ ├── MyStack.java │ │ │ └── TestMyStack.java │ │ │ ├── palindromeNumber │ │ │ ├── PalindromeNumber.java │ │ │ └── TestPalindromeNumber.java │ │ │ ├── powXn │ │ │ ├── PowXn.java │ │ │ └── TestPowXn.java │ │ │ ├── removeDuplicatesFromSortedArray │ │ │ ├── RemoveDuplicatesFromSortedArray.java │ │ │ └── TestRemoveDuplicates.java │ │ │ ├── reverseLinkedList │ │ │ ├── ListNode.java │ │ │ ├── ReverseLinkedList.java │ │ │ └── TestReverseLinkedList.java │ │ │ ├── reverseLinkedListII │ │ │ ├── ListNode.java │ │ │ ├── ReverseLinkedListII.java │ │ │ └── TestReverseLinkedListII.java │ │ │ ├── reverseWordsInAString │ │ │ ├── ReverseWordsInAString.java │ │ │ └── TestReverseWordsInAString.java │ │ │ ├── rotateArray │ │ │ ├── RotateArray.java │ │ │ └── TestRotateArray.java │ │ │ ├── search2DMatrix │ │ │ ├── search2DMatrix.java │ │ │ └── search2DMatrixTest.java │ │ │ ├── searchA2DMatrixII │ │ │ ├── SearchA2DMatrixII.java │ │ │ └── Test_240.java │ │ │ ├── searchForRange │ │ │ ├── searchForRange.java │ │ │ └── searchForRangeTest.java │ │ │ ├── searchInABigSortedArray │ │ │ ├── searchInABigSortedArray.java │ │ │ └── searchInABigSortedArrayTest.java │ │ │ ├── searchInRotatedSortedArray │ │ │ ├── searchInRotatedSortedArray.java │ │ │ └── searchInRotatedSortedArrayTest.java │ │ │ ├── searchInsertPosition │ │ │ ├── searchInsertPosition.java │ │ │ └── searchInsertPositionTest.java │ │ │ ├── searchRangeInBinarySearchTree │ │ │ ├── TreeNode.java │ │ │ ├── searchRangeInBinarySearchTree.java │ │ │ └── searchRangeInBinarySearchTreeTest.java │ │ │ ├── strStr │ │ │ ├── StrStrKmp.java │ │ │ ├── TestStrStrKmp.java │ │ │ ├── strStr.java │ │ │ └── strStrTest.java │ │ │ ├── subsets │ │ │ ├── subsets.java │ │ │ ├── subsetsII.java │ │ │ ├── subsetsIITest.java │ │ │ └── subsetsTest.java │ │ │ ├── validAnagram │ │ │ ├── TestValidAnagram.java │ │ │ └── ValidAnagram.java │ │ │ ├── validPalindrome │ │ │ ├── TestValidPalindrome.java │ │ │ └── ValidPalindrome.java │ │ │ └── validateBinarySearchTree │ │ │ ├── TreeNode.java │ │ │ ├── validateBinarySearchTree.java │ │ │ └── validateBinarySearchTreeTest.java │ └── python │ │ ├── 1-bitAnd2-bitCharacters │ │ └── isOneBitCharacter.py │ │ ├── AddOneRowToTree │ │ └── addOneRow.py │ │ ├── BinarySearchTreeIterator │ │ └── BSTIterator.py │ │ ├── BinaryTreePostorderTraversal │ │ └── postorderTraversal.py │ │ ├── BinaryTreeTilt │ │ └── findTilt.py │ │ ├── BinaryTreeZigzagLevelOrderTraversal │ │ └── zigzagLevelOrder.py │ │ ├── CheckCompletenessOfABinaryTree │ │ └── isCompleteTree.py │ │ ├── ConstructBinaryTreeFromInorderAndPostorderTraversal │ │ └── buildTree.py │ │ ├── ConstructBinaryTreeFromPreorderAndInorderTraversal │ │ └── buildTree.py │ │ ├── ContainsDuplicateII │ │ └── containsNearbyDuplicate.py │ │ ├── ContainsDuplicateIII │ │ └── containsNearbyAlmostDuplicate.py │ │ ├── ConvertBSTtoGreaterTree │ │ └── convertBST.py │ │ ├── CopyListWithRandomPointer │ │ └── copyRandomList.py │ │ ├── CountCompleteTreeNodes │ │ └── countNodes.py │ │ ├── DeleteNodeInABST │ │ └── deleteNode.py │ │ ├── DiameterOfBinaryTree │ │ └── diameterOfBinaryTree.py │ │ ├── DifferentWaysToAddParentheses │ │ └── diffWaysToCompute.py │ │ ├── FibonacciNumber │ │ └── fib.py │ │ ├── FindDuplicateSubtrees │ │ └── findDuplicateSubtrees.py │ │ ├── FindTheDuplicateNumber │ │ └── findDuplicate.py │ │ ├── FlattenBinaryTreeToLinkedList │ │ └── flatten.py │ │ ├── FlipBinaryTreeToMatchPreorderTraversal │ │ └── flipMatchVoyage.py │ │ ├── FlipEquivalentBinaryTrees │ │ └── flipEquiv.py │ │ ├── HappyNumber │ │ └── isHappy.py │ │ ├── HouseRobber │ │ └── rob.py │ │ ├── HouseRobberIII │ │ └── rob.py │ │ ├── ImageSmoother │ │ └── imageSmoother.py │ │ ├── InsertionSortList │ │ └── insertionSortList.py │ │ ├── K-diffPairsInAnArray │ │ └── findPairs.py │ │ ├── KthSmallestElementInABST │ │ └── kthSmallest.py │ │ ├── LargestNumberAtLeastTwiceOfOthers │ │ └── dominantIndex.py │ │ ├── LargestPerimeterTriangle │ │ └── largestPerimeter.py │ │ ├── LinkedListCycleII │ │ └── detectCycle.py │ │ ├── LongestConsecutiveSequence │ │ └── LongestConsecutive.py │ │ ├── LongestContinuousIncreasingSubsequence │ │ └── findLengthOfLCIS.py │ │ ├── LongestTurbulentSubarray │ │ └── maxTurbulenceSize.py │ │ ├── LongestUnivaluePath │ │ └── longestUnivaluePath.py │ │ ├── LowestCommonAncestorOfABinarySearchTree │ │ └── lowestCommonAncestor.py │ │ ├── LowestCommonAncestorOfABinaryTree │ │ └── lowestCommonAncestor.py │ │ ├── MaximizeDistanceToClosestPerson │ │ └── maxDistToClosest.py │ │ ├── MaximumAverageSubarrayI │ │ └── findMaxAverage.py │ │ ├── MaximumProductOfThreeNumbers │ │ └── maximumProduct.py │ │ ├── MaximumWidthOfBinaryTree │ │ └── widthOfBinaryTree.py │ │ ├── MiddleOfTheLinkedList │ │ └── middleOfTheLinkedList.py │ │ ├── MinCostClimbingStairs │ │ └── minCostClimbingStairs.py │ │ ├── Non-decreasingArray │ │ └── checkPossibility.py │ │ ├── NumberOfIslands │ │ └── numIslands.py │ │ ├── PancakeSorting │ │ └── pancakeSort.py │ │ ├── PartitionList │ │ └── partition.py │ │ ├── PathSumII │ │ └── pathSum.py │ │ ├── PathSumIII │ │ └── pathSum.py │ │ ├── PopulatingNextRightPointersInEachNode │ │ └── connect.py │ │ ├── PopulatingNextRightPointersInEachNodeII │ │ └── connect.py │ │ ├── PositionsOfLargeGroups │ │ └── largeGroupPositions.py │ │ ├── PrintBinaryTree │ │ └── printTree.py │ │ ├── RedundantConnection │ │ └── findRedundantConnection.py │ │ ├── RemoveDuplicatesFromSortedListII │ │ └── deleteDuplicates.py │ │ ├── RemoveNthNodeFromEndOfList │ │ └── removeNthFromEnd.py │ │ ├── ReorderList │ │ └── reorderList.py │ │ ├── RevealCardsInIncreasingOrder │ │ └── deckRevealedIncreasing.py │ │ ├── ReverseLinkedListII │ │ └── reverseBetween.py │ │ ├── SearchA2DMatrixII │ │ └── searchMatrix.py │ │ ├── SecondMinimumNodeInABinaryTree │ │ └── findSecondMinimumValue.py │ │ ├── SerializeAndDeserializeBST │ │ └── serialize.py │ │ ├── ShortestUnsortedContinuousSubarray │ │ └── findUnsortedSubarray.py │ │ ├── SingleNumberII │ │ └── SingleNumberII.py │ │ ├── SortList │ │ └── sortList.py │ │ ├── SquaresOfSortedArray │ │ └── sortedSquares.py │ │ ├── Subsets │ │ └── subsets.py │ │ ├── SubtreeOfAnotherTree │ │ └── isSubtree.py │ │ ├── SumOfLeftLeaves │ │ └── sumOfLeftLeaves.py │ │ ├── SumRootToLeafNumbers │ │ └── sumNumbers.py │ │ ├── SwimInRisingWater │ │ └── swim_in_rising_water.py │ │ ├── ThirdMaximumNumber │ │ └── thirdMax.py │ │ ├── UniqueBinarySearchTrees │ │ └── numTrees.py │ │ ├── UniqueBinarySearchTreesII │ │ └── generateTrees.py │ │ ├── ValidMountainArray │ │ └── validMountainArray.py │ │ ├── ValidateBinarySearchTree │ │ └── isValidBST.py │ │ ├── XOfAKindInADeckOfCards │ │ └── hasGroupsSizeX.py │ │ ├── firstMissingPositive │ │ └── firstMissingPositive.py │ │ ├── jumpGame │ │ └── jumpGame.py │ │ └── uniquePaths │ │ └── uniquePathsIII.py ├── database │ ├── README.md │ └── TripsAndUsers.sql ├── scripts │ ├── README.md │ ├── comments.sh │ ├── git.config.sh │ ├── lib │ │ └── query_problem.sh │ ├── readme.sh │ └── workflow.sh └── shell │ ├── README.md │ ├── TenthLine.sh │ ├── TransposeFile.sh │ ├── ValidPhoneNumbers.sh │ └── WordFrequency.sh ├── translations ├── README-ar.md ├── README-bg.md ├── README-bn.md ├── README-cn.md ├── README-de.md ├── README-el.md ├── README-es.md ├── README-fa.md ├── README-fr.md ├── README-he.md ├── README-hi.md ├── README-id.md ├── README-ja.md ├── README-kh.md ├── README-ko.md ├── README-pl.md ├── README-ptbr.md ├── README-ru.md ├── README-th.md ├── README-tr.md ├── README-tw.md ├── README-uk.md ├── README-ur.md ├── README-uz.md ├── README-vi.md └── how-to.md └── urlLookup-codingchallenge ├── README.md ├── blacklist ├── url1.txt └── url2.txt ├── cmd ├── svc │ └── main.go └── updater │ └── main.go ├── config.go ├── db ├── api.go └── db.go ├── docker ├── Dockerfile.updater ├── Dockerfile.webservice ├── docker-compose.yaml ├── nginx-conf │ └── nginx.conf ├── redis-conf │ ├── redis-1-master.conf │ └── redis-1-slave.conf ├── svc-conf │ └── svc.conf └── updater-conf │ └── updater.conf ├── go.mod ├── go.sum ├── handler ├── api.go └── handler.go ├── model └── url.go ├── router ├── router.go └── routes.go ├── updater ├── updater.go └── updater_test.go └── utils.go /extras/cheat sheets/C Reference Card (ANSI) 2.2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/C Reference Card (ANSI) 2.2.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/Coding Interview Python Language Essentials.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/Coding Interview Python Language Essentials.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/Cpp_reference.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/Cpp_reference.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/STL Quick Reference 1.29.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/STL Quick Reference 1.29.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/big-o-cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/big-o-cheatsheet.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/bits-cheat-sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/bits-cheat-sheet.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/python-cheat-sheet-v1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/python-cheat-sheet-v1.pdf -------------------------------------------------------------------------------- /extras/cheat sheets/system-design.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/extras/cheat sheets/system-design.pdf -------------------------------------------------------------------------------- /faang-codingexercises/Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | verify_ssl = true 3 | url = "https://pypi.org/simple" 4 | name = "pypi" 5 | 6 | 7 | [dev-packages] 8 | pygame = "*" 9 | sympy = "*" 10 | 11 | [requires] 12 | python_version = "3.10" 13 | sympy = "1.3" 14 | anytree = "2.4.3" 15 | 16 | [packages] 17 | pytest = "*" 18 | numpy = "*" 19 | html-testrunner = "*" 20 | pygame = "*" 21 | sympy = "*" 22 | -------------------------------------------------------------------------------- /faang-codingexercises/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-midnight -------------------------------------------------------------------------------- /faang-codingexercises/bash_scripts/datetime.dat: -------------------------------------------------------------------------------- 1 | # bash --date and -d option expects the date in US or ISO8601 format, 2 | # i.e. mm/dd/yyyy or yyyy-mm-dd, not in UK, EU, or any other format. 3 | 2019-01-07 10:51:56 4 | 2018-09-23 09:11:27 5 | 2022-01-01 21:51:09 6 | 2014-12-03 11:25:49 7 | 2010-05-20 01:51:44 8 | 1998-03-10 05:47:02 9 | #Wed 26 Sep 07:45:47 EDT 2018 10 | #Mon Jan 7 10:45:04 PST 2019 11 | #Mon 7 Jan 11:53:40 PST 2019 12 | #Tue 02 Oct 02:22:34 PST 2018 13 | 06/22/2011 01:51:44 14 | -------------------------------------------------------------------------------- /faang-codingexercises/node_modules/numpy/README.md: -------------------------------------------------------------------------------- 1 | # numpy 2 | numpy 3 | -------------------------------------------------------------------------------- /faang-codingexercises/node_modules/unittest/index.js: -------------------------------------------------------------------------------- 1 | import Auth from "./model/Auth"; 2 | 3 | var auth = new Auth(); 4 | console.log(auth.hello()); 5 | -------------------------------------------------------------------------------- /faang-codingexercises/node_modules/unittest/model/Auth.js: -------------------------------------------------------------------------------- 1 | import User from './User'; 2 | 3 | class Auth { 4 | constructor() { 5 | 6 | } 7 | hello() { 8 | var newUser = new User(); 9 | return newUser.signin(); 10 | } 11 | } 12 | 13 | export default Auth; 14 | -------------------------------------------------------------------------------- /faang-codingexercises/node_modules/unittest/model/User.js: -------------------------------------------------------------------------------- 1 | export default class Idea { 2 | constructor() { 3 | 4 | } 5 | signin() { 6 | return "SignIn"; 7 | } 8 | } -------------------------------------------------------------------------------- /faang-codingexercises/node_modules/unittest/test/testUser.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const User = require('../model/User') 4 | const expect = require('chai').expect 5 | 6 | describe('User module', () => { 7 | describe("init", () => { 8 | it('should export a function', () => { 9 | expect(User.init).to.be.a('function') 10 | }) 11 | }) 12 | }) -------------------------------------------------------------------------------- /faang-codingexercises/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "requires": true, 3 | "lockfileVersion": 1, 4 | "dependencies": { 5 | "numpy": { 6 | "version": "0.0.1", 7 | "resolved": "https://registry.npmjs.org/numpy/-/numpy-0.0.1.tgz", 8 | "integrity": "sha1-xrvUxJtFvVN/dooJySIKKQ3kFZg=" 9 | }, 10 | "unittest": { 11 | "version": "1.0.0", 12 | "resolved": "https://registry.npmjs.org/unittest/-/unittest-1.0.0.tgz", 13 | "integrity": "sha512-FG4NN+k1Nfnw429RjFTHMQh3R6k2GjSB2PNy5Fly9NESy76n1yePyPs3Jgriv5BoM+iBXGafXAKixGDYx0Hzyw==" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /faang-codingexercises/resources/bkg-blu.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/faang-codingexercises/resources/bkg-blu.jpg -------------------------------------------------------------------------------- /faang-codingexercises/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This script executes the python program and pipes the output to the end of the python code 4 | # 5 | # 6 | if [ $# -lt 1 ]; then 7 | echo "Usage:" 8 | echo " bash run.sh codechallenge_###.py" 9 | echo " Example:" 10 | echo " bash run.sh codechallenge_015.py" 11 | exit 0 12 | else 13 | python $1 > output.txt 14 | echo -e "'''\nRun-time output:\n===============\n$(cat output.txt)" > input.txt; echo -e "'''\n" >> input.txt 15 | rm -f output.txt 16 | cat input.txt >> $1 17 | rm -f input.txt 18 | fi 19 | -------------------------------------------------------------------------------- /img/All-The-Worlds-Brands.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/img/All-The-Worlds-Brands.jpg -------------------------------------------------------------------------------- /img/faang-stocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/img/faang-stocks.png -------------------------------------------------------------------------------- /img/fangvaasm.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/img/fangvaasm.jpg -------------------------------------------------------------------------------- /leetcode-part-1/cpp/1310_XOR_Queries_of_a_Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector xorQueries(vector& arr, vector>& queries) { 4 | vector res; 5 | // Compute accumulated xor from head 6 | for (int i = 1; i < arr.size(); i++) 7 | arr[i] ^= arr[i - 1]; 8 | for (auto &q: queries) 9 | res.push_back(q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]); 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /leetcode-part-1/cpp/201_bitwise_and_of_numbers_range.cpp: -------------------------------------------------------------------------------- 1 | /** time complexity : O(logN). N = min(m, n) **/ 2 | 3 | class Solution { 4 | public: 5 | int rangeBitwiseAnd(int m, int n) { 6 | int cnt = 0; 7 | while(m < n) { 8 | m = m >> 1; 9 | n = n >> 1; 10 | cnt++; 11 | } 12 | return n< fizzBuzz(int n) { 5 | int i; 6 | vector s; 7 | for (i = 0; i < n; i++) { 8 | if ((i + 1) % 15 == 0) 9 | s.pb("FizzBuzz"); 10 | else if ((i + 1) % 5 == 0) 11 | s.pb("Buzz"); 12 | else if ((i + 1) % 3 == 0) 13 | s.pb("Fizz"); 14 | else 15 | s.pb(to_string(i + 1)); 16 | } 17 | return s; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode-part-1/create_empty_files.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | if __name__ == '__main__': 4 | file_name = 'test' 5 | try: 6 | file_name = sys.argv[1] 7 | except IndexError: 8 | print("Usage: python create_empty_file [filename]") 9 | print("Creating " + file_name + "in java and python dir...") 10 | with open("python/" + file_name + ".py", 'w'): 11 | pass 12 | with open("java/" + file_name + ".java", 'w'): 13 | pass 14 | print("Done!") 15 | -------------------------------------------------------------------------------- /leetcode-part-1/java/001_Two_Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // example in leetcode book 3 | public int[] twoSum(int[] nums, int target) { 4 | Map map = new HashMap<>(); 5 | for (int i = 0; i < nums.length; i++) { 6 | int x = nums[i]; 7 | if (map.containsKey(target - x)) { 8 | return new int[]{map.get(target - x), i}; 9 | } 10 | map.put(x, i); 11 | } 12 | throw new IllegalArgumentException("No two sum solution"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /leetcode-part-1/java/006_ZigZag_Conversion.java: -------------------------------------------------------------------------------- 1 | //TODO -------------------------------------------------------------------------------- /leetcode-part-1/java/007_Reverse_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | if (x == 0) return 0; 4 | long res = 0; 5 | while (x != 0) { 6 | res = res * 10 + x % 10; 7 | if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) 8 | return 0; 9 | x /= 10; 10 | } 11 | return (int) res; 12 | } 13 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/011_Container_With_Most_Water.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | 4 | int maxArea = 0; 5 | int left = 0; 6 | int right = height.length - 1; 7 | 8 | while (left < right) { 9 | maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right])); 10 | // Two points 11 | if (height[left] < height[right]) left++; 12 | else right--; 13 | } 14 | return maxArea; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-1/java/012_Integer_to_Roman.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String intToRoman(int num) { 3 | Map map = new HashMap(); 4 | map.put(1, "I"); map.put(5, "V"); map.put(10, "X"); 5 | map.put(50, "L"); map.put(100, "C"); map.put(500, "D"); map.put(1000, "M"); 6 | map.put(4, "IV"); map.put(9, "IX"); map.put(40, "XL"); map.put(90, "XC"); 7 | map.put(400, "CD"); map.put(900, "CM"); 8 | 9 | int[] sequence = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 10 | 11 | StringBuffer sb = new StringBuffer(); 12 | for (int i = 0; i= base) { 16 | sb.append(map.get(base)); 17 | num -= base; 18 | } 19 | } 20 | 21 | return sb.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode-part-1/java/013_Roman_to_Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | int[] arr = new int['A' + 26]; 4 | arr['I'] = 1; 5 | arr['V'] = 5; 6 | arr['X'] = 10; 7 | arr['L'] = 50; 8 | arr['C'] = 100; 9 | arr['D'] = 500; 10 | arr['M'] = 1000; 11 | 12 | int result = 0; 13 | int prev = 0; 14 | 15 | for (int i = s.length() - 1; i >= 0; i--) { 16 | int current = arr[s.charAt(i)]; 17 | result += prev > current ? -current : current; 18 | prev = current; 19 | } 20 | 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/1064_Fixed_Point.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /* public int fixedPoint(int[] A) { 3 | for (int i = 0; i < A.length; i++) { 4 | // Because if A[i] > i, then i can never be greater than A[i] any more 5 | if (A[i] == i) return i; 6 | else if (A[i] > i) return -1; 7 | } 8 | return -1; 9 | } */ 10 | public int fixedPoint(int[] A) { 11 | int l = 0; 12 | int h = A.length; 13 | while (l <= h) { 14 | int mid = (l + h) / 2; 15 | if (A[mid] > mid) h = mid - 1; 16 | else if (A[mid] < mid) l = mid + 1; 17 | else return mid; 18 | } 19 | return -1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode-part-1/java/1304_Find_N_Unique_Integers_Sum_up_to_Zero.java: -------------------------------------------------------------------------------- 1 | public int[] sumZero(int n) { 2 | int[] res = new int[n]; 3 | // place negative sum(from 1 to n-1) in 0 4 | for (int i = 1; i < n; i++) { 5 | res[i] = i; 6 | res[0] -= i; 7 | } 8 | return res; 9 | } 10 | -------------------------------------------------------------------------------- /leetcode-part-1/java/1310_XOR_Queries_of_a_Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] xorQueries(int[] arr, int[][] queries) { 3 | int[] res = new int[queries.length], q; 4 | // Compute accumulated xor from head 5 | for (int i = 1; i < arr.length; i++) 6 | arr[i] ^= arr[i - 1]; 7 | // query result equals to xor[0, l] xor xor[0, r] 8 | for (int i = 0; i < queries.length; i++) { 9 | q = queries[i]; 10 | res[i] = q[0] > 0 ? arr[q[0] - 1] ^ arr[q[1]] : arr[q[1]]; 11 | } 12 | return res; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /leetcode-part-1/java/1323_Maximum_69_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximum69Number (int num) { 3 | // Replace first 6 with 9 if exists 4 | return Integer.valueOf(String.valueOf(num).replaceFirst("6", "9")); 5 | } 6 | 7 | /* 8 | public int maximum69Number (int num) { 9 | char[] chars = Integer.toString(num).toCharArray(); 10 | // Replace first 6 with 9 if exists 11 | for (int i = 0; i < chars.length; i++) { 12 | if (chars[i] == '6') { 13 | chars[i] = '9'; 14 | break; 15 | } 16 | } 17 | return Integer.parseInt(new String(chars)); 18 | }*/ 19 | } 20 | -------------------------------------------------------------------------------- /leetcode-part-1/java/1480_Running_Sum_of_1d_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] runningSum(int[] nums) { 3 | if (nums.length <= 1) return nums; 4 | for (int i = 1; i < nums.length; i++) 5 | nums[i] += nums[i - 1]; 6 | return nums; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /leetcode-part-1/java/204_Count_Primes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // ttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity 3 | public int countPrimes(int n) { 4 | boolean[] isPrime = new boolean[n]; 5 | int count = 0; 6 | Arrays.fill(isPrime, true); 7 | for (int i = 2; i < n; i++) { 8 | if (i * i >= n) 9 | break; 10 | if (!isPrime[i]) 11 | continue; 12 | for (int j = i * i; j < n; j += i) 13 | isPrime[j] = false; 14 | } 15 | for (int i = 2; i < n; i++) 16 | if (isPrime[i]) 17 | count++; 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-1/java/223_Rectangle_Area.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 3 | // https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way 4 | // Possible overlap area 5 | int left = Math.max(A, E), right = Math.max(Math.min(C, G), left); 6 | int bottom = Math.max(B, F), top = Math.max(Math.min(D, H), bottom); 7 | return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /leetcode-part-1/java/238_Product_of_Array_Except_Self.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int n = nums.length; 4 | int[] res = new int[n]; 5 | res[0] = 1; 6 | for (int i = 1; i < n; i++) { 7 | // left part 8 | res[i] = res[i - 1] * nums[i - 1]; 9 | } 10 | int right = 1; 11 | for (int i = n - 1; i >= 0; i--) { 12 | res[i] *= right; 13 | // right part 14 | right *= nums[i]; 15 | } 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode-part-1/java/383_Ransom_Note.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canConstruct(String ransomNote, String magazine) { 3 | int[] table = new int[128]; 4 | for (char c : magazine.toCharArray()) table[c]++; 5 | for (char c : ransomNote.toCharArray()) 6 | if (--table[c] < 0) return false; 7 | return true; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /leetcode-part-1/java/387_First_Unique_Character_in_a_String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int firstUniqChar(String s) { 3 | int freq [] = new int[26]; 4 | for(int i = 0; i < s.length(); i ++) 5 | freq [s.charAt(i) - 'a'] ++; 6 | for(int i = 0; i < s.length(); i ++) 7 | if(freq [s.charAt(i) - 'a'] == 1) 8 | return i; 9 | return -1; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode-part-1/java/389_Find_the_Difference.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public char findTheDifference(String s, String t) { 3 | int total = t.charAt(s.length()); 4 | for (int i = 0; i < s.length(); i++) 5 | total += (t.charAt(i) - s.charAt(i)); 6 | return (char) total; 7 | } 8 | 9 | /* public char findTheDifference(String s, String t) { 10 | int total = t.charAt(s.length()); 11 | for (int i = 0; i < s.length(); i++) { 12 | total ^= t.charAt(i); 13 | total ^= s.charAt(i); 14 | } 15 | return (char) total; 16 | } */ 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-1/java/400_Nth_Digit.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findNthDigit(int n) { 3 | int len = 1; 4 | long count = 9; 5 | int start = 1; 6 | // https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution 7 | while (n > len * count) { 8 | n -= len * count; 9 | len += 1; 10 | count *= 10; 11 | start *= 10; 12 | } 13 | start += (n - 1) / len; 14 | String s = Integer.toString(start); 15 | return Character.getNumericValue(s.charAt((n - 1) % len)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-1/java/401_Binary_Watch.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List readBinaryWatch(int num) { 3 | List times = new ArrayList<>(); 4 | for (int h = 0; h < 12; h++) 5 | for (int m = 0; m < 60; m++) 6 | if (Integer.bitCount(h * 64 + m) == num) 7 | times.add(String.format("%d:%02d", h, m)); 8 | return times; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /leetcode-part-1/java/405_Convert_a_Number_to_Hexadecimal.java: -------------------------------------------------------------------------------- 1 | import com.sun.corba.se.spi.orbutil.fsm.Guard.Result; 2 | 3 | class Solution { 4 | public String toHex(int num) { 5 | String hex_map = "0123456789abcdef"; 6 | if (num == 0) return "0"; 7 | String res = ""; 8 | // To avoid infinite loop caused by negative num 9 | while (num != 0 && res.length() < 8) { 10 | res = hex_map.charAt(num & 15) + res; 11 | num = num >> 4; 12 | } 13 | return res; 14 | } 15 | 16 | /* public String toHex(int num) { 17 | String hex = Integer.toHexString(num); 18 | return hex; 19 | } */ 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-1/java/409_Longest_Palindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/longest-palindrome/solution/ 3 | public int longestPalindrome(String s) { 4 | int[] count = new int[128]; 5 | for (char c: s.toCharArray()) 6 | count[c]++; 7 | 8 | int ans = 0; 9 | for (int v: count) { 10 | ans += v / 2 * 2; 11 | if (ans % 2 == 0 && v % 2 == 1) 12 | ans++; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/412_Fizz_Buzz.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Solution { 5 | public List fizzBuzz(int n) { 6 | List res = new ArrayList<>(); 7 | for (int i = 1; i <= n; i++) { 8 | String tmp = ""; 9 | if (i % 3 == 0) tmp += "Fizz"; 10 | if (i % 5 == 0) tmp += "Buzz"; 11 | if (tmp.length() == 0) tmp += String.valueOf(i); 12 | res.add(tmp); 13 | } 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-1/java/414_Third_Maximum_Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int thirdMax(int[] nums) { 3 | PriorityQueue pq = new PriorityQueue<>(3); 4 | Set set = new HashSet<>(); 5 | for (int i : nums) { 6 | if (set.contains(i)) continue; 7 | pq.offer(i); 8 | set.add(i); 9 | if (pq.size() > 3) set.remove(pq.poll()); 10 | } 11 | while (pq.size() < 3 && pq.size() > 1) { 12 | pq.poll(); 13 | } 14 | return pq.peek(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-1/java/415_Add_Strings.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String addStrings(String num1, String num2) { 3 | StringBuilder sb = new StringBuilder(); 4 | int carry = 0; 5 | // condition is great 6 | // https://leetcode.com/problems/add-strings/discuss/90436/Straightforward-Java-8-main-lines-25ms 7 | for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){ 8 | int x = i < 0 ? 0 : num1.charAt(i) - '0'; 9 | int y = j < 0 ? 0 : num2.charAt(j) - '0'; 10 | sb.append((x + y + carry) % 10); 11 | carry = (x + y + carry) / 10; 12 | } 13 | return sb.reverse().toString(); 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/434_Number_of_Segments_in_a_String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/number-of-segments-in-a-string/solution/ 3 | // public int countSegments(String s) { 4 | // String trimmed = s.trim(); 5 | // if (trimmed.equals("")) { 6 | // return 0; 7 | // } 8 | // return trimmed.split("\\s+").length; 9 | // } 10 | public int countSegments(String s) { 11 | int segmentCount = 0; 12 | 13 | for (int i = 0; i < s.length(); i++) { 14 | if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') { 15 | segmentCount++; 16 | } 17 | } 18 | 19 | return segmentCount; 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/443_String_Compression.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int compress(char[] chars) { 3 | // https://leetcode.com/problems/string-compression/solution/ 4 | int anchor = 0, write = 0; 5 | for (int read = 0; read < chars.length; read++) { 6 | if (read + 1 == chars.length || chars[read + 1] != chars[read]) { 7 | chars[write++] = chars[anchor]; 8 | if (read > anchor) { 9 | for (char c: ("" + (read - anchor + 1)).toCharArray()) { 10 | chars[write++] = c; 11 | } 12 | } 13 | anchor = read + 1; 14 | } 15 | } 16 | return write; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/448_Find_All_Numbers_Disappeared_in_an_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution 3 | public List findDisappearedNumbers(int[] nums) { 4 | List ret = new ArrayList(); 5 | 6 | for(int i = 0; i < nums.length; i++) { 7 | int val = Math.abs(nums[i]) - 1; 8 | if(nums[val] > 0) { 9 | nums[val] = -nums[val]; 10 | } 11 | } 12 | 13 | for(int i = 0; i < nums.length; i++) { 14 | if(nums[i] > 0) { 15 | ret.add(i+1); 16 | } 17 | } 18 | return ret; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-1/java/453_Minimum_Moves_to_Equal_Array_Elements.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Collections; 3 | 4 | class Solution { 5 | public int minMoves(int[] nums) { 6 | if (nums.length == 0) return 0; 7 | Arrays.sort(nums); 8 | int min_num = nums[0]; 9 | int ans = 0; 10 | for (int num : nums) { 11 | ans += num - min_num; 12 | } 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/458_Poor_Pigs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 3 | int n = minutesToTest / minutesToDie + 1; 4 | int pigs = 0; 5 | while (Math.pow(n, pigs) < buckets) pigs++; 6 | return pigs; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /leetcode-part-1/java/461_Hamming_Distance.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hammingDistance(int x, int y) { 3 | return Integer.bitCount(x ^ y); 4 | } 5 | } -------------------------------------------------------------------------------- /leetcode-part-1/java/482_License_Key_Formatting.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String licenseKeyFormatting(String s, int k) { 3 | // https://leetcode.com/problems/license-key-formatting/discuss/96512/Java-5-lines-clean-solution 4 | StringBuilder sb = new StringBuilder(); 5 | for (int i = s.length() - 1; i >= 0; i--) 6 | if (s.charAt(i) != '-') 7 | sb.append(sb.length() % (k + 1) == k ? '-' : "").append(s.charAt(i)); 8 | return sb.reverse().toString().toUpperCase(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /leetcode-part-1/java/485_Max_Consecutive_Ones.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMaxConsecutiveOnes(int[] nums) { 3 | int ans = 0; 4 | int curr = 0; 5 | for (int i = 0; i < nums.length; i++) { 6 | if (nums[i] == 1) { 7 | // Add 1 when encounter 1 8 | curr++; 9 | if (curr > ans) ans = curr; 10 | } else { 11 | // Set to 0 when encounter 0 12 | curr = 0; 13 | } 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-1/java/509_Fibonacci_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /*public int fib(int N) { 3 | // Recursively, O(n) 4 | if (N == 0) return 0; 5 | if (N == 1) return 1; 6 | return fib(N - 1) + fib(N - 2); 7 | }*/ 8 | 9 | private List memo; 10 | 11 | public Solution() { 12 | memo = new ArrayList(); 13 | memo.add(0); 14 | memo.add(1); 15 | } 16 | 17 | public int fib(int N) { 18 | // Dp with memo, O(n) 19 | if (N < memo.size()) return memo.get(N); 20 | for (int i = memo.size(); i <= N; i++) { 21 | memo.add(memo.get(i - 1) + memo.get(i - 2)); 22 | } 23 | return memo.get(N); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode-part-1/java/541_Reverse_String_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseStr(String s, int k) { 3 | // https://leetcode.com/problems/reverse-string-ii/solution/ 4 | char[] a = s.toCharArray(); 5 | for (int start = 0; start < a.length; start += 2 * k) { 6 | int i = start, j = Math.min(start + k - 1, a.length - 1); 7 | // Reverse from i to j 8 | while (i < j) { 9 | char tmp = a[i]; 10 | a[i++] = a[j]; 11 | a[j--] = tmp; 12 | } 13 | } 14 | return new String(a); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-1/java/543_Diameter_of_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // https://leetcode.com/problems/diameter-of-binary-tree/solution/ 3 | int ans; 4 | public int diameterOfBinaryTree(TreeNode root) { 5 | ans = 1; 6 | depth(root); 7 | return ans - 1; 8 | } 9 | public int depth(TreeNode node) { 10 | if (node == null) return 0; 11 | int L = depth(node.left); 12 | int R = depth(node.right); 13 | ans = Math.max(ans, L+R+1); 14 | return Math.max(L, R) + 1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-1/java/557_Reverse_Words_in_a_String_III.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseWords(String s) { 3 | String words[] = s.split(" "); 4 | StringBuilder ans = new StringBuilder(); 5 | for (String word: words) 6 | ans.append(new StringBuffer(word).reverse().toString() + " "); 7 | return ans.toString().trim(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /leetcode-part-1/java/674_Longest_Continuous_Increasing_Subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findLengthOfLCIS(int[] nums) { 3 | if (nums.length == 0) return 0; 4 | int curr = 1, ans = 1; 5 | for (int i = 0; i < nums.length - 1; i++) { 6 | if (nums[i] < nums[i + 1]) { 7 | curr ++; 8 | if (curr >= ans) ans = curr; 9 | } else { 10 | curr = 1; 11 | } 12 | } 13 | return ans; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /leetcode-part-1/java/680_Valid_Palindrome_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindromeRange(String s, int i, int j) { 3 | for (int k = i; k <= i + (j - i) / 2; k++) { 4 | if (s.charAt(k) != s.charAt(j - k + i)) return false; 5 | } 6 | return true; 7 | } 8 | public boolean validPalindrome(String s) { 9 | for (int i = 0; i < s.length() / 2; i++) { 10 | if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { 11 | // Not equal 12 | int j = s.length() - 1 - i; 13 | // delete left or right 14 | return (isPalindromeRange(s, i + 1, j) || 15 | isPalindromeRange(s, i, j - 1)); 16 | } 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-1/java/709_To_Lower_Case.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String toLowerCase(String str) { 3 | return str.toLowerCase(); 4 | } 5 | 6 | /*public String toLowerCase(String str) { 7 | char[] a = str.toCharArray(); 8 | for (int i = 0; i < a.length; i++) 9 | if ('A' <= a[i] && a[i] <= 'Z') 10 | a[i] = (char) (a[i] - 'A' + 'a'); 11 | return new String(a); 12 | }*/ 13 | } 14 | -------------------------------------------------------------------------------- /leetcode-part-1/java/724_Find_Pivot_Index.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int pivotIndex(int[] nums) { 3 | int totalsum = 0, leftsum = 0; 4 | // Compute total sum 5 | for (int i = 0; i < nums.length; i++) totalsum += nums[i]; 6 | // Check leftsum == rightsum 7 | for (int i = 0; i < nums.length; i++) { 8 | if (leftsum == totalsum - leftsum - nums[i]) return i; 9 | leftsum += nums[i]; 10 | } 11 | return -1; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode-part-1/java/760_Find_Anagram_Mappings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] anagramMappings(int[] A, int[] B) { 3 | int[] ans = new int[A.length]; 4 | HashMap valIndex = new HashMap<>(); 5 | for (int i = 0; i < B.length; i++) valIndex.put(B[i], i); 6 | for (int i = 0; i < A.length; i++) ans[i] = valIndex.get(A[i]); 7 | return ans; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /leetcode-part-1/java/766_Toeplitz_Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isToeplitzMatrix(int[][] matrix) { 3 | // Start from second line and column 4 | for (int r = 1; r < matrix.length; ++r) 5 | for (int c = 1; c < matrix[0].length; ++c) 6 | // Check step by step 7 | if (matrix[r-1][c-1] != matrix[r][c]) 8 | return false; 9 | return true; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode-part-1/java/771_Jewels_and_Stones.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | class Solution { 4 | public int numJewelsInStones(String J, String S) { 5 | int result = 0; 6 | HashSet jHash = new HashSet<>(); 7 | for (int j = 0; j < J.length(); j++) { 8 | jHash.add(J.charAt(j)); 9 | } 10 | for (int s = 0; s < S.length(); s++) { 11 | if (jHash.contains(S.charAt(s))) { 12 | result++; 13 | } 14 | } 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-1/java/832_Flipping_an_Image.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] flipAndInvertImage(int[][] A) { 3 | int C = A[0].length; 4 | for (int[] row: A) 5 | for (int i = 0; i < (C + 1) / 2; ++i) { 6 | int tmp = row[i] ^ 1; 7 | row[i] = row[C - 1 - i] ^ 1; 8 | row[C - 1 - i] = tmp; 9 | } 10 | 11 | return A; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode-part-1/java/852_Peak_Index_in_a_Mountain_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // public int peakIndexInMountainArray(int[] A) { 3 | // int i = 0; 4 | // for (; A[i] < A[i + 1]; i++); 5 | // return i; 6 | // } 7 | 8 | public int peakIndexInMountainArray(int[] A) { 9 | int lo = 0, hi = A.length - 1; 10 | while (lo < hi) { 11 | int mid = (lo + hi) / 2; 12 | if (A[mid] < A[mid + 1]) lo = mid + 1; 13 | else hi = mid; 14 | } 15 | return lo; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-1/java/867_Transpose_Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] transpose(int[][] A) { 3 | int R = A.length, C = A[0].length; 4 | int[][] ans = new int[C][R]; 5 | for (int r = 0; r < R; ++r) 6 | for (int c = 0; c < C; ++c) { 7 | ans[c][r] = A[r][c]; 8 | } 9 | return ans; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode-part-1/java/872_Leaf-Similar_Trees.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean leafSimilar(TreeNode root1, TreeNode root2) { 3 | List leaves1 = new ArrayList(); 4 | List leaves2 = new ArrayList(); 5 | dfs(root1, leaves1); 6 | dfs(root2, leaves2); 7 | return leaves1.equals(leaves2); 8 | } 9 | 10 | public void dfs(TreeNode node, List leafValues) { 11 | if (node != null) { 12 | if (node.left == null && node.right == null) 13 | leafValues.add(node.val); 14 | dfs(node.left, leafValues); 15 | dfs(node.right, leafValues); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode-part-1/java/929_Unique_Email_Addresses.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | class Solution { 4 | public int numUniqueEmails(String[] emails) { 5 | HashSet emailSet = new HashSet<>(); 6 | for (String email: emails) { 7 | String firstSplit[] = email.split("@"); 8 | String secondSplit[] = firstSplit[0].replaceAll(".", "").split("[+]"); 9 | emailSet.add(secondSplit[0] + firstSplit[1]); 10 | } 11 | return emailSet.size(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode-part-1/java/933_Number_of_Recent_Calls.java: -------------------------------------------------------------------------------- 1 | class RecentCounter { 2 | Queue q; 3 | public RecentCounter() { 4 | q = new LinkedList(); 5 | } 6 | 7 | public int ping(int t) { 8 | q.add(t); 9 | while (q.peek() < t - 3000) 10 | q.poll(); 11 | return q.size(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode-part-1/java/937_Reorder_Log_Files.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | class Solution { 4 | public String[] reorderLogFiles(String[] logs) { 5 | Arrays.sort(logs, (log1, log2) -> { 6 | String[] split1 = log1.split(" ", 2); 7 | String[] split2 = log2.split(" ", 2); 8 | boolean isDigit1 = Character.isDigit(split1[1].charAt(0)); 9 | boolean isDigit2 = Character.isDigit(split2[1].charAt(0)); 10 | if (!isDigit1 && !isDigit2) { 11 | int cmp = split1[1].compareTo(split2[1]); 12 | if (cmp != 0) return cmp; 13 | return split1[0].compareTo(split2[0]); 14 | } 15 | return isDigit1 ? (isDigit2 ? 0 : 1) : -1; 16 | }); 17 | return logs; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode-part-1/java/961_N-Repeated_Element_in_Size_2N_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int repeatedNTimes(int[] A) { 3 | HashMap hash = new HashMap<>(); 4 | int ans = A[0]; 5 | for (int n: A) { 6 | int count = hash.getOrDefault(n, 0) + 1; 7 | hash.put(n, count); 8 | if (count >= hash.get(ans)) ans = n; 9 | } 10 | return ans; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /leetcode-part-1/python/011_Container_With_Most_Water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | # Two points 4 | left, right = 0, len(height) - 1 5 | result = 0 6 | while left < right: 7 | result = max(min(height[left], height[right]) * (right - left), result) 8 | if height[left] > height[right]: 9 | # remove right 10 | right -= 1 11 | else: 12 | # remove left 13 | left += 1 14 | return result 15 | -------------------------------------------------------------------------------- /leetcode-part-1/python/038_Count_and_Say.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n): 3 | """ 4 | :type n: int 5 | :rtype: str 6 | """ 7 | if n == 1: 8 | return '1' 9 | x = '1' 10 | while n > 1: 11 | # each round, read itself 12 | x = self.count(x) 13 | n -= 1 14 | return x 15 | 16 | def count(self, x): 17 | m = list(x) 18 | res = [] 19 | m.append(None) 20 | i , j = 0 , 0 21 | while i < len(m) - 1: 22 | j += 1 23 | if m[j] != m[i]: 24 | # note j - i is the count of m[i] 25 | res += [j - i, m[i]] 26 | i = j 27 | return ''.join(str(s) for s in res) -------------------------------------------------------------------------------- /leetcode-part-1/python/045_Jump_Game_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) <= 1: 8 | return 0 9 | end = 0 + nums[0] 10 | start = 0 11 | step = 1 12 | maxDis = 0 + nums[0] 13 | while end < len(nums) - 1: 14 | for i in range(start + 1, end + 1): 15 | # greedy 16 | maxDis = max(maxDis, nums[i] + i) 17 | start = end 18 | end = maxDis 19 | step += 1 20 | return step 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/055_Jump_Game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canJump(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | # greedy 8 | # https://leetcode.com/articles/jump-game/ 9 | length = len(nums) 10 | begin = length - 1 11 | for i in reversed(range(length - 1)): 12 | if i + nums[i] >= begin: 13 | begin = i 14 | return not begin -------------------------------------------------------------------------------- /leetcode-part-1/python/058_Length_of_Last_Word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLastWord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | if len(s) == 0: 8 | return 0 9 | temp = s.split(' ') 10 | temp = [t for t in temp if len(t) > 0] 11 | if len(temp) == 0: 12 | return 0 13 | else: 14 | return len(temp[-1]) -------------------------------------------------------------------------------- /leetcode-part-1/python/059_Spiral_Matrix_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generateMatrix(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[List[int]] 6 | """ 7 | res = [[0] * n for _ in range(n)] 8 | pos = [0, 0] 9 | move = (0, 1) 10 | for index in range(1, n * n + 1): 11 | res[pos[0]][pos[1]] = index 12 | if res[(pos[0] + move[0]) % n][(pos[1] + move[1]) % n] > 0: 13 | # (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0) 14 | move = (move[1], -1 * move[0]) 15 | pos[0] = pos[0] + move[0] 16 | pos[1] = pos[1] + move[1] 17 | return res 18 | 19 | if __name__ == '__main__': 20 | # begin 21 | s = Solution() 22 | print s.generateMatrix(2) -------------------------------------------------------------------------------- /leetcode-part-1/python/062_Unique_Paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m, n): 3 | """ 4 | :type m: int 5 | :type n: int 6 | :rtype: int 7 | """ 8 | dmap = [[0] * n for _ in range(m)] 9 | for i in range(m): 10 | dmap[i][0] = 1 11 | for j in range(n): 12 | dmap[0][j] = 1 13 | for i in range(1, m): 14 | for j in range(1, n): 15 | l = u = 0 16 | if i-1 >= 0: 17 | u = dmap[i-1][j] 18 | if j-1>= 0: 19 | l = dmap[i][j-1] 20 | dmap[i][j] = l + u 21 | return dmap[m-1][n-1] 22 | -------------------------------------------------------------------------------- /leetcode-part-1/python/071_Simplify_Path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def simplifyPath(self, path): 3 | """ 4 | :type path: str 5 | :rtype: str 6 | """ 7 | result = [] 8 | plist = path.split('/') 9 | for pos in plist: 10 | if pos: 11 | if pos == '..': 12 | try: 13 | # up one level 14 | result.pop() 15 | except: 16 | # arrive top level 17 | result = [] 18 | elif pos != '.': 19 | result.append(pos) 20 | return '/'+'/'.join(result) -------------------------------------------------------------------------------- /leetcode-part-1/python/089_Gray_Code.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def grayCode(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[int] 6 | """ 7 | # https://leetcode.com/discuss/86617/6-line-java-solution-very-concise 8 | res = [0] 9 | for i in range(n): 10 | for j in reversed(range(len(res))): 11 | res.append(res[j] + (1 << i)) 12 | return res 13 | 14 | 15 | # def count_one(self, num): 16 | # count = 0 17 | # while num: 18 | # num &= (num - 1) 19 | # count += 1 20 | # return count 21 | 22 | if __name__ == "__main__": 23 | s = Solution() 24 | print s.grayCode(2) 25 | 26 | -------------------------------------------------------------------------------- /leetcode-part-1/python/096_Unique_Binary_Search_Trees.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numTrees(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/discuss/86650/fantastic-clean-java-dp-solution-with-detail-explaination 8 | dp = [0] * (n + 1) 9 | dp[0] = 1 10 | dp[1] = 1 11 | for level in range(2, n + 1): 12 | for root in range(1, level + 1): 13 | dp[level] += dp[level - root] * dp[root - 1] 14 | return dp[n] -------------------------------------------------------------------------------- /leetcode-part-1/python/100_Same_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def isSameTree(self, p, q): 10 | """ 11 | :type p: TreeNode 12 | :type q: TreeNode 13 | :rtype: bool 14 | """ 15 | if p == q: 16 | return True 17 | try: 18 | left = right = True 19 | if p.val == q.val: 20 | left = self.isSameTree(p.left, q.left) 21 | right = self.isSameTree(p.right, q.right) 22 | return (left and right) 23 | except: 24 | return False 25 | return False -------------------------------------------------------------------------------- /leetcode-part-1/python/104_Maximum_Depth_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def maxDepth(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if root is None: 15 | return 0 16 | ld = self.maxDepth(root.left) 17 | rd = self.maxDepth(root.right) 18 | return 1 + max(ld, rd) 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/1108_Defanging_an_IP_Address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | # replace 4 | return address.replace('.', '[.]') 5 | # def defangIPaddr(self, address: str) -> str: 6 | # # split and join 7 | # return '[.]'.join(address.split('.')) 8 | # def defangIPaddr(self, address: str) -> str: 9 | # # replace 10 | # return re.sub('\.', '[.]', address) 11 | # def defangIPaddr(self, address: str) -> str: 12 | # return ''.join('[.]' if c == '.' else c for c in address) 13 | -------------------------------------------------------------------------------- /leetcode-part-1/python/112_Path_Sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def hasPathSum(self, root, sum): 10 | """ 11 | :type root: TreeNode 12 | :type sum: int 13 | :rtype: bool 14 | """ 15 | if root is None: 16 | return False 17 | sum = sum - root.val 18 | if sum == 0 and root.left is None and root.right is None: 19 | return True 20 | # check left 21 | left = self.hasPathSum(root.left, sum) 22 | # check right 23 | right = self.hasPathSum(root.right, sum) 24 | return (left or right) 25 | -------------------------------------------------------------------------------- /leetcode-part-1/python/115_Distinct_Subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numDistinct(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: int 7 | """ 8 | # https://discuss.leetcode.com/topic/51131/space-o-mn-and-o-n-python-solutions 9 | dp = [[0 for j in xrange(0, len(t) + 1)] for i in xrange(0, len(s) + 1)] 10 | for j in xrange(1, len(t) + 1): 11 | dp[0][j] = 0 12 | for i in xrange(1, len(s) + 1): 13 | dp[i][0] = 1 14 | dp[0][0] = 1 15 | for i in xrange(1, len(s) + 1): 16 | for j in xrange(1, len(t) + 1): 17 | dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] * (s[i - 1] == t[j - 1]) 18 | 19 | return dp[-1][-1] 20 | -------------------------------------------------------------------------------- /leetcode-part-1/python/118_Pascal's_Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows): 3 | """ 4 | :type numRows: int 5 | :rtype: List[List[int]] 6 | """ 7 | result = [] 8 | for i in range(numRows): 9 | result.append([0] * (i + 1)) 10 | for i in range(numRows): 11 | for j in range(i + 1): 12 | if j == 0 or j == i: 13 | result[i][j] = 1 14 | else: 15 | result[i][j] = result[i - 1][j - 1] + result[i - 1][j] 16 | return result 17 | -------------------------------------------------------------------------------- /leetcode-part-1/python/119_Pascal's_Triangle_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getRow(self, rowIndex): 3 | """ 4 | :type rowIndex: int 5 | :rtype: List[int] 6 | """ 7 | last = [1] 8 | res = [1] 9 | for r in range(1, rowIndex + 1): 10 | res = [1] 11 | for index in range(len(last) - 1): 12 | res.append(last[index] + last[index + 1]) 13 | res.append(1) 14 | last = res 15 | return res 16 | 17 | if __name__ == "__main__": 18 | s = Solution() 19 | print s.getRow(3) -------------------------------------------------------------------------------- /leetcode-part-1/python/120_Triangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minimumTotal(self, triangle): 3 | """ 4 | :type triangle: List[List[int]] 5 | :rtype: int 6 | """ 7 | if triangle is None or len(triangle) == 0: 8 | return 0 9 | ls = len(triangle) 10 | dp = [0] * ls 11 | dp[0] = triangle[0][0] 12 | for i in range(1, ls): 13 | # note that dp should be updated in reversed order 14 | dp[i] = dp[i - 1] + triangle[i][i] 15 | for j in reversed(range(1, i)): 16 | dp[j] = min(dp[j - 1] + triangle[i][j], dp[j] + triangle[i][j]) 17 | dp[0] = dp[0] + triangle[i][0] 18 | return min(dp) 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/121_Best_Time_to_Buy_and_Sell_Stock.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | length = len(prices) 8 | if length == 0: 9 | return 0 10 | max_profit, low = 0, prices[0] 11 | for i in range(1, length): 12 | if low > prices[i]: 13 | low = prices[i] 14 | else: 15 | temp = prices[i] - low 16 | if temp > max_profit: 17 | max_profit = temp 18 | return max_profit -------------------------------------------------------------------------------- /leetcode-part-1/python/122_Best_Time_to_Buy_and_Sell_Stock_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | # sum of prices[i + 1] - prices[i], if prices[i + 1] > prices[i] 8 | return sum([y - x for x, y in zip(prices[0:-1], prices[1:]) if x < y]) 9 | -------------------------------------------------------------------------------- /leetcode-part-1/python/125_Valid_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | alnum_s = [t.lower() for t in s if t.isalnum()] 8 | ls = len(alnum_s) 9 | if ls <= 1: 10 | return True 11 | mid = ls / 2 12 | for i in range(mid): 13 | if alnum_s[i] != alnum_s[ls - 1 - i]: 14 | return False 15 | return True -------------------------------------------------------------------------------- /leetcode-part-1/python/1304_Find_N_Unique_Integers_Sum_up_to_Zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumZero(self, n: int) -> List[int]: 3 | prefix_sum = 0 4 | res = [] 5 | # 1, n-1 6 | for i in range(1, n): 7 | res.append(i) 8 | prefix_sum = prefix_sum + i 9 | # sum(from 1 to n-1) 10 | res.append(-prefix_sum) 11 | return res 12 | 13 | # def sumZero(self, n: int) -> List[int]: 14 | # # 1,n-1 15 | # prefix = list(range(1, n)) 16 | # # sum(from 1 to n-1) 17 | # return prefix + [-sum(prefix)] 18 | -------------------------------------------------------------------------------- /leetcode-part-1/python/1310_XOR_Queries_of_a_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: 3 | pref = [0] 4 | # Compute accumulated xor from head 5 | for e in arr: 6 | pref.append(e ^ pref[-1]) 7 | ans = [] 8 | # query result equal to xor[0, l] xor x[0, r] 9 | for [l, r] in queries: 10 | ans.append(pref[r+1] ^ pref[l]) 11 | return ans 12 | 13 | # def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: 14 | # for i in range(len(arr) - 1): 15 | # arr[i + 1] ^= arr[i] 16 | # return [arr[j] ^ arr[i - 1] if i else arr[j] for i, j in queries] 17 | -------------------------------------------------------------------------------- /leetcode-part-1/python/1323_Maximum_69_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | # Replace first 6 with 9 if exists 4 | return(str(num).replace('6', '9', 1)) 5 | -------------------------------------------------------------------------------- /leetcode-part-1/python/135_Candy.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def candy(self, ratings): 3 | """ 4 | :type ratings: List[int] 5 | :rtype: int 6 | """ 7 | # https://discuss.leetcode.com/topic/5243/a-simple-solution 8 | if ratings is None or len(ratings) == 0: 9 | return 0 10 | ls = len(ratings) 11 | num = [1] * ls 12 | for i in range(1, ls): 13 | if ratings[i] > ratings[i - 1]: 14 | num[i] = num[i - 1] + 1 15 | for i in range(ls - 1, 0, -1): 16 | if ratings[i - 1] > ratings[i]: 17 | num[i - 1] = max(num[i] + 1, num[i - 1]) 18 | return sum(num) 19 | 20 | -------------------------------------------------------------------------------- /leetcode-part-1/python/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts_Solution.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. 3 | The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. 4 | Input: n = 4 5 | Output: "pppz" 6 | ''' 7 | class Solution: 8 | def generateTheString(self, n: int) -> str: 9 | if n%2==0: 10 | return "a" * (n-1) + "b" 11 | else: 12 | return "a" * n 13 | -------------------------------------------------------------------------------- /leetcode-part-1/python/1480_Running_Sum_of_1d_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def runningSum(self, nums: List[int]) -> List[int]: 3 | if nums is None or len(nums) == 0: 4 | return nums 5 | for i in range(1, len(nums)): 6 | nums[i] += nums[i-1] 7 | return nums 8 | 9 | # def runningSum(self, nums: List[int]) -> List[int]: 10 | # # accumulate method 11 | # return accumulate(nums) 12 | -------------------------------------------------------------------------------- /leetcode-part-1/python/150_Evaluate_Reverse_Polish_Notation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def evalRPN(self, tokens): 3 | """ 4 | :type tokens: List[str] 5 | :rtype: int 6 | """ 7 | stack = [] 8 | for t in tokens: 9 | try: 10 | temp = int(t) 11 | stack.append(temp) 12 | except: 13 | b = stack.pop() 14 | a = stack.pop() 15 | if t == "+": 16 | a += b 17 | elif t == "-": 18 | a -= b 19 | elif t == "*": 20 | a *= b 21 | else: 22 | a = int(a * 1.0 / b) 23 | stack.append(a) 24 | return stack[-1] -------------------------------------------------------------------------------- /leetcode-part-1/python/152_Maximum_Product_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProduct(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if nums is None or len(nums) == 0: 8 | return 0 9 | max_here = min_here = max_so_far = nums[0] 10 | for i in range(1, len(nums)): 11 | mx, mn = max_here, min_here 12 | max_here = max(max(mx * nums[i], nums[i]), mn * nums[i]) 13 | min_here = min(min(mx * nums[i], nums[i]), mn * nums[i]) 14 | max_so_far = max(max_here, max_so_far) 15 | return max_so_far -------------------------------------------------------------------------------- /leetcode-part-1/python/157_Read_N_Characters_Given_Read4.py: -------------------------------------------------------------------------------- 1 | # The read4 API is already defined for you. 2 | # @param buf, a list of characters 3 | # @return an integer 4 | # def read4(buf): 5 | 6 | class Solution(object): 7 | def read(self, buf, n): 8 | """ 9 | :type buf: Destination buffer (List[str]) 10 | :type n: Maximum number of characters to read (int) 11 | :rtype: The number of characters read (int) 12 | """ 13 | pos, eof = 0, False 14 | while not eof and pos < n: 15 | buffer = [''] * 4 16 | sz = read4(buffer) 17 | if sz < 4: 18 | eof = True 19 | for i in range(sz): 20 | buf[pos + i] = buffer[i] 21 | pos += min(n - pos, sz) 22 | return pos -------------------------------------------------------------------------------- /leetcode-part-1/python/159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLongestSubstringTwoDistinct(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | i, j, maxLen = 0, -1, 0 8 | # i for start, k for end, j for latest pos contains different character from k 9 | for k in range(1, len(s)): 10 | if s[k] == s[k - 1]: 11 | continue 12 | if j >= 0 and s[j] != s[k]: 13 | maxLen = max(k - i, maxLen) 14 | # update i 15 | i = j + 1 16 | # update 17 | j = k - 1 18 | return max(len(s) - i, maxLen) -------------------------------------------------------------------------------- /leetcode-part-1/python/162_Find_Peak_Element.py: -------------------------------------------------------------------------------- 1 | # class Solution(object): 2 | # def findPeakElement(self, nums): 3 | # """ 4 | # :type nums: List[int] 5 | # :rtype: int 6 | # """ 7 | 8 | class Solution(object): 9 | def findPeakElement(self, nums): 10 | # https://leetcode.com/discuss/88467/tricky-problem-tricky-solution 11 | # note that num[-1] = num[n] = -∞ 12 | start, end = 0, len(nums) - 1 13 | while start < end: 14 | mid = (start + end) / 2 15 | if nums[mid] < nums[mid+1]: 16 | start= mid + 1 17 | else: 18 | end = mid 19 | return start 20 | -------------------------------------------------------------------------------- /leetcode-part-1/python/163_Missing_Ranges.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMissingRanges(self, nums, lower, upper): 3 | """ 4 | :type nums: List[int] 5 | :type lower: int 6 | :type upper: int 7 | :rtype: List[str] 8 | """ 9 | ranges = [] 10 | prev = lower - 1 11 | for i in range(len(nums) + 1): 12 | if i == len(nums): 13 | curr = upper + 1 14 | else: 15 | curr = nums[i] 16 | if curr - prev > 2: 17 | ranges.append("%d->%d" % (prev + 1, curr - 1)) 18 | elif curr - prev == 2: 19 | ranges.append("%d" % (prev + 1)) 20 | prev = curr 21 | return ranges -------------------------------------------------------------------------------- /leetcode-part-1/python/167_Two_Sum_II_Input_array_is_sorted.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, numbers, target): 3 | """ 4 | :type numbers: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | # Two Points 9 | begin, end = 0, len(numbers) - 1 10 | while begin < end: 11 | curr = numbers[begin] + numbers[end] 12 | if curr == target: 13 | return [begin + 1, end + 1] 14 | elif curr < target: 15 | begin += 1 16 | else: 17 | end -= 1 18 | 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/168_Excel_Sheet_Column_Title.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convertToTitle(self, n: int) -> str: 3 | res = "" 4 | while n > 0: 5 | n -= 1 6 | res = chr(65 + n % 26) + res 7 | n //= 26 8 | return res 9 | -------------------------------------------------------------------------------- /leetcode-part-1/python/179_Largest_Number.py: -------------------------------------------------------------------------------- 1 | class LargerNumKey(str): 2 | def __lt__(x, y): 3 | return x + y > y + x 4 | 5 | 6 | class Solution: 7 | def largestNumber(self, nums): 8 | largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey)) 9 | return '0' if largest_num[0] == '0' else largest_num 10 | -------------------------------------------------------------------------------- /leetcode-part-1/python/186_Reverse_Words_in_a_String_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: a list of 1 length strings (List[str]) 5 | :rtype: nothing 6 | """ 7 | ls, pos = len(s), 0 8 | if s is None or ls == 0: 9 | return 10 | self.reverse(s, 0, ls) 11 | for i in range(ls + 1): 12 | if i == ls or s[i] == ' ': 13 | self.reverse(s, pos, i) 14 | pos = i + 1 15 | 16 | def reverse(self, array_s, begin, end): 17 | for i in range((end - begin) / 2): 18 | array_s[begin + i], array_s[end - i - 1] = array_s[end - i - 1], array_s[begin + i] 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/191_Number_of_1_Bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def hammingWeight(self, n): 3 | # """ 4 | # :type n: int 5 | # :rtype: int 6 | # """ 7 | # # using bin 8 | # s_n = bin(n)[2:] 9 | # return s_n.count('1') 10 | 11 | def hammingWeight(self, n): 12 | """ 13 | :type n: int 14 | :rtype: int 15 | """ 16 | # https://leetcode.com/articles/number-1-bits/ 17 | count = 0 18 | while n: 19 | n &= n - 1 20 | count += 1 21 | return count 22 | -------------------------------------------------------------------------------- /leetcode-part-1/python/202_Happy_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isHappy(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | # https://en.wikipedia.org/wiki/Happy_number 8 | seen_numbers = set() 9 | while n > 1 and n not in seen_numbers: 10 | seen_numbers.add(n) 11 | n = sum(map(lambda x: int(x) * int(x), list(str(n)))) 12 | return n == 1 -------------------------------------------------------------------------------- /leetcode-part-1/python/204_Count_Primes.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPrimes(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity 8 | isPrime = [True] * n 9 | for i in xrange(2, n): 10 | if i * i >= n: 11 | break 12 | if not isPrime[i]: 13 | continue 14 | for j in xrange(i * i, n, i): 15 | isPrime[j] = False 16 | count = 0 17 | for i in xrange(2, n): 18 | if isPrime[i]: 19 | count += 1 20 | return count 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/216_Combination_Sum_III.py: -------------------------------------------------------------------------------- 1 | import itertools as it 2 | class Solution(object): 3 | def combinationSum3(self, k, n): 4 | """ 5 | :type k: int 6 | :type n: int 7 | :rtype: List[List[int]] 8 | """ 9 | return list(it.ifilter(lambda x: sum(x) == n, list(it.combinations(range(1, 10), k)))) 10 | -------------------------------------------------------------------------------- /leetcode-part-1/python/217_Contains_Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def containsDuplicate(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: bool 6 | """ 7 | # use set to check duplicate 8 | return len(nums) != len(set(nums)) 9 | 10 | # def containsDuplicate(self, nums): 11 | # nums.sort() 12 | # for i in range(len(nums) - 1): 13 | # if nums[i] == nums[i + 1]: 14 | # return True 15 | # return False -------------------------------------------------------------------------------- /leetcode-part-1/python/223_Rectangle Area.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def computeArea(self, A, B, C, D, E, F, G, H): 3 | """ 4 | :type A: int 5 | :type B: int 6 | :type C: int 7 | :type D: int 8 | :type E: int 9 | :type F: int 10 | :type G: int 11 | :type H: int 12 | :rtype: int 13 | """ 14 | # sum of areas of two rectangles 15 | result = (C - A) * (D - B) + (G - E) * (H - F) 16 | # no overlap 17 | if (C <= E or G <= A or H <= B or D <= F): 18 | return result 19 | # overlap length on x 20 | dx = min(C, G) - max(A, E) 21 | # overlap length on y 22 | dy = min(D, H) - max(B, F) 23 | return result - dx * dy 24 | -------------------------------------------------------------------------------- /leetcode-part-1/python/231_Power_of_Two.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfTwo(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | if n < 0: 8 | return False 9 | bin_str = bin(n) 10 | return sum(map(lambda x: int(x), list(bin_str[2:]))) == 1 -------------------------------------------------------------------------------- /leetcode-part-1/python/237_Delete_Node_in_a_Linked_List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteNode(self, node): 9 | """ 10 | :type node: ListNode 11 | :rtype: void Do not return anything, modify node in-place instead. 12 | """ 13 | node.val = node.next.val 14 | node.next = node.next.next -------------------------------------------------------------------------------- /leetcode-part-1/python/238_Product_of_Array_Except_Self.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def productExceptSelf(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans = [1] * len(nums) 8 | for i in range(1, len(nums)): 9 | ans[i] = ans[i - 1] * nums[i - 1] 10 | right = 1 11 | for i in range(len(nums) - 1, -1, -1): 12 | ans[i] *= right 13 | right *= nums[i] 14 | return ans 15 | -------------------------------------------------------------------------------- /leetcode-part-1/python/246_Strobogrammatic_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isStrobogrammatic(self, num): 3 | """ 4 | :type num: str 5 | :rtype: bool 6 | """ 7 | # hash table 8 | dic = {'0':'0', '6':'9', '9': '6', '1' :'1', '8': '8'} 9 | temp_s = '' 10 | for c in num[::-1]: 11 | if c not in dic: 12 | return False 13 | temp_s += dic[c] 14 | if int(temp_s) == int(num): 15 | return True 16 | return False 17 | 18 | # def isStrobogrammatic(self, num): 19 | # # https://discuss.leetcode.com/topic/20840/1-liners-python 20 | # return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)/2+1)) 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/258_Add_Digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def addDigits(self, num): 3 | """ 4 | :type num: int 5 | :rtype: int 6 | """ 7 | # https: // en.wikipedia.org / wiki / Digital_root 8 | if num < 10: 9 | return num 10 | return num - ((num - 1) / 9) * 9 -------------------------------------------------------------------------------- /leetcode-part-1/python/266_Palindrome_Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPermutePalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | dic = {} 8 | for c in s: 9 | dic[c] = dic.get(c, 0) + 1 10 | odd, even = 0, 0 11 | for c in dic: 12 | if dic[c] % 2 == 0: 13 | even += 1 14 | else: 15 | odd += 1 16 | if odd <= 1: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/278_First_Bad_Version.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return a bool 4 | # def isBadVersion(version): 5 | 6 | class Solution(object): 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | left, right= 1, n 13 | while left < right: 14 | mid = (right + left) / 2 15 | if isBadVersion(mid): 16 | right = mid 17 | else: 18 | left = mid + 1 19 | return left -------------------------------------------------------------------------------- /leetcode-part-1/python/292_Nim_Game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canWinNim(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | return n % 4 != 0 -------------------------------------------------------------------------------- /leetcode-part-1/python/293_Flip_Game.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generatePossibleNextMoves(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[str] 6 | """ 7 | # return [s[:i] + "--" + s[i+2:] for i in range(len(s) - 1) if s[i] == s[i + 1] == "+"] 8 | res = [] 9 | if s is None or len(s) == 0: 10 | return res 11 | ls = len(s) 12 | for i in range(ls - 1): 13 | if s[i] == '+' and s[i + 1] == '+': 14 | res.append(s[:i] + '--' + s[i + 2:]) 15 | return res 16 | -------------------------------------------------------------------------------- /leetcode-part-1/python/326_Power_of_Three.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def isPowerOfThree(self, n): 3 | # """ 4 | # :type n: int 5 | # :rtype: bool 6 | # """ 7 | # import math 8 | # if n <= 0: 9 | # return False 10 | # # use round to check 11 | # log_res = round(math.log(n, 3), 10) 12 | # if log_res - int(log_res) > 0: 13 | # return False 14 | # return True 15 | 16 | def isPowerOfThree(self, n): 17 | max3pow = 1162261467 18 | if n <= 0 or n > max3pow: 19 | return False 20 | return max3pow % n == 0 -------------------------------------------------------------------------------- /leetcode-part-1/python/338_Counting_Bits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countBits(self, num): 3 | """ 4 | :type num: int 5 | :rtype: List[int] 6 | """ 7 | res = [0] * (num + 1) 8 | for i in range(1, num + 1): 9 | # res[left:last] + last bit 10 | res[i] = res[i >> 1] + (i & 1) 11 | return res 12 | 13 | -------------------------------------------------------------------------------- /leetcode-part-1/python/342_Power_of_Four.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfFour(self, num): 3 | """ 4 | :type num: int 5 | :rtype: bool 6 | """ 7 | # bin(4**0) '0b1' 8 | # bin(4**1) '0b100' 9 | # bin(4**2) '0b10000' 10 | # bin(4**3) '0b1000000' 11 | return num > 0 and num & (num-1) == 0 and len(bin(num)[3:]) % 2 == 0 -------------------------------------------------------------------------------- /leetcode-part-1/python/344_Reverse_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseString(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | # slice 8 | return s[::-1] -------------------------------------------------------------------------------- /leetcode-part-1/python/345_Reverse_Vowels_of_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseVowels(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | str_index = [] 8 | vowel = [] 9 | res = [] 10 | pos = -1 11 | for index, value in enumerate(s): 12 | if value in 'aeiouAEIOU': 13 | str_index.append(-1) 14 | vowel.append(value) 15 | else: 16 | str_index.append(index) 17 | for index in str_index: 18 | if index < 0: 19 | res.append(vowel[pos]) 20 | pos -= 1 21 | else: 22 | res.append(s[index]) 23 | return ''.join(res) 24 | 25 | -------------------------------------------------------------------------------- /leetcode-part-1/python/347_Top_K_Frequent_Elements.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def topKFrequent(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: List[int] 7 | """ 8 | counter = collections.Counter(nums) 9 | return [k for k,v in counter.most_common(k)] 10 | # return heapq.nlargest(k, count.keys(), key=count.get) 11 | -------------------------------------------------------------------------------- /leetcode-part-1/python/349_Intersection_of_Two_Arrays.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersection(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: List[int] 7 | """ 8 | # set 9 | return list(set(nums1) & set(nums2)) -------------------------------------------------------------------------------- /leetcode-part-1/python/350_Intersection_of_Two_Arrays_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersect(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: List[int] 7 | """ 8 | nums1.sort() 9 | nums2.sort() 10 | res = [] 11 | pos1 = pos2 = 0 12 | while pos1 < len(nums1) and pos2 < len(nums2): 13 | if nums1[pos1] == nums2[pos2]: 14 | res.append(nums1[pos1]) 15 | pos1 += 1 16 | pos2 += 1 17 | elif nums1[pos1] < nums2[pos2]: 18 | pos1 += 1 19 | else: 20 | pos2 += 1 21 | return res 22 | -------------------------------------------------------------------------------- /leetcode-part-1/python/370_Range_Addition.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getModifiedArray(self, length, updates): 3 | """ 4 | :type length: int 5 | :type updates: List[List[int]] 6 | :rtype: List[int] 7 | """ 8 | res = [0] * length 9 | # interval problem 10 | for t in updates: 11 | start, end, val = t 12 | res[start] += val 13 | if end < length - 1: 14 | res[end + 1] -= val 15 | # Cumulative sums 16 | for i in range(1, length): 17 | res[i] = res[i] + res[i - 1] 18 | return res 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/371_Sum_of_Two_Integers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | """ 4 | :type a: int 5 | :type b: int 6 | :rtype: int 7 | """ 8 | # https://leetcode.com/discuss/111582/java-simple-easy-understand-solution-with-explanation 9 | # in Python this problem is much different because of the negative number 10 | # https://leetcode.com/discuss/111705/one-positive-one-negative-case-successful-for-python-rules 11 | import ctypes 12 | sum = 0 13 | carry = ctypes.c_int32(b) 14 | while carry.value != 0: 15 | sum = a ^ carry.value 16 | carry = ctypes.c_int32(a & carry.value) 17 | carry.value <<= 1 18 | a = sum 19 | return sum -------------------------------------------------------------------------------- /leetcode-part-1/python/374_Guess_Number_Higher_or_Lower.py: -------------------------------------------------------------------------------- 1 | # The guess API is already defined for you. 2 | # @param num, your guess 3 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | # def guess(num): 5 | 6 | class Solution(object): 7 | def guessNumber(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | # binary search 13 | begin, end = 1, n 14 | while begin <= end: 15 | mid = (begin + end) / 2 16 | res = guess(mid) 17 | if res == 0: 18 | return mid 19 | elif res > 0: 20 | begin = mid + 1 21 | else: 22 | end = mid - 1 23 | -------------------------------------------------------------------------------- /leetcode-part-1/python/383_Ransom_Note.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canConstruct(self, ransomNote, magazine): 3 | """ 4 | :type ransomNote: str 5 | :type magazine: str 6 | :rtype: bool 7 | """ 8 | letter_map = {} 9 | for letter in magazine: 10 | letter_map[letter] = letter_map.get(letter, 0) + 1 11 | for letter in ransomNote: 12 | letter_map[letter] = letter_map.get(letter, 0) - 1 13 | if letter_map[letter] < 0: 14 | return False 15 | return True 16 | 17 | # def canConstruct(self, ransomNote, magazine): 18 | # return not collections.Counter(ransomNote) - collections.Counter(magazine) 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/387_First_Unique_Character_in_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstUniqChar(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | count_map = {} 8 | for c in s: 9 | count_map[c] = count_map.get(c, 0) + 1 10 | for i, c in enumerate(s): 11 | if count_map[c] == 1: 12 | return i 13 | return -1 14 | 15 | # def firstUniqChar(self, s): 16 | # min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1]) 17 | -------------------------------------------------------------------------------- /leetcode-part-1/python/389_Find_the_Difference.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findTheDifference(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: str 7 | """ 8 | res = ord(t[-1]) 9 | for i in range(len(s)): 10 | res += ord(t[i]) 11 | res -= ord(s[i]) 12 | return chr(res) 13 | 14 | # def findTheDifference(self, s, t): 15 | # res = 0 16 | # for c in s + t: 17 | # res ^= ord(c) 18 | # return chr(res) 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/400_Nth_Digit.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findNthDigit(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution 8 | count = 9 9 | start = 1 10 | curr_len = 1 11 | while n > curr_len * count: 12 | n -= curr_len * count 13 | curr_len += 1 14 | count *= 10 15 | start *= 10 16 | start += (n - 1) / curr_len 17 | s = str(start) 18 | return int(s[(n - 1) % curr_len] 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/401_Binary_Watch.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def readBinaryWatch(self, num): 3 | """ 4 | :type num: int 5 | :rtype: List[str] 6 | """ 7 | return ['%d:%02d' % (h, m) 8 | for h in range(12) for m in range(60) 9 | if (bin(h) + bin(m)).count('1') == num] 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /leetcode-part-1/python/414_Third_Maximum_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def thirdMax(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | import Queue 8 | pq = Queue.PriorityQueue(4) 9 | check = set() 10 | for n in nums: 11 | if n in check: 12 | continue 13 | pq.put(n) 14 | check.add(n) 15 | if len(check) > 3: 16 | check.remove(pq.get()) 17 | total = len(check) 18 | while total < 3 and total > 1: 19 | total -= 1 20 | return pq.get() 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaximumXOR(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | # https://discuss.leetcode.com/topic/63299/python-6-lines-bit-by-bit 8 | answer = 0 9 | for i in range(32)[::-1]: 10 | answer <<= 1 11 | # use a set to remove duplicate 12 | prefixes = {num >> i for num in nums} 13 | # if there is x y in prefixes, where x ^ y = answer ^ 1 14 | answer += any(answer ^ 1 ^ p in prefixes for p in prefixes) 15 | return answer 16 | 17 | 18 | if __name__ == '__main__': 19 | s = Solution() 20 | s.findMaximumXOR([3, 10, 5, 25, 2, 8]) 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/434_Number_of_Segments_in_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # https://leetcode.com/problems/number-of-segments-in-a-string/solution/ 3 | # def countSegments(self, s): 4 | # """ 5 | # :type s: str 6 | # :rtype: int 7 | # """ 8 | # return len(s.split()) 9 | 10 | def countSegments(self, s): 11 | segment_count = 0 12 | for i in range(len(s)): 13 | if (i == 0 or s[i-1] == ' ') and s[i] != ' ': 14 | segment_count += 1 15 | 16 | return segment_count -------------------------------------------------------------------------------- /leetcode-part-1/python/441_Arranging_Coins.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrangeCoins(self, n): 3 | level = 0 4 | while n > level: 5 | level += 1 6 | n -= level 7 | return level 8 | -------------------------------------------------------------------------------- /leetcode-part-1/python/443_String_Compression.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def compress(self, chars): 3 | """ 4 | :type chars: List[str] 5 | :rtype: int 6 | """ 7 | # https://leetcode.com/problems/string-compression/solution/ 8 | anchor = write = 0 9 | for read, c in enumerate(chars): 10 | if read + 1 == len(chars) or chars[read + 1] != c: 11 | chars[write] = chars[anchor] 12 | write += 1 13 | if read > anchor: 14 | for digit in str(read - anchor + 1): 15 | chars[write] = digit 16 | write += 1 17 | anchor = read + 1 18 | return write -------------------------------------------------------------------------------- /leetcode-part-1/python/448_Find_All_Numbers_Disappeared_in_an_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDisappearedNumbers(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution 8 | res = [] 9 | if nums: 10 | n = len(nums) 11 | for i in range(n): 12 | val = abs(nums[i]) - 1 13 | if nums[val] > 0: 14 | nums[val] = -nums[val] 15 | for i in range(n): 16 | if nums[i] > 0: 17 | res.append(i + 1) 18 | return res 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/453_Minimum_Moves_to_Equal_Array_Elements.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minMoves(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if nums is None or len(nums) == 0: 8 | return 0 9 | min_num = min(nums) 10 | return sum([i - min_num for i in nums]) 11 | -------------------------------------------------------------------------------- /leetcode-part-1/python/458_Poor_Pigs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def poorPigs(self, buckets, minutesToDie, minutesToTest): 3 | """ 4 | :type buckets: int 5 | :type minutesToDie: int 6 | :type minutesToTest: int 7 | :rtype: int 8 | """ 9 | # https://leetcode.com/problems/poor-pigs/discuss/94266/Another-explanation-and-solution 10 | pigs = 0 11 | while (minutesToTest / minutesToDie + 1) ** pigs < buckets: 12 | pigs += 1 13 | return pigs 14 | -------------------------------------------------------------------------------- /leetcode-part-1/python/461_Hamming_Distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingDistance(self, x, y): 3 | """ 4 | :type x: int 5 | :type y: int 6 | :rtype: int 7 | """ 8 | return bin(x ^ y).count('1') 9 | -------------------------------------------------------------------------------- /leetcode-part-1/python/475_Heaters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findRadius(self, houses, heaters): 3 | """ 4 | :type houses: List[int] 5 | :type heaters: List[int] 6 | :rtype: int 7 | """ 8 | heaters = sorted(heaters) + [float('inf')] 9 | i = r = 0 10 | for x in sorted(houses): 11 | # move to next range 12 | while x >= sum(heaters[i:i + 2]) / 2.: 13 | i += 1 14 | # ans = hearter - hourse 15 | r = max(r, abs(heaters[i] - x)) 16 | return r 17 | -------------------------------------------------------------------------------- /leetcode-part-1/python/482_License_Key_Formatting.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def licenseKeyFormatting(self, S, K): 3 | """ 4 | :type S: str 5 | :type K: int 6 | :rtype: str 7 | """ 8 | # https://leetcode.com/problems/license-key-formatting/discuss/96497/Python-solution 9 | S = S.upper().replace('-', '') 10 | ls = len(S) 11 | if ls % K == 0: 12 | pos = K 13 | else: 14 | pos = ls % K 15 | res = S[:pos] 16 | while pos < ls: 17 | res += '-' + S[pos:pos + K] 18 | pos += K 19 | return res 20 | -------------------------------------------------------------------------------- /leetcode-part-1/python/485_Max_Consecutive_Ones.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMaxConsecutiveOnes(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | ans = 0 8 | curr = 0 9 | for n in nums: 10 | if n == 1: 11 | # Add 1 to curr when encounter 1 12 | curr += 1 13 | if curr > ans: 14 | ans = curr 15 | else: 16 | # Add 1 to curr when encounter 1 17 | curr = 0 18 | return ans 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/541_Reverse_String_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseStr(self, s: str, k: int) -> str: 3 | N = len(s) 4 | ans = "" 5 | position = 0 6 | while position < N: 7 | nx = s[position : position + k] 8 | ans = ans + nx[::-1] + s[position + k : position + 2 * k] 9 | position += 2 * k 10 | return ans 11 | 12 | # def reverseStr(self, s: str, k: int) -> str: 13 | # s = list(s) 14 | # for i in range(0, len(s), 2*k): 15 | # s[i:i+k] = reversed(s[i:i+k]) 16 | # return "".join(s) 17 | 18 | 19 | 20 | s1 = Solution() 21 | s="abcdefg" 22 | k=2 23 | print(s1.reverseStr(s,k)) 24 | -------------------------------------------------------------------------------- /leetcode-part-1/python/543_Diameter_of_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | # https://leetcode.com/problems/diameter-of-binary-tree/solution/ 10 | def diameterOfBinaryTree(self, root): 11 | self.ans = 1 12 | def depth(node): 13 | if not node: return 0 14 | L = depth(node.left) 15 | R = depth(node.right) 16 | self.ans = max(self.ans, L+R+1) 17 | return max(L, R) + 1 18 | 19 | depth(root) 20 | # number of nodes - 1 = length 21 | return self.ans - 1 22 | -------------------------------------------------------------------------------- /leetcode-part-1/python/557_Reverse_Words_in_a_String_III.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseWords(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | return ' '.join([word[::-1] for word in s.split(' ')]) 8 | -------------------------------------------------------------------------------- /leetcode-part-1/python/560_Subarray_Sum_Equals_K.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def subarraySum(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | sum_map = {} 9 | sum_map[0] = 1 10 | count = curr_sum = 0 11 | for num in nums: 12 | curr_sum += num 13 | # Check if sum - k in hash 14 | count += sum_map.get(curr_sum - k, 0) 15 | # add curr_sum to hash 16 | sum_map[curr_sum] = sum_map.get(curr_sum, 0) + 1 17 | return count 18 | -------------------------------------------------------------------------------- /leetcode-part-1/python/605_Can_Place_Flowers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canPlaceFlowers(self, flowerbed, n): 3 | """ 4 | :type flowerbed: List[int] 5 | :type n: int 6 | :rtype: bool 7 | """ 8 | count = 0 9 | for i in range(len(flowerbed)): 10 | curr = flowerbed[i] 11 | if i - 1 >= 0: 12 | curr += flowerbed[i - 1] 13 | if i + 1 < len(flowerbed): 14 | curr += flowerbed[i + 1] 15 | if curr == 0: 16 | count += 1 17 | flowerbed[i] = 1 18 | if count >= n: 19 | return True 20 | return False 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/668_Kth_Smallest_Number_in_Multiplication_Table.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthNumber(self, m: int, n: int, k: int) -> int: 3 | # https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/ 4 | def enough(x): 5 | count = 0 6 | # ith row [i, 2*i, 3*i, ..., n*i] 7 | # for each column, k = x // i 8 | for i in range(1, m+1): 9 | count += min(x // i, n) 10 | return count >= k 11 | 12 | lo, hi = 1, m * n 13 | while lo < hi: 14 | mi = (lo + hi) // 2 15 | if not enough(mi): 16 | lo = mi + 1 17 | else: 18 | hi = mi 19 | return lo 20 | -------------------------------------------------------------------------------- /leetcode-part-1/python/674_Longest_Continuous_Increasing_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLengthOfLCIS(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if not nums or len(nums) == 0: 8 | return 0 9 | ans = curr = 1 10 | for i in range(len(nums) - 1): 11 | if nums[i] < nums[i + 1]: 12 | curr += 1 13 | ans = max(ans, curr) 14 | else: 15 | curr = 1 16 | return ans 17 | -------------------------------------------------------------------------------- /leetcode-part-1/python/709_To_Lower_Case.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def toLowerCase(self, str): 3 | """ 4 | :type str: str 5 | :rtype: str 6 | """ 7 | res = [] 8 | gap = ord('a') - ord('A') 9 | for c in str: 10 | if ord(c) >= ord('A') and ord(c) <= ord('Z'): 11 | res.append(chr(ord(c) + gap)) 12 | else: 13 | res.append(c) 14 | return ''.join(res) 15 | 16 | # def toLowerCase(self, str): 17 | # return str.lower() 18 | -------------------------------------------------------------------------------- /leetcode-part-1/python/724_Find_Pivot_Index.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def pivotIndex(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | totalsum = sum(nums) 8 | leftsum = 0 9 | for i, v in enumerate(nums): 10 | # leftsum == rightsum 11 | if leftsum == totalsum - leftsum - v: 12 | return i 13 | leftsum += v 14 | return -1 15 | -------------------------------------------------------------------------------- /leetcode-part-1/python/728_Self_Dividing_Numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 3 | # check every digit 4 | return [x for x in range(left, right+1) if all([int(i) != 0 and x % int(i)==0 for i in str(x)])] 5 | 6 | # def selfDividingNumbers(self, left: int, right: int) -> List[int]: 7 | # return [x for x in range(left, right+1) if all((i and (x % i==0) for i in map(int, str(x))))] 8 | -------------------------------------------------------------------------------- /leetcode-part-1/python/760_Find_Anagram_Mappings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def anagramMappings(self, A, B): 3 | """ 4 | :type A: List[int] 5 | :type B: List[int] 6 | :rtype: List[int] 7 | """ 8 | val_index = {} 9 | ans = [] 10 | for i, n in enumerate(B): 11 | val_index[n] = i 12 | for n in A: 13 | ans.append(val_index[n]) 14 | return ans 15 | -------------------------------------------------------------------------------- /leetcode-part-1/python/766_Toeplitz_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isToeplitzMatrix(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: bool 6 | """ 7 | # Actually, we don't need to check the last row and column 8 | for r in range(len(matrix) - 1): 9 | for c in range(len(matrix[0]) - 1): 10 | if matrix[r][c] != matrix[r + 1][c + 1]: 11 | return False 12 | return True 13 | -------------------------------------------------------------------------------- /leetcode-part-1/python/771_Jewels_and_Stones.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numJewelsInStones(self, J, S): 3 | """ 4 | :type J: str 5 | :type S: str 6 | :rtype: int 7 | """ 8 | if len(J) == 0 or len(S) == 0: 9 | return 0 10 | j_set = set(J) 11 | ans = 0 12 | for c in S: 13 | if c in j_set: 14 | ans += 1 15 | return ans 16 | -------------------------------------------------------------------------------- /leetcode-part-1/python/819_Most_Common_Word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mostCommonWord(self, paragraph, banned): 3 | """ 4 | :type paragraph: str 5 | :type banned: List[str] 6 | :rtype: str 7 | """ 8 | # https://leetcode.com/problems/most-common-word/discuss/193268/python-one-liner 9 | banned = set(banned) 10 | count = collections.Counter(word for word in re.split('[ !?\',;.]', 11 | paragraph.lower()) if word) 12 | return max((item for item in count.items() if item[0] not in banned), 13 | key=operator.itemgetter(1))[0] 14 | -------------------------------------------------------------------------------- /leetcode-part-1/python/832_Flipping_an_Image.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def flipAndInvertImage(self, A): 3 | for row in A: 4 | for i in xrange((len(row) + 1) / 2): 5 | """ 6 | In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] 7 | helps us find the i-th value of the row, counting from the right. 8 | """ 9 | row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 10 | return A 11 | # return [[1 ^ i for i in row[::-1]] for row in A] 12 | -------------------------------------------------------------------------------- /leetcode-part-1/python/836_Rectangle_Overlap.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isRectangleOverlap(self, rec1, rec2): 3 | """ 4 | :type rec1: List[int] 5 | :type rec2: List[int] 6 | :rtype: bool 7 | """ 8 | return not (rec1[2] <= rec2[0] or # left 9 | rec1[3] <= rec2[1] or # bottom 10 | rec1[0] >= rec2[2] or # right 11 | rec1[1] >= rec2[3]) # top 12 | 13 | # def isRectangleOverlap(self, rec1, rec2): 14 | # def intersect(p_left, p_right, q_left, q_right): 15 | # return min(p_right, q_right) > max(p_left, q_left) 16 | # return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and 17 | # intersect(rec1[1], rec1[3], rec2[1], rec2[3])) 18 | -------------------------------------------------------------------------------- /leetcode-part-1/python/852_Peak_Index_in_a_Mountain_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def peakIndexInMountainArray(self, A): 3 | # """ 4 | # :type A: List[int] 5 | # :rtype: int 6 | # """ 7 | # i = 0 8 | # while A[i + 1] >= A[i]: 9 | # i += 1 10 | # return i 11 | 12 | def peakIndexInMountainArray(self, A): 13 | lo, hi = 0, len(A) - 1 14 | while lo < hi: 15 | mid = (lo + hi) / 2 16 | if A[mid] < A[mid + 1]: 17 | lo = mid + 1 18 | else: 19 | hi = mid 20 | return lo 21 | -------------------------------------------------------------------------------- /leetcode-part-1/python/867_Transpose_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def transpose(self, A): 3 | """ 4 | :type A: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | R, C = len(A), len(A[0]) 8 | ans = [[None] * R for _ in xrange(C)] 9 | for r, row in enumerate(A): 10 | for c, val in enumerate(row): 11 | ans[c][r] = val 12 | return ans 13 | # Alternative Solution: 14 | # return zip(*A) 15 | 16 | # def transpose(self, A): 17 | # res = [] 18 | # for i in range(len(A[0])): 19 | # temp = [] 20 | # for j in range(len(A)): 21 | # temp.append(A[j][i]) 22 | # res.append(temp) 23 | # return res 24 | -------------------------------------------------------------------------------- /leetcode-part-1/python/929_Unique_Email_Addresses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numUniqueEmails(self, emails): 3 | """ 4 | :type emails: List[str] 5 | :rtype: int 6 | """ 7 | email_set = set() 8 | for email in emails: 9 | elements = email.split('@') 10 | email_set.add(elements[0].split('+')[0].replace('.', '') + elements[1]) 11 | return len(email_set) 12 | -------------------------------------------------------------------------------- /leetcode-part-1/python/933_Number_of_Recent_Calls.py: -------------------------------------------------------------------------------- 1 | class RecentCounter(object): 2 | 3 | def __init__(self): 4 | self.queue = [] 5 | 6 | def ping(self, t): 7 | """ 8 | :type t: int 9 | :rtype: int 10 | """ 11 | self.queue.append(t) 12 | while self.queue and self.queue[0] < t - 3000: 13 | self.queue.pop(0) 14 | return len(self.queue) 15 | 16 | 17 | # Your RecentCounter object will be instantiated and called as such: 18 | # obj = RecentCounter() 19 | # param_1 = obj.ping(t) 20 | -------------------------------------------------------------------------------- /leetcode-part-1/python/961_N-Repeated_Element_in_Size_2N_Array.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Solution(object): 5 | def repeatedNTimes(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | counter = collections.Counter(A) 11 | return counter.most_common(1)[0][0] 12 | 13 | 14 | if __name__ == '__main__': 15 | s = Solution() 16 | print s.repeatedNTimes([1, 2, 3, 3]) 17 | print s.repeatedNTimes([2, 1, 2, 5, 3, 2]) 18 | print s.repeatedNTimes([5, 1, 5, 2, 5, 3, 5, 4]) 19 | -------------------------------------------------------------------------------- /leetcode-part-1/python/973_K_Closest_Points_to_Origin.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # def kClosest(self, points, K): 3 | # """ 4 | # :type points: List[List[int]] 5 | # :type K: int 6 | # :rtype: List[List[int]] 7 | # """ 8 | # # Sort 9 | # return sorted(points, key=lambda x: x[0] ** 2 + x[1] ** 2)[:K] 10 | 11 | def kClosest(self, points, K): 12 | # K smallest heaq 13 | return heapq.nsmallest(K, points, key=lambda x: x[0] ** 2 + x[1] ** 2) 14 | -------------------------------------------------------------------------------- /leetcode-part-1/python/981_Time_Based_Store.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class TimeMap(object): 4 | 5 | def __init__(self): 6 | self.store = defaultdict(list) 7 | 8 | def set(self, key, value, timestamp): 9 | self.store[key].append((value, timestamp)) 10 | 11 | def get(self, key, timestamp): 12 | values = self.store.get(key, []) 13 | res = "" 14 | 15 | l = 0 16 | r = len(values) - 1 17 | 18 | while l <= r: 19 | mid = (l + r) // 2 20 | if values[mid][1] <= timestamp: 21 | l = mid + 1 22 | res = values[mid][0] 23 | else: 24 | r = mid - 1 25 | 26 | return res 27 | -------------------------------------------------------------------------------- /leetcode-part-1/python/997_Find_The_Town_Judge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 3 | if N==1: 4 | return 1 5 | d1={} 6 | d2={} 7 | for i, j in trust: 8 | if j in d1: 9 | d1[j]+=1 10 | else: 11 | d1[j]=1 12 | if i in d2: 13 | d2[i]+=1 14 | else: 15 | d2[i]=1 16 | for i,j in d1.items(): 17 | if j==N-1: 18 | if i not in d2: 19 | return i 20 | return -1 21 | 22 | -------------------------------------------------------------------------------- /leetcode-part-1/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/leetcode-part-1/python/__init__.py -------------------------------------------------------------------------------- /leetcode-part-2/LeetCode.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /leetcode-part-2/array/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode-part-2/array/WiggleSort.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 2 | 3 | // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | 5 | public class WiggleSort { 6 | public void wiggleSort(int[] nums) { 7 | for(int i = 1; i < nums.length; i++) { 8 | int current = nums[i - 1]; 9 | 10 | if((i % 2 == 1) == (current > nums[i])) { 11 | nums[i - 1] = nums[i]; 12 | nums[i] = current; 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-2/binary-search/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-2/binary-search/SquareRootX.java: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | 3 | // Compute and return the square root of x. 4 | 5 | public class Solution { 6 | public int mySqrt(int x) { 7 | if(x == 0) { 8 | return 0; 9 | } 10 | 11 | int left = 1; 12 | int right = x; 13 | 14 | while(left <= right) { 15 | int mid = left + (right - left) / 2; 16 | 17 | if(mid == x / mid) { 18 | return mid; 19 | } else if(mid > x / mid) { 20 | right = mid - 1; 21 | } else if(mid < x / mid) { 22 | left = mid + 1; 23 | } 24 | } 25 | 26 | return right; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-2/bit-manipulation/CountingBits.java: -------------------------------------------------------------------------------- 1 | // Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 2 | 3 | // Example: 4 | // For num = 5 you should return [0,1,1,2,1,2]. 5 | 6 | public class CountingBits { 7 | public int[] countBits(int num) { 8 | int[] bits = new int[num + 1]; 9 | 10 | bits[0] = 0; 11 | 12 | for(int i = 1; i <= num; i++) { 13 | bits[i] = bits[i >> 1] + (i & 1); 14 | } 15 | 16 | return bits; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode-part-2/bit-manipulation/HammingDistance.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, calculate the Hamming distance. 4 | 5 | // Note: 6 | // 0 ≤ x, y < 2^31. 7 | 8 | // Example: 9 | 10 | // Input: x = 1, y = 4 11 | 12 | // Output: 2 13 | 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | 19 | // The above arrows point to positions where the corresponding bits are different. 20 | 21 | public class HammingDistance { 22 | public int hammingDistance(int x, int y) { 23 | return Integer.bitCount(x ^ y); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode-part-2/bit-manipulation/NumberOfOneBits.java: -------------------------------------------------------------------------------- 1 | // Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 2 | 3 | // For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 4 | 5 | public class NumberOfOneBits { 6 | // you need to treat n as an unsigned value 7 | public int hammingWeight(int n) { 8 | if(n == 0) { 9 | return 0; 10 | } 11 | 12 | int count = 0; 13 | 14 | while(n != 0) { 15 | count += (n) & 1; 16 | n >>>= 1; 17 | } 18 | 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode-part-2/bit-manipulation/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | //Given an integer, write a function to determine if it is a power of two. 2 | // 3 | //Example 1: 4 | // 5 | //Input: 1 6 | //Output: true 7 | //Example 2: 8 | // 9 | //Input: 16 10 | //Output: true 11 | //Example 3: 12 | // 13 | //Input: 218 14 | //Output: false 15 | 16 | class PowerOfTwo { 17 | public boolean isPowerOfTwo(int n) { 18 | long i = 1; 19 | while(i < n) { 20 | i <<= 1; 21 | } 22 | 23 | return i == n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode-part-2/bit-manipulation/SumOfTwoInteger.java: -------------------------------------------------------------------------------- 1 | // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 2 | 3 | // Example: 4 | // Given a = 1 and b = 2, return 3. 5 | 6 | public class SumOfTwoIntegers { 7 | public int getSum(int a, int b) { 8 | if(a == 0) { 9 | return b; 10 | } 11 | 12 | if(b == 0) { 13 | return a; 14 | } 15 | 16 | while(b != 0) { 17 | int carry = a & b; 18 | a = a ^ b; 19 | b = carry << 1; 20 | } 21 | 22 | return a; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode-part-2/depth-first-search/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class MaximumDepthOfABinaryTree { 15 | public int maxDepth(TreeNode root) { 16 | if(root == null) { 17 | return 0; 18 | } 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode-part-2/divide-and-conquer/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | int length = nums.length; 12 | Arrays.sort(nums); 13 | 14 | return nums[length - k]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-2/dynamic-programming/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | // You are climbing a stair case. It takes n steps to reach to the top. 2 | 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | // Note: Given n will be a positive integer. 6 | 7 | public class ClimbingStairs { 8 | public int climbStairs(int n) { 9 | int[] dp = new int[n + 1]; 10 | 11 | dp[0] = 1; 12 | dp[1] = 1; 13 | 14 | for(int i = 2; i < dp.length; i++) { 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | } 17 | 18 | return dp[dp.length - 1]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-2/hash-table/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-2/hash-table/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /leetcode-part-2/hash-table/StrobogrammaticNumber.java: -------------------------------------------------------------------------------- 1 | // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | 3 | // Write a function to determine if a number is strobogrammatic. The number is represented as a string. 4 | 5 | // For example, the numbers "69", "88", and "818" are all strobogrammatic. 6 | 7 | public class StrobogrammaticNumber { 8 | public boolean isStrobogrammatic(String num) { 9 | for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { 10 | if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-2/linked-list/DeleteNodeInALinkedList.java: -------------------------------------------------------------------------------- 1 | // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 2 | 3 | // Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class DeleteNodeInALinkedList { 14 | public void deleteNode(ListNode node) { 15 | node.val = node.next.val; 16 | node.next = node.next.next; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode-part-2/linked-list/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-2/math/AddDigits.java: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | 3 | //For example: 4 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | 6 | //Follow up: 7 | //Could you do it without any loop/recursion in O(1) runtime? 8 | 9 | class AddDigits { 10 | public int addDigits(int num) { 11 | while(num >= 10) { 12 | int temp = 0; 13 | while(num > 0) { 14 | temp += num % 10; 15 | num /= 10; 16 | } 17 | num = temp; 18 | } 19 | 20 | return num; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode-part-2/math/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | //Determine whether an integer is a palindrome. Do this without extra space. 2 | 3 | class PalindromeNumber { 4 | public boolean isPalindrome(int x) { 5 | if(x < 0) { 6 | return false; 7 | } 8 | 9 | int num = x; 10 | int reversed = 0; 11 | 12 | while(num != 0) { 13 | reversed = reversed * 10 + num % 10; 14 | num /= 10; 15 | } 16 | 17 | return x == reversed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode-part-2/math/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | //Given an integer, write a function to determine if it is a power of two. 2 | // 3 | //Example 1: 4 | // 5 | //Input: 1 6 | //Output: true 7 | //Example 2: 8 | // 9 | //Input: 16 10 | //Output: true 11 | //Example 3: 12 | // 13 | //Input: 218 14 | //Output: false 15 | 16 | class PowerOfTwo { 17 | public boolean isPowerOfTwo(int n) { 18 | long i = 1; 19 | while(i < n) { 20 | i <<= 1; 21 | } 22 | 23 | return i == n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode-part-2/string/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | class LongestCommonPrefix { 2 | public String longestCommonPrefix(String[] strs) { 3 | if(strs == null || strs.length == 0) { 4 | return ""; 5 | } 6 | 7 | String s = strs[0]; 8 | for(int i = 0; i < s.length(); i++) { 9 | char current = s.charAt(i); 10 | for(int j = 1; j < strs.length; j++) { 11 | if(i >= strs[j].length() || strs[j].charAt(i) != current) { 12 | return s.substring(0, i); 13 | } 14 | } 15 | } 16 | 17 | return s; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode-part-2/string/LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | public class LongestPalindrome { 2 | public int longestPalindrome(String s) { 3 | HashMap map = new HashMap(); 4 | 5 | int count = 0; 6 | 7 | for(int i = 0; i < s.length(); i++) { 8 | if(!map.containsKey(s.charAt(i))) { 9 | map.put(s.charAt(i), (int)(s.charAt(i))); 10 | } else { 11 | map.remove(s.charAt(i)); 12 | count++; 13 | } 14 | } 15 | 16 | return map.isEmpty() ? count * 2 : count * 2 + 1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode-part-2/string/PalindromePermutation.java: -------------------------------------------------------------------------------- 1 | public class PalindromePermutation { 2 | public boolean canPermutePalindrome(String s) { 3 | char[] characters = new char[256]; 4 | 5 | for(int i = 0; i < s.length(); i++) { 6 | characters[s.charAt(i)]++; 7 | } 8 | 9 | int oddCount = 0; 10 | 11 | for(int i = 0; i < characters.length; i++) { 12 | if(!(characters[i] % 2 == 0)) { 13 | oddCount++; 14 | 15 | if(oddCount > 1) { 16 | return false; 17 | } 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode-part-2/string/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-2/two-pointers/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | 3 | // Note: 4 | // You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 5 | 6 | public class MergeSortedArray { 7 | public void merge(int[] A, int m, int[] B, int n) { 8 | int i = m - 1; 9 | int j = n - 1; 10 | int k = m + n - 1; 11 | 12 | while(i >= 0 && j >= 0) { 13 | A[k--] = A[i] > B[j] ? A[i--] : B[j--]; 14 | } 15 | 16 | while(j >= 0) { 17 | A[k--] = B[j--]; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-2/two-pointers/ReverseString.java: -------------------------------------------------------------------------------- 1 | // Write a function that takes a string as input and returns the string reversed. 2 | 3 | // Example: 4 | // Given s = "hello", return "olleh". 5 | 6 | public class ReverseString { 7 | public String reverseString(String s) { 8 | if(s == null || s.length() == 1 || s.length() == 0) { 9 | return s; 10 | } 11 | 12 | char[] word = s.toCharArray(); 13 | 14 | for(int i = 0, j = s.length() - 1; i < j; i++, j--) { 15 | char temp = word[i]; 16 | word[i] = word[j]; 17 | word[j] = temp; 18 | } 19 | 20 | return new String(word); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode-part-3/adobe/AddDigits.java: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | 3 | //For example: 4 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | 6 | //Follow up: 7 | //Could you do it without any loop/recursion in O(1) runtime? 8 | 9 | class AddDigits { 10 | public int addDigits(int num) { 11 | while(num >= 10) { 12 | int temp = 0; 13 | while(num > 0) { 14 | temp += num % 10; 15 | num /= 10; 16 | } 17 | num = temp; 18 | } 19 | 20 | return num; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /leetcode-part-3/airbnb/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /leetcode-part-3/airbnb/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /leetcode-part-3/amazon/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | int length = nums.length; 12 | 13 | Arrays.sort(nums); 14 | 15 | return nums[length - k]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-3/amazon/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-3/apple/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /leetcode-part-3/bloomberg/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /leetcode-part-3/facebook/HammingDistance.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, calculate the Hamming distance. 4 | 5 | // Note: 6 | // 0 ≤ x, y < 2^31. 7 | 8 | // Example: 9 | 10 | // Input: x = 1, y = 4 11 | 12 | // Output: 2 13 | 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | 19 | // The above arrows point to positions where the corresponding bits are different. 20 | 21 | public class HammingDistance { 22 | public int hammingDistance(int x, int y) { 23 | return Integer.bitCount(x ^ y); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode-part-3/facebook/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class KthLargestElementInAnArray { 10 | public int findKthLargest(int[] nums, int k) { 11 | int length = nums.length; 12 | 13 | Arrays.sort(nums); 14 | 15 | return nums[length - k]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-3/facebook/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | // Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 2 | 3 | // Note: 4 | // You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 5 | 6 | public class MergeSortedArray { 7 | public void merge(int[] A, int m, int[] B, int n) { 8 | int i = m - 1; 9 | int j = n - 1; 10 | int k = m + n - 1; 11 | 12 | while(i >= 0 && j >= 0) { 13 | A[k--] = A[i] > B[j] ? A[i--] : B[j--]; 14 | } 15 | 16 | while(j >= 0) { 17 | A[k--] = B[j--]; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-3/facebook/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-3/facebook/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-3/facebook/SquareRootX.java: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | 3 | // Compute and return the square root of x. 4 | 5 | public class SquareRootX { 6 | public int mySqrt(int x) { 7 | if(x == 0) { 8 | return 0; 9 | } 10 | 11 | int left = 1; 12 | int right = x; 13 | 14 | while(left <= right) { 15 | int mid = left + (right - left) / 2; 16 | 17 | if(mid == x / mid) { 18 | return mid; 19 | } else if(mid > x / mid) { 20 | right = mid - 1; 21 | } else if(mid < x / mid) { 22 | left = mid + 1; 23 | } 24 | } 25 | 26 | return right; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-3/google/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | //Given an integer, write a function to determine if it is a power of two. 2 | // 3 | //Example 1: 4 | // 5 | //Input: 1 6 | //Output: true 7 | //Example 2: 8 | // 9 | //Input: 16 10 | //Output: true 11 | //Example 3: 12 | // 13 | //Input: 218 14 | //Output: false 15 | 16 | class PowerOfTwo { 17 | public boolean isPowerOfTwo(int n) { 18 | long i = 1; 19 | while(i < n) { 20 | i <<= 1; 21 | } 22 | 23 | return i == n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode-part-3/google/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-3/google/StrobogrammaticNumber.java: -------------------------------------------------------------------------------- 1 | // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | 3 | // Write a function to determine if a number is strobogrammatic. The number is represented as a string. 4 | 5 | // For example, the numbers "69", "88", and "818" are all strobogrammatic. 6 | 7 | public class StrobogrammaticNumber { 8 | public boolean isStrobogrammatic(String num) { 9 | for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { 10 | if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode-part-3/google/WiggleSort.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 2 | 3 | // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | 5 | public class WiggleSort { 6 | public void wiggleSort(int[] nums) { 7 | for(int i = 1; i < nums.length; i++) { 8 | int current = nums[i - 1]; 9 | 10 | if((i % 2 == 1) == (current > nums[i])) { 11 | nums[i - 1] = nums[i]; 12 | nums[i] = current; 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode-part-3/linkedin/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class MaximumDepthOfABinaryTree { 15 | public int maxDepth(TreeNode root) { 16 | if(root == null) { 17 | return 0; 18 | } 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode-part-3/linkedin/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | // Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 2 | 3 | // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 4 | // the contiguous subarray [4,-1,2,1] has the largest sum = 6. 5 | 6 | public class MaximumSubarray { 7 | public int maxSubArray(int[] nums) { 8 | int[] dp = new int[nums.length]; 9 | 10 | dp[0] = nums[0]; 11 | 12 | int max = dp[0]; 13 | 14 | for(int i = 1; i < nums.length; i++) { 15 | dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 16 | max = Math.max(dp[i], max); 17 | } 18 | 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode-part-3/linkedin/PowerOfXToTheN.java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class PowerOfXToTheN { 4 | public double myPow(double x, int n) { 5 | if(n == 0) { 6 | return 1; 7 | } 8 | 9 | if(Double.isInfinite(x)) { 10 | return 0; 11 | } 12 | 13 | if(n < 0) { 14 | n = -n; 15 | x = 1 / x; 16 | } 17 | 18 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode-part-3/microsoft/AddDigits.java: -------------------------------------------------------------------------------- 1 | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 2 | 3 | //For example: 4 | //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 5 | 6 | //Follow up: 7 | //Could you do it without any loop/recursion in O(1) runtime? 8 | 9 | class AddDigits { 10 | public int addDigits(int num) { 11 | while(num >= 10) { 12 | int temp = 0; 13 | while(num > 0) { 14 | temp += num % 10; 15 | num /= 10; 16 | } 17 | num = temp; 18 | } 19 | 20 | return num; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /leetcode-part-3/microsoft/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /leetcode-part-3/palantir/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /leetcode-part-3/palantir/ContainsDuplicatesII.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers and an integer k, find out whether there are two distinct indices i and 2 | //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 3 | 4 | class ContainsDuplicatesII { 5 | public boolean containsNearbyDuplicate(int[] nums, int k) { 6 | HashMap map = new HashMap(); 7 | for(int i = 0; i < nums.length; i++) { 8 | int current = nums[i]; 9 | if(map.containsKey(current) && i - map.get(current) <= k) { 10 | return true; 11 | } else { 12 | map.put(current, i); 13 | } 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /leetcode-part-3/snapchat/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /leetcode-part-3/twitter/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-3/uber/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class MaximumDepthOfABinaryTree { 15 | public int maxDepth(TreeNode root) { 16 | if(root == null) { 17 | return 0; 18 | } 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode-part-3/uber/PalindromePermutation.java: -------------------------------------------------------------------------------- 1 | public class PalindromePermutation { 2 | public boolean canPermutePalindrome(String s) { 3 | char[] characters = new char[256]; 4 | 5 | for(int i = 0; i < s.length(); i++) { 6 | characters[s.charAt(i)]++; 7 | } 8 | 9 | int oddCount = 0; 10 | 11 | for(int i = 0; i < characters.length; i++) { 12 | if(!(characters[i] % 2 == 0)) { 13 | oddCount++; 14 | if(oddCount > 1) { 15 | return false; 16 | } 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode-part-3/uber/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | // Reverse a singly linked list. 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class ReverseLinkedList { 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null) { 14 | return head; 15 | } 16 | 17 | ListNode newHead = null; 18 | 19 | while(head != null) { 20 | ListNode next = head.next; 21 | head.next = newHead; 22 | newHead = head; 23 | head = next; 24 | } 25 | 26 | return newHead; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode-part-3/yahoo/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | //Given an array of integers, find if the array contains any duplicates. Your function should return 2 | //true if any value appears at least twice in the array, and it should return false if every element is distinct. 3 | 4 | class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashMap map = new HashMap(); 7 | for(int i: nums) { 8 | if(map.containsKey(i)) { 9 | return true; 10 | } else { 11 | map.put(i, 1); 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /leetcode-part-3/yelp/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | //Given an input string, reverse the string word by word. 2 | //For example, 3 | //Given s = "the sky is blue", 4 | //return "blue is sky the". 5 | 6 | public class ReverseWordsInAString { 7 | public String reverseWords(String s) { 8 | String[] words = s.trim().split("\\s+"); 9 | String result = ""; 10 | for(int i = words.length - 1; i > 0; i--) { 11 | result += words[i] + " "; 12 | } 13 | 14 | return result + words[0]; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /leetcode/algorithms/cpp/largestPerimeterTriangle/largestPerimeterTriangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestPerimeter(vector& A) { 4 | if (A.size() < 3) return 0; 5 | sort(A.begin(), A.end(), greater()); 6 | for (auto it = A.begin(); it != A.end() - 2; ++it) { 7 | if (*it < *(it + 1) + *(it + 2)) 8 | return *it + *(it + 1) + *(it + 2); 9 | } 10 | return 0; 11 | } 12 | }; 13 | 14 | -------------------------------------------------------------------------------- /leetcode/algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.h: -------------------------------------------------------------------------------- 1 | // 2 | // OJ#418.h 3 | // LeeteCodeOJ#418 4 | // 5 | // Created by Wang Yi on 25/10/16. 6 | // Copyright (c) 2016 Wang Yi. All rights reserved. 7 | // 8 | 9 | #ifndef __LeeteCodeOJ_418__OJ_418__ 10 | #define __LeeteCodeOJ_418__OJ_418__ 11 | 12 | #define M 10 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | using std::vector; 19 | using std::string; 20 | 21 | int SentenceScreenFitting(char stc[][M], int row, int col, size_t l); 22 | 23 | class Solution { 24 | public: 25 | int wordsTyping(vector& sentence, int rows, int cols); 26 | }; 27 | 28 | #endif /* defined(__LeeteCodeOJ_418__OJ_418__) */ 29 | -------------------------------------------------------------------------------- /leetcode/algorithms/golang/twoSum/twoSum.go: -------------------------------------------------------------------------------- 1 | package twoSum 2 | 3 | func twoSum(nums []int, target int) []int { 4 | numMap := make(map[int]int) 5 | for index, num := range nums { 6 | if i, ok := numMap[target-num]; ok { 7 | return []int{i, index} 8 | } 9 | numMap[num] = index 10 | } 11 | return nil 12 | } -------------------------------------------------------------------------------- /leetcode/algorithms/java/algorithms-java.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/junit-4.7.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/coding-interview-collection/1239b482b7d5426671e12c7e4b2991834dcb7c82/leetcode/algorithms/java/junit-4.7.jar -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/balancedBinaryTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package balancedBinaryTree; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | public int val; 8 | public TreeNode left, right; 9 | public TreeNode(int val) { 10 | this.val = val; 11 | this.left = this.right = null; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/binarySearchTreeIterator/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binarySearchTreeIterator; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | public int val; 8 | public TreeNode left, right; 9 | public TreeNode(int val) { 10 | this.val = val; 11 | this.left = this.right = null; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/binaryTreeBFSTraversal/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreeBFSTraversal; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/binaryTreeLevelOrderTraversal/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreeLevelOrderTraversal; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/binaryTreeMaximumPathSum/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreeMaximumPathSum; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/binaryTreePreorderTraversal/TreeNode.java: -------------------------------------------------------------------------------- 1 | package binaryTreePreorderTraversal; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/countAndSay/TestCountAndSay.java: -------------------------------------------------------------------------------- 1 | package countAndSay; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 38. Count and Say 7 | */ 8 | public class TestCountAndSay { 9 | @Test 10 | public void test() { 11 | CountAndSay solution = new CountAndSay(); 12 | String next5 = solution.countAndSay(5); 13 | Assert.assertTrue(next5.equals("111221")); 14 | String next6 = solution.countAndSay(6); 15 | Assert.assertTrue(next6.equals("312211")); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/dynamicProgramming/climbStairs/climbStairsTest.java: -------------------------------------------------------------------------------- 1 | package dynamicProgramming.climbStairs; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 12/10/15. 9 | */ 10 | public class climbStairsTest { 11 | 12 | @Test 13 | public void testClimbStairs() throws Exception { 14 | int[] inputs = {1,2,3,4}; 15 | 16 | int[] results = {1,2,3,5}; 17 | 18 | for (int i = 0; i < results.length; i++) { 19 | climbStairs c = new climbStairs(); 20 | int r = c.climbStairs(inputs[i]); 21 | System.out.println(r); 22 | assertEquals(results[i], r); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/dynamicProgramming/uniquePaths/uniquePathsTest.java: -------------------------------------------------------------------------------- 1 | package dynamicProgramming.uniquePaths; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 11/10/15. 9 | */ 10 | public class uniquePathsTest { 11 | 12 | @Test 13 | public void testUniquePaths() throws Exception { 14 | int[][] inputs = { 15 | {2,2}, 16 | {3,7}, 17 | }; 18 | int[] results = {2,28}; 19 | for (int i = 0; i < inputs.length; i++) { 20 | uniquePaths u = new uniquePaths(); 21 | int r = u.uniquePaths(inputs[i][0], inputs[i][1]); 22 | System.out.println(r); 23 | assertEquals(results[i], r); 24 | } 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/firstBadVersion/VersionControl.java: -------------------------------------------------------------------------------- 1 | package firstBadVersion; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class VersionControl { 7 | int firstBadVersion; 8 | boolean isBadVersion(int version) { 9 | if (version >= firstBadVersion) { 10 | return true; 11 | } 12 | return false; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/firstBadVersion/firstBadVersionTest.java: -------------------------------------------------------------------------------- 1 | package firstBadVersion; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 5/10/15. 9 | */ 10 | public class firstBadVersionTest { 11 | 12 | @Test 13 | public void testFirstBadVersion() throws Exception { 14 | int[] inputs = {1,22,34,40,5232,6342342,71231}; 15 | int[] targets = {1, 10, 20, 25, 323, 45454, 23232}; 16 | 17 | firstBadVersion f = new firstBadVersion(); 18 | for (int i = 0; i < targets.length; i++) { 19 | f.firstBadVersion = targets[i]; 20 | int r = f.firstBadVersion(inputs[i]); 21 | System.out.println(r); 22 | assertEquals(targets[i], r); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/inorderSuccessorInBST/TreeNode.java: -------------------------------------------------------------------------------- 1 | package inorderSuccessorInBST; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/lengthOfLastWord/TestLengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | package lengthOfLastWord; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 58. Length of Last Word 8 | */ 9 | public class TestLengthOfLastWord { 10 | @Test 11 | public void test() { 12 | LengthOfLastWord solution = new LengthOfLastWord(); 13 | String str1 = "Hello World"; 14 | Assert.assertTrue(solution.lengthOfLastWord(str1) == 5); 15 | String str2 = "Thank you very much "; 16 | Assert.assertTrue(solution.lengthOfLastWord(str2) == 4); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/lowestCommonAncestorOfABinaryTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package lowestCommonAncestorOfABinaryTree; 2 | 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | TreeNode(int x) { val = x; } 8 | } 9 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/maximumDepthOfBinaryTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package maximumDepthOfBinaryTree; 2 | 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | TreeNode(int x) { val = x; } 8 | } 9 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/minStack/TestMinStack.java: -------------------------------------------------------------------------------- 1 | package minStack; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 155. Min Stack 8 | */ 9 | public class TestMinStack { 10 | @Test 11 | public void test() { 12 | MinStack minStack = new MinStack(); 13 | minStack.push(3); 14 | minStack.push(4); 15 | minStack.push(1); 16 | minStack.push(2); 17 | Assert.assertTrue(minStack.getMin() == 1); 18 | minStack.pop(); 19 | minStack.pop(); 20 | Assert.assertTrue(minStack.getMin() == 3); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/myQueue/TestMyQueue.java: -------------------------------------------------------------------------------- 1 | package myQueue; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 232. Implement Queue using Stacks 7 | */ 8 | public class TestMyQueue { 9 | @Test 10 | public void test(){ 11 | MyQueue queue=new MyQueue(); 12 | Assert.assertTrue(queue.empty()); 13 | queue.push(1); 14 | queue.push(2); 15 | queue.push(3); 16 | queue.push(4); 17 | Assert.assertTrue(queue.pop()==1); 18 | Assert.assertTrue(queue.pop()==2); 19 | queue.push(5); 20 | Assert.assertTrue(queue.peek()==3); 21 | Assert.assertTrue(!queue.empty()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/myStack/TestMyStack.java: -------------------------------------------------------------------------------- 1 | package myStack; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 225. Implement Stack using Queues 7 | */ 8 | public class TestMyStack { 9 | @Test 10 | public void test(){ 11 | MyStack stack=new MyStack(); 12 | stack.push(1); 13 | stack.push(2); 14 | stack.push(3); 15 | stack.push(4); 16 | Assert.assertTrue(stack.empty()==false); 17 | Assert.assertTrue(stack.pop()==4); 18 | Assert.assertTrue(stack.pop()==3); 19 | Assert.assertTrue(stack.top()==2); 20 | stack.push(5); 21 | Assert.assertTrue(stack.top()==5); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/palindromeNumber/TestPalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package palindromeNumber; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 9. Palindrome Number 8 | */ 9 | public class TestPalindromeNumber { 10 | @Test 11 | public void test() { 12 | PalindromeNumber solution = new PalindromeNumber(); 13 | boolean flag1 = solution.isPalindrome(1234567); 14 | Assert.assertTrue(!flag1); 15 | boolean flag2 = solution.isPalindrome(1234321); 16 | Assert.assertTrue(flag2); 17 | boolean flag3 = solution.isPalindrome(12344321); 18 | Assert.assertTrue(flag3); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/powXn/TestPowXn.java: -------------------------------------------------------------------------------- 1 | package powXn; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 50. Pow(x, n) 8 | */ 9 | public class TestPowXn { 10 | @Test 11 | public void test() { 12 | PowXn solution = new PowXn(); 13 | Assert.assertTrue(solution.myPow01(3, 9) == 19683); 14 | Assert.assertTrue(solution.myPow02(3, 9) == 19683); 15 | Assert.assertTrue(solution.myPow01(2.10000, -3)-0.10798<0.0001); 16 | Assert.assertTrue(solution.myPow02(2.10000, -3)-0.10798<0.0001); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/reverseWordsInAString/TestReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | package reverseWordsInAString; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 151. Reverse Words in a String 8 | */ 9 | public class TestReverseWordsInAString { 10 | @Test 11 | public void test() { 12 | ReverseWordsInAString solution = new ReverseWordsInAString(); 13 | String str = " the sky is blue "; 14 | String result = solution.reverseWords(str); 15 | Assert.assertTrue(result.equals("blue is sky the")); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/searchA2DMatrixII/Test_240.java: -------------------------------------------------------------------------------- 1 | package searchA2DMatrixII; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 240. Search a 2D Matrix II 7 | */ 8 | public class Test_240 { 9 | @Test 10 | public void test() { 11 | SearchA2DMatrixII solution = new SearchA2DMatrixII(); 12 | int[][] matrix = {{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, 13 | {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}; 14 | int target = 5; 15 | Assert.assertTrue(solution.searchMatrix(matrix, target)); 16 | target = 20; 17 | Assert.assertTrue(!solution.searchMatrix(matrix, target)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/searchRangeInBinarySearchTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package searchRangeInBinarySearchTree; 2 | 3 | /** 4 | * Created by leicao on 5/10/15. 5 | */ 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | TreeNode(int x) { val = x; } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/strStr/strStrTest.java: -------------------------------------------------------------------------------- 1 | package strStr; 2 | 3 | import com.sun.org.apache.xpath.internal.operations.Equals; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by leicao on 2/10/15. 9 | */ 10 | public class strStrTest { 11 | 12 | @org.junit.Test 13 | public void testStrStr() throws Exception { 14 | strStr strStr = new strStr(); 15 | String[][] inputs = { 16 | {"I am the haystack!","haystack!"}, 17 | {"I am the haystack!","haytack"}, 18 | }; 19 | int[] outputs = {9, -1}; 20 | for (int i = 0; i < inputs.length; i++) { 21 | assertEquals(outputs[i], strStr.strStr(inputs[i][0], inputs[i][1])); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/validAnagram/TestValidAnagram.java: -------------------------------------------------------------------------------- 1 | package validAnagram; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | /** 7 | * Test for 242. Valid Anagram 8 | */ 9 | public class TestValidAnagram { 10 | @Test 11 | public void test() { 12 | ValidAnagram solution = new ValidAnagram(); 13 | Assert.assertTrue(solution.isAnagram("anagram", "nagaram")); 14 | Assert.assertTrue(!solution.isAnagram("rat", "car")); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/validPalindrome/TestValidPalindrome.java: -------------------------------------------------------------------------------- 1 | package validPalindrome; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | /** 6 | * Test for 125. Valid Palindrome 7 | */ 8 | public class TestValidPalindrome { 9 | @Test 10 | public void test() { 11 | ValidPalindrome solution = new ValidPalindrome(); 12 | String str1 = "A man, a plan, a canal: Panama"; 13 | Assert.assertTrue(solution.isPalindrome(str1)); 14 | String str2 = "race a car"; 15 | Assert.assertTrue(!solution.isPalindrome(str2)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/algorithms/java/src/validateBinarySearchTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package validateBinarySearchTree; 2 | 3 | public class TreeNode { 4 | public int val; 5 | public TreeNode left, right; 6 | public TreeNode(int val) { 7 | this.val = val; 8 | this.left = this.right = null; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /leetcode/algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py: -------------------------------------------------------------------------------- 1 | def isOneBitCharacter(self, bits): 2 | i = 0 3 | while i < len(bits): 4 | if bits[i] == 0: 5 | i += 1 6 | if i >= len(bits): return True 7 | if bits[i] == 1: 8 | i += 2 9 | if i >= len(bits): return False 10 | if i == len(bits) - 1: return True -------------------------------------------------------------------------------- /leetcode/algorithms/python/AddOneRowToTree/addOneRow.py: -------------------------------------------------------------------------------- 1 | # get the nodes at (d - 1) layer: 2 | 3 | def addOneRow(self, root, v, d): 4 | dummy, dummy.left = TreeNode(v), root 5 | row = [dummy] 6 | for _ in range(d - 1): 7 | row = [kid for node in row for kid in (node.left, node.right) if kid] 8 | 9 | for node in row: 10 | node.left, node.left.left = TreeNode(v), node.left 11 | node.right, node.right.right = TreeNode(v), node.right 12 | return dummy.left -------------------------------------------------------------------------------- /leetcode/algorithms/python/BinaryTreeTilt/findTilt.py: -------------------------------------------------------------------------------- 1 | def findTilt(self, root): 2 | self.res = 0 3 | def helper(root): 4 | if not root: return 0 5 | left = helper(root.left) 6 | right = helper(root.right) 7 | self.res += abs(left - right) 8 | return root.val + left + right 9 | helper(root) 10 | return self.res -------------------------------------------------------------------------------- /leetcode/algorithms/python/BinaryTreeZigzagLevelOrderTraversal/zigzagLevelOrder.py: -------------------------------------------------------------------------------- 1 | """ 2 | simple bfs 3 | """ 4 | 5 | def zigzagLevelOrder(self, root): 6 | if not root: return [] 7 | stack = [[root]] 8 | res = [[root.val]] 9 | level = 0 10 | while True: 11 | level += 1 12 | children = [child for node in stack[-1] for child in (node.left, node.right) if child] 13 | if not children: break 14 | temp = [node.val for node in children] 15 | if level % 2 == 1: temp.reverse() 16 | res.append(temp) 17 | stack.append(children) 18 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/CheckCompletenessOfABinaryTree/isCompleteTree.py: -------------------------------------------------------------------------------- 1 | def isCompleteTree(self, root): 2 | stack = [[(root, 0)]] 3 | layer = 0 4 | while True: 5 | children = [] 6 | for node, value in stack[-1]: 7 | if node.left: children.append((node.left, 2 * value)) 8 | if node.right: children.append((node.right, 2 * value + 1)) 9 | if node.right and not node.left: return False 10 | if not children: break 11 | if len(stack[-1]) != pow(2, layer): return False 12 | stack.append(children) 13 | layer += 1 14 | return len(stack[-1]) == stack[-1][-1][1] + 1 -------------------------------------------------------------------------------- /leetcode/algorithms/python/ConstructBinaryTreeFromInorderAndPostorderTraversal/buildTree.py: -------------------------------------------------------------------------------- 1 | def buildTree(self, inorder, postorder): 2 | if inorder: 3 | i = inorder.index(postorder.pop()) 4 | root = TreeNode(inorder[i]) 5 | root.right = self.buildTree(inorder[i+1:], postorder) 6 | root.left = self.buildTree(inorder[:i], postorder) 7 | return root -------------------------------------------------------------------------------- /leetcode/algorithms/python/ConstructBinaryTreeFromPreorderAndInorderTraversal/buildTree.py: -------------------------------------------------------------------------------- 1 | def buildTree(self, preorder, inorder): 2 | if inorder: 3 | i = inorder.index(preorder.pop(0)) 4 | root = TreeNode(inorder[i]) 5 | root.left = self.buildTree(preorder, inorder[:i]) 6 | root.right = self.buildTree(preorder, inorder[i+1:]) 7 | return root -------------------------------------------------------------------------------- /leetcode/algorithms/python/ContainsDuplicateII/containsNearbyDuplicate.py: -------------------------------------------------------------------------------- 1 | # Method 1: using set 2 | 3 | def containsNearbyDuplicate(self, nums, k): 4 | if len(nums) <= k + 1: return len(nums) != len(set(nums)) 5 | if k == 0: return False 6 | s = set(nums[:k]) 7 | for i in range(k, len(nums)): 8 | if nums[i] in s: return True 9 | else: 10 | s.remove(nums[i - k]) 11 | s.add(nums[i]) 12 | return False 13 | 14 | # Method 2: using dictionary 15 | def containsNearbyDuplicate(self, nums, k): 16 | d = {} 17 | for i, n in enumerate(nums): 18 | if n in d and i - d[n] <= k: 19 | return True 20 | d[n] = i 21 | return False 22 | -------------------------------------------------------------------------------- /leetcode/algorithms/python/ContainsDuplicateIII/containsNearbyAlmostDuplicate.py: -------------------------------------------------------------------------------- 1 | def containsNearbyAlmostDuplicate(self, nums, k, t): 2 | if k < 1 or t < 0: return False 3 | d = {} 4 | w = t + 1 5 | for i, n in enumerate(nums): 6 | m = n // w 7 | if m in d: return True 8 | if m - 1 in d and abs(d[m-1] - n) <= t: return True 9 | if m + 1 in d and abs(d[m+1] - n) <= t: return True 10 | d[m] = n 11 | if i >= k: del d[nums[i - k] // w] 12 | return False -------------------------------------------------------------------------------- /leetcode/algorithms/python/ConvertBSTtoGreaterTree/convertBST.py: -------------------------------------------------------------------------------- 1 | """ 2 | since this is a BST, we can do a inorder traversal (inversed, from right to left), 3 | during this process, track the sum and update the node.val 4 | """ 5 | 6 | class Solution: 7 | def convertBST(self, root): 8 | self.total = 0 9 | 10 | def helper(node): 11 | if not node: return 12 | helper(node.right) 13 | node.val += self.total 14 | self.total = node.val 15 | helper(node.left) 16 | 17 | helper(root) 18 | return root -------------------------------------------------------------------------------- /leetcode/algorithms/python/CountCompleteTreeNodes/countNodes.py: -------------------------------------------------------------------------------- 1 | def countNodes(self, root): 2 | if not root: return 0 3 | hl, hr = 0, 0 4 | l, r = root, root 5 | while l: 6 | hl += 1 7 | l = l.left 8 | while r: 9 | hr += 1 10 | r = r.right 11 | if hl == hr: return pow(2, hl) - 1 12 | return 1 + self.countNodes(root.left) + self.countNodes(root.right) -------------------------------------------------------------------------------- /leetcode/algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | def diameterOfBinaryTree(self, root): 2 | self.res = 0 3 | def helper(root): 4 | if not root: return 0 5 | left, right = helper(root.left), helper(root.right) 6 | self.res = max(self.res, left + right) 7 | return 1 + max(left, right) 8 | helper(root) 9 | return self.res -------------------------------------------------------------------------------- /leetcode/algorithms/python/DifferentWaysToAddParentheses/diffWaysToCompute.py: -------------------------------------------------------------------------------- 1 | def diffWaysToCompute(self, input): 2 | return [a + b if c == '+' else a - b if c == '-' else a * b \ 3 | for i, c in enumerate(input) if c in '+-*' \ 4 | for a in self.diffWaysToCompute(input[:i]) \ 5 | for b in self.diffWaysToCompute(input[i+1:])] or [int(input)] -------------------------------------------------------------------------------- /leetcode/algorithms/python/FibonacciNumber/fib.py: -------------------------------------------------------------------------------- 1 | """ 2 | Method 1: iterative: 3 | """ 4 | def fib1(self, N): 5 | if N <= 1: return N 6 | a, b = 0, 1 7 | for _ in range(2, N + 1): 8 | a, b = b, a + b 9 | return b 10 | 11 | """ 12 | Method 2: recursive without memorization: 13 | """ 14 | def fib2(self, N): 15 | if N <= 1: return N 16 | return self.fib(N - 1) + self.fib(N - 2) 17 | 18 | """ 19 | Method 3: recursive with memorization 20 | """ 21 | def fib3(self, N): 22 | memo = {0:0, 1:1} 23 | def helper(n): 24 | if n not in memo: 25 | memo[n] = helper(n - 1) + helper(n - 2) 26 | return memo[n] 27 | return helper(N) -------------------------------------------------------------------------------- /leetcode/algorithms/python/FindDuplicateSubtrees/findDuplicateSubtrees.py: -------------------------------------------------------------------------------- 1 | def findDuplicateSubtrees(self, root): 2 | nodes = collections.defaultdict(list) 3 | 4 | def helper(root): 5 | if not root: return 'None' 6 | struct = '%s,%s,%s' % (str(root.val), helper(root.left), helper(root.right)) 7 | nodes[struct].append(root) 8 | return struct 9 | 10 | helper(root) 11 | return [nodes[struct][0] for struct in nodes if len(nodes[struct]) > 1] -------------------------------------------------------------------------------- /leetcode/algorithms/python/FindTheDuplicateNumber/findDuplicate.py: -------------------------------------------------------------------------------- 1 | # the same as linked list cycle problem 2 | def findDuplicate(self, nums): 3 | if len(nums) <= 1: return -1 4 | slow, fast = nums[0], nums[nums[0]] 5 | while slow != fast: 6 | slow = nums[slow] 7 | fast = nums[nums[fast]] 8 | 9 | fast = 0 10 | while slow != fast: 11 | slow = nums[slow] 12 | fast = nums[fast] 13 | return slow -------------------------------------------------------------------------------- /leetcode/algorithms/python/FlattenBinaryTreeToLinkedList/flatten.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def __init__(self): 3 | self.prev = None 4 | 5 | def flatten(self, root): 6 | if not root: return None 7 | self.flatten(root.right) 8 | self.flatten(root.left) 9 | root.right = self.prev 10 | root.left = None 11 | self.prev = root -------------------------------------------------------------------------------- /leetcode/algorithms/python/FlipBinaryTreeToMatchPreorderTraversal/flipMatchVoyage.py: -------------------------------------------------------------------------------- 1 | def flipMatchVoyage(self, root, voyage): 2 | res = [] 3 | self.i = 0 4 | def dfs(root): 5 | if not root: return True 6 | if root.val != voyage[self.i]: return False 7 | self.i += 1 8 | if root.left and root.left.val != voyage[self.i]: 9 | res.append(root.val) 10 | root.left, root.right = root.right, root.left 11 | return dfs(root.left) and dfs(root.right) 12 | return res if dfs(root) else [-1] -------------------------------------------------------------------------------- /leetcode/algorithms/python/HouseRobber/rob.py: -------------------------------------------------------------------------------- 1 | def rob(self, nums): 2 | temp = [0, 0] 3 | for n in nums: 4 | temp[0], temp[1] = max(temp), n + temp[0] 5 | 6 | return max(temp) -------------------------------------------------------------------------------- /leetcode/algorithms/python/ImageSmoother/imageSmoother.py: -------------------------------------------------------------------------------- 1 | def imageSmoother(self, M): 2 | from copy import deepcopy 3 | 4 | if not M or not M[0]: return [[]] 5 | row, col = len(M), len(M[0]) 6 | res = deepcopy(M) 7 | for x in range(row): 8 | for y in range(col): 9 | temp = [M[i][j] for i in [x - 1, x, x + 1] for j in [y - 1, y, y + 1] if \ 10 | 0 <= i < row and 0 <= j < col] 11 | res[x][y] = sum(temp) // len(temp) 12 | 13 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/InsertionSortList/insertionSortList.py: -------------------------------------------------------------------------------- 1 | def insertionSortList(self, head): 2 | if not head: return head 3 | 4 | dummy = ListNode(0) 5 | curr = head 6 | prev = dummy 7 | 8 | while curr: 9 | next = curr.next 10 | while prev.next and prev.next.val < curr.val: 11 | prev = prev.next 12 | 13 | curr.next = prev.next 14 | prev.next = curr 15 | prev = dummy 16 | 17 | curr = next 18 | 19 | return dummy.next -------------------------------------------------------------------------------- /leetcode/algorithms/python/K-diffPairsInAnArray/findPairs.py: -------------------------------------------------------------------------------- 1 | def findPairs(self, nums, k): 2 | if k > 0: 3 | return len(set(nums) & set(a + k for a in nums)) 4 | elif k == 0: 5 | return sum(v > 1 for v in collections.Counter(nums).values()) 6 | return 0 -------------------------------------------------------------------------------- /leetcode/algorithms/python/KthSmallestElementInABST/kthSmallest.py: -------------------------------------------------------------------------------- 1 | # Method 1: recursive in-order traversal 2 | def kthSmallest1(self, root, k): 3 | inorder = [] 4 | def helper(root): 5 | if root: 6 | helper(root.left) 7 | inorder.append(root.val) 8 | helper(root.right) 9 | 10 | helper(root) 11 | return inorder[k-1] 12 | 13 | # Method 2: iterative in-order traversal 14 | def kthSmallest2(self, root, k): 15 | stack = [] 16 | while root or stack: 17 | while root: 18 | stack.append(root) 19 | root = root.left 20 | root = stack.pop() 21 | k -= 1 22 | if k == 0: return root.val 23 | root = root.right -------------------------------------------------------------------------------- /leetcode/algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py: -------------------------------------------------------------------------------- 1 | def dominantIndex(self, nums): 2 | i = nums.index(max(nums)) 3 | l = nums[i] 4 | del nums[i] 5 | if not nums: return 0 6 | return i if l >= 2 * max(nums) else -1 -------------------------------------------------------------------------------- /leetcode/algorithms/python/LargestPerimeterTriangle/largestPerimeter.py: -------------------------------------------------------------------------------- 1 | def largestPerimeter(self, A): 2 | A.sort() 3 | n = len(A) 4 | for i in range(1, len(A) - 1): 5 | if A[n - i - 2] + A[n - i - 1] > A[n - i]: 6 | return A[n - i - 2] + A[n - i - 1] + A[n - i] 7 | return 0 -------------------------------------------------------------------------------- /leetcode/algorithms/python/LinkedListCycleII/detectCycle.py: -------------------------------------------------------------------------------- 1 | def detectCycle(self, head): 2 | slow, fast = head, head 3 | while fast and fast.next: 4 | slow = slow.next 5 | fast = fast.next.next 6 | if slow == fast: break 7 | 8 | if not fast or not fast.next: return None 9 | slow = head 10 | while slow != fast: 11 | slow = slow.next 12 | fast = fast.next 13 | return slow -------------------------------------------------------------------------------- /leetcode/algorithms/python/LongestConsecutiveSequence/LongestConsecutive.py: -------------------------------------------------------------------------------- 1 | def longestConsecutive(self, nums): 2 | 3 | #first, create a hashmap 4 | hm = set(nums) 5 | longest = 0 6 | #find the longest consecutive sequence from each number in the new 7 | #hashmap (set) 8 | for num in hm: 9 | if (num - 1) not in hm: 10 | current = num + 1 11 | cons = 1 12 | while current in hm: 13 | current += 1 14 | cons += 1 15 | if cons > longest: 16 | longest = cons 17 | 18 | return longest -------------------------------------------------------------------------------- /leetcode/algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py: -------------------------------------------------------------------------------- 1 | def findLengthOfLCIS(self, nums): 2 | if not nums: return 0 3 | res = 1 4 | temp = 1 5 | for i in range(1, len(nums)): 6 | if nums[i] > nums[i - 1]: 7 | temp += 1 8 | else: 9 | res = max(temp, res) 10 | temp = 1 11 | return max(temp, res) -------------------------------------------------------------------------------- /leetcode/algorithms/python/LongestTurbulentSubarray/maxTurbulenceSize.py: -------------------------------------------------------------------------------- 1 | def maxTurbulenceSize(self, A): 2 | res = inc = dec = 1 3 | for i in range(1, len(A)): 4 | if A[i] > A[i - 1]: 5 | inc = dec + 1 6 | dec = 1 7 | elif A[i] < A[i - 1]: 8 | dec = inc + 1 9 | inc = 1 10 | else: 11 | inc = 1 12 | dec = 1 13 | res = max(res, max(inc, dec)) 14 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/LongestUnivaluePath/longestUnivaluePath.py: -------------------------------------------------------------------------------- 1 | def longestUnivaluePath(self, root): 2 | self.longest = 0 3 | def helper(root): 4 | if not root: return 0 5 | l, r = helper(root.left), helper(root.right) 6 | left = (l + 1) if root.left and root.left.val == root.val else 0 7 | right = (r + 1) if root.right and root.right.val == root.val else 0 8 | self.longest = max(self.longest, left + right) 9 | return max(left, right) 10 | helper(root) 11 | return self.longest -------------------------------------------------------------------------------- /leetcode/algorithms/python/LowestCommonAncestorOfABinarySearchTree/lowestCommonAncestor.py: -------------------------------------------------------------------------------- 1 | # straight forward recursive solution 2 | 3 | def lowestCommonAncestor(self, root, p, q): 4 | if not root: return None 5 | if root.val > p.val and root.val > q.val: 6 | return self.lowestCommonAncestor(root.left, p, q) 7 | elif root.val < p.val and root.val < q.val: 8 | return self.lowestCommonAncestor(root.right, p, q) 9 | return root -------------------------------------------------------------------------------- /leetcode/algorithms/python/LowestCommonAncestorOfABinaryTree/lowestCommonAncestor.py: -------------------------------------------------------------------------------- 1 | def lowestCommonAncestor(self, root, p, q): 2 | if root in (None, p, q): return root 3 | left = self.lowestCommonAncestor(root.left, p, q) 4 | right = self.lowestCommonAncestor(root.right, p, q) 5 | return root if left and right else left or right -------------------------------------------------------------------------------- /leetcode/algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py: -------------------------------------------------------------------------------- 1 | def maxDistToClosest(self, seats): 2 | first = seats.index(1) 3 | last = 0 4 | for i in range(len(seats) - 1, -1, -1): 5 | if seats[i]: 6 | last = i 7 | break 8 | res = 0 9 | temp = 0 10 | for i in range(first, last + 1): 11 | if seats[i] == 1: 12 | res = max(temp, res) 13 | temp = 0 14 | else: 15 | temp += 1 16 | return max(first, len(seats) - last - 1, (res + 1) // 2) -------------------------------------------------------------------------------- /leetcode/algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py: -------------------------------------------------------------------------------- 1 | # Method 1: sliding window 2 | 3 | def findMaxAverage(self, nums, k): 4 | total = 0 5 | temp = float('-inf') 6 | for i, n in enumerate(nums): 7 | total += n 8 | if i >= k: total -= nums[i- k] 9 | if i >= k - 1: 10 | temp = max(temp, total) 11 | return temp / k 12 | 13 | 14 | 15 | # Method 2: prefix sum 16 | def findMaxAverage(self, nums, k): 17 | temp = [0] 18 | for n in nums: 19 | temp.append(temp[-1] + n) 20 | 21 | res = max(temp[i + k] - temp[i] for i in range(len(nums) - k + 1)) 22 | return res / k -------------------------------------------------------------------------------- /leetcode/algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py: -------------------------------------------------------------------------------- 1 | # simply find the three largest and two smallest 2 | # Method 1: sort 3 | def maximumProduct(self, nums): 4 | nums.sort() 5 | return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3]) 6 | 7 | # Method 2: using heapq, O(n) time 8 | def maximumProduct(self, nums): 9 | import heapq 10 | a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums) 11 | return max(a[0] * a[1] * a[2], a[0] * b[0] * b[1]) -------------------------------------------------------------------------------- /leetcode/algorithms/python/MaximumWidthOfBinaryTree/widthOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | def widthOfBinaryTree(self, root): 2 | if not root: return 0 3 | stack = [[(root, 0)]] 4 | res = 1 5 | while True: 6 | children = [] 7 | for node, value in stack[-1]: 8 | if node.left: children.append((node.left, value * 2)) 9 | if node.right: children.append((node.right, value * 2 + 1)) 10 | if not children: break 11 | stack.append(children) 12 | res = max(res, children[-1][1] - children[0][1] + 1) 13 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/MiddleOfTheLinkedList/middleOfTheLinkedList.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def middleNode(self, head: ListNode) -> ListNode: 9 | aux = head 10 | cont = 1 11 | while aux.next: 12 | cont += 1 13 | aux = aux.next 14 | print(cont) 15 | if cont%2 == 0: 16 | posicao = (cont/2)+1 17 | else: 18 | posicao = (cont//2)+1 19 | aux = head 20 | cont = 1 21 | while True: 22 | if cont == posicao: 23 | return aux 24 | aux = aux.next 25 | cont += 1 -------------------------------------------------------------------------------- /leetcode/algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py: -------------------------------------------------------------------------------- 1 | def minCostClimbingStairs(self, cost): 2 | temp = [0, cost[0]] 3 | for i in range(1, len(cost)): 4 | temp[0], temp[1] = temp[1], min(temp) + cost[i] 5 | return min(temp) -------------------------------------------------------------------------------- /leetcode/algorithms/python/Non-decreasingArray/checkPossibility.py: -------------------------------------------------------------------------------- 1 | def checkPossibility(self, nums): 2 | count = 0 3 | for i in range(1, len(nums)): 4 | if nums[i] < nums[i - 1]: 5 | count += 1 6 | if i == 1 or nums[i - 2] <= nums[i]: nums[i - 1] = nums[i] 7 | else: nums[i] = nums[i - 1] 8 | 9 | if count >= 2: return False 10 | return True -------------------------------------------------------------------------------- /leetcode/algorithms/python/PancakeSorting/pancakeSort.py: -------------------------------------------------------------------------------- 1 | """ 2 | basic idea: find the index of smallest element in A, filp the list from that index, this makes the smallest element 3 | comes to the first, then filp the whole list, to make smallest element goes to the tail. And then delete that element. 4 | 5 | Do this step until all the smallest element comes to the tail, then just filp the whole list again, and we can get what we want 6 | """ 7 | 8 | def pancakeSort(self, A): 9 | res = [] 10 | n = len(A) 11 | while A: 12 | smallest = A.index(min(A)) 13 | res.append(smallest + 1) 14 | res.append(len(A)) 15 | A = list(reversed(A[:smallest + 1])) + A[smallest + 1:] 16 | A.reverse() 17 | del A[-1] 18 | res.append(n) 19 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/PartitionList/partition.py: -------------------------------------------------------------------------------- 1 | def partition(self, head, x): 2 | h1 = l1 = ListNode(0) 3 | h2 = l2 = ListNode(0) 4 | while head: 5 | if head.val < x: 6 | l1.next = head 7 | l1 = l1.next 8 | else: 9 | l2.next = head 10 | l2 = l2.next 11 | head = head.next 12 | l2.next = None 13 | l1.next = h2.next 14 | return h1.next -------------------------------------------------------------------------------- /leetcode/algorithms/python/PathSumIII/pathSum.py: -------------------------------------------------------------------------------- 1 | def pathSum(self, root, target): 2 | self.result = 0 3 | cache = {0:1} 4 | 5 | def dfs(root, currPathSum): 6 | if not root: return 7 | 8 | currPathSum += root.val 9 | oldPathSum = currPathSum - target 10 | 11 | self.result += cache.get(oldPathSum, 0) 12 | cache[currPathSum] = cache.get(currPathSum, 0) + 1 13 | 14 | 15 | dfs(root.left, currPathSum) 16 | dfs(root.right, currPathSum) 17 | 18 | cache[currPathSum] -= 1 19 | 20 | dfs(root, 0) 21 | return self.result -------------------------------------------------------------------------------- /leetcode/algorithms/python/PopulatingNextRightPointersInEachNode/connect.py: -------------------------------------------------------------------------------- 1 | def connect(self, root): 2 | if not root: return 3 | stack = [[root]] 4 | while True: 5 | children = [child for node in stack[-1] for child in (node.left, node.right) if child] 6 | if not children: break 7 | stack.append(children) 8 | for i in range(len(children) - 1): 9 | children[i].next = children[i+1] -------------------------------------------------------------------------------- /leetcode/algorithms/python/PopulatingNextRightPointersInEachNodeII/connect.py: -------------------------------------------------------------------------------- 1 | def connect(self, root): 2 | if not root: return root 3 | stack = [[root]] 4 | while True: 5 | children = [child for node in stack[-1] for child in (node.left, node.right) if child] 6 | if not children: break 7 | stack.append(children) 8 | for i in range(len(children) - 1): 9 | children[i].next = children[i + 1] -------------------------------------------------------------------------------- /leetcode/algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py: -------------------------------------------------------------------------------- 1 | def largeGroupPositions(self, S): 2 | res = [] 3 | i = 0 4 | while i < len(S) - 2: 5 | if S[i] == S[i + 1] and S[i] == S[i + 2]: 6 | val = S[i] 7 | index = i 8 | while i < len(S) and S[i] == val: 9 | i += 1 10 | res.append([index, i - 1]) 11 | i -= 1 12 | i += 1 13 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/RemoveDuplicatesFromSortedListII/deleteDuplicates.py: -------------------------------------------------------------------------------- 1 | def deleteDuplicates(self, head): 2 | dummy = prev = ListNode(0) 3 | dummy.next = head 4 | while head and head.next: 5 | if head.val == head.next.val: 6 | while head and head.next and head.val == head.next.val: 7 | head = head.next 8 | head = head.next 9 | prev.next = head 10 | else: 11 | prev = prev.next 12 | head = head.next 13 | return dummy.next -------------------------------------------------------------------------------- /leetcode/algorithms/python/RemoveNthNodeFromEndOfList/removeNthFromEnd.py: -------------------------------------------------------------------------------- 1 | def removeNthFromEnd(self, head, n): 2 | slow = fast = head 3 | for i in range(n): 4 | fast = fast.next 5 | if not fast: return head.next 6 | while fast.next: 7 | fast = fast.next 8 | slow = slow.next 9 | slow.next = slow.next.next 10 | return head -------------------------------------------------------------------------------- /leetcode/algorithms/python/RevealCardsInIncreasingOrder/deckRevealedIncreasing.py: -------------------------------------------------------------------------------- 1 | def deckRevealedIncreasing(self, deck): 2 | deck.sort() 3 | res = [0] * len(deck) 4 | index = list(range(len(deck))) 5 | 6 | for i in range(len(deck)): 7 | res[index.pop(0)] = deck[i] 8 | if index: index.append(index.pop(0)) 9 | return res -------------------------------------------------------------------------------- /leetcode/algorithms/python/ReverseLinkedListII/reverseBetween.py: -------------------------------------------------------------------------------- 1 | def reverseBetween(self, head, m, n): 2 | if not head or n == m: return head 3 | p = dummy = ListNode(0) 4 | dummy.next = head 5 | for _ in range(m - 1): 6 | p = p.next 7 | tail = p.next 8 | 9 | for _ in range(n - m): 10 | temp = p.next 11 | p.next = tail.next 12 | tail.next = tail.next.next 13 | p.next.next = temp 14 | return dummy.next -------------------------------------------------------------------------------- /leetcode/algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py: -------------------------------------------------------------------------------- 1 | def findUnsortedSubarray(self, nums): 2 | same = [a == b for a, b in zip(nums, sorted(nums))] 3 | return 0 if all(same) else len(nums) - same.index(False) - same[::-1].index(False) -------------------------------------------------------------------------------- /leetcode/algorithms/python/SingleNumberII/SingleNumberII.py: -------------------------------------------------------------------------------- 1 | def singleNumber(self, nums): 2 | 3 | #1. make hashmap 4 | #2. while traversing list, add each element 5 | #3. remove it once it has been seen 3 times 6 | #4. finally, the only value left is the one we're looking for 7 | 8 | hashmap = defaultdict(int) 9 | for num in nums: 10 | hashmap[num] += 1 11 | if hashmap[num] == 3: 12 | del hashmap[num] 13 | 14 | singleNum = hashmap.keys()[0] 15 | return singleNum 16 | -------------------------------------------------------------------------------- /leetcode/algorithms/python/SquaresOfSortedArray/sortedSquares.py: -------------------------------------------------------------------------------- 1 | def sortedSquares(self, A): 2 | return list(sorted([a ** 2 for a in A])) -------------------------------------------------------------------------------- /leetcode/algorithms/python/Subsets/subsets.py: -------------------------------------------------------------------------------- 1 | def subsets(self, nums): 2 | res = [] 3 | def backtracking(temp, start): 4 | res.append(temp[:]) 5 | for i in range(start, len(nums)): 6 | temp.append(nums[i]) 7 | backtracking(temp, i + 1) 8 | temp.pop() 9 | 10 | backtracking([], 0) 11 | return res 12 | -------------------------------------------------------------------------------- /leetcode/algorithms/python/SubtreeOfAnotherTree/isSubtree.py: -------------------------------------------------------------------------------- 1 | def isSubtree(self, s, t): 2 | stack = [s] 3 | while stack: 4 | node = stack.pop(0) 5 | if node.val == t.val: 6 | if self.check(node, t): return True 7 | stack += [child for child in [node.left, node.right] if child] 8 | return False 9 | 10 | def check(self, first, second): 11 | if not first and not second: 12 | return True 13 | if first and second: 14 | return first.val == second.val and self.check(first.left, second.left) and self.check(first.right, second.right) 15 | return False -------------------------------------------------------------------------------- /leetcode/algorithms/python/SumOfLeftLeaves/sumOfLeftLeaves.py: -------------------------------------------------------------------------------- 1 | """ 2 | straight forward recursive solution: 3 | if left node is leave, add the value and the the right subtree 4 | if not, then recursively call left and right subtree 5 | """ 6 | def sumOfLeftLeaves(self, root): 7 | if not root: return 0 8 | if root.left and not root.left.left and not root.left.right: 9 | return root.left.val + self.sumOfLeftLeaves(root.right) 10 | return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) -------------------------------------------------------------------------------- /leetcode/algorithms/python/ThirdMaximumNumber/thirdMax.py: -------------------------------------------------------------------------------- 1 | def thirdMax(self, nums): 2 | if len(set(nums)) < 3: return max(nums) 3 | first = second = third = float('-inf') 4 | for n in nums: 5 | if n > first: 6 | third = second 7 | second = first 8 | first = n 9 | elif second < n < first: 10 | third = second 11 | second = n 12 | elif third < n < second: 13 | third = n 14 | return third -------------------------------------------------------------------------------- /leetcode/algorithms/python/UniqueBinarySearchTrees/numTrees.py: -------------------------------------------------------------------------------- 1 | def numTrees(self, n): 2 | if n == 1: return 1 3 | res = [1, 1] 4 | for i in range(2, n + 1): 5 | val = 0 6 | for j in range(i): 7 | val += res[j] * res[i - j - 1] 8 | res.append(val) 9 | return res[n] -------------------------------------------------------------------------------- /leetcode/algorithms/python/ValidMountainArray/validMountainArray.py: -------------------------------------------------------------------------------- 1 | # Method 1: using index find the max first, and then process 2 | 3 | def validMountainArray(self, A): 4 | if len(A) < 3: return False 5 | index = A.index(max(A)) 6 | if index == 0 or index == len(A) -1: return False 7 | for i in range(1, len(A)): 8 | if i <= index: 9 | if A[i] <= A[i - 1]: return False 10 | else: 11 | if A[i] >= A[i - 1]: return False 12 | return True 13 | 14 | 15 | # Method 2: one pass, using two pointers trace from the begining and end 16 | def validMountainArray(self, A): 17 | i, j = 0, len(A) - 1 18 | while i < len(A) - 1 and A[i] < A[i + 1]: i += 1 19 | while j > 0 and A[j - 1] > A[j]: j -= 1 20 | return 0 < i == j < len(A) - 1 -------------------------------------------------------------------------------- /leetcode/algorithms/python/XOfAKindInADeckOfCards/hasGroupsSizeX.py: -------------------------------------------------------------------------------- 1 | # Method 1: find the greatest common divisor using iteration 2 | 3 | def hasGroupsSizeX(self, deck): 4 | if len(deck) < 2: return False 5 | vals = collections.Counter(deck).values() 6 | for n in range(2, max(vals) + 1): 7 | if all(v % n == 0 for v in vals): return True 8 | return False 9 | 10 | # Method 2: find the greatest common divisor using reduce 11 | # Time complexity: O(n) 12 | def hasGroupsSizeX(self, deck): 13 | from functools import reduce 14 | if len(deck) < 2: return False 15 | vals = collections.Counter(deck).values() 16 | def gcd(a, b): 17 | while b: a, b = b, a % b 18 | return a 19 | return reduce(gcd, vals) -------------------------------------------------------------------------------- /leetcode/database/README.md: -------------------------------------------------------------------------------- 1 | ### LeetCode Database 2 | 3 | 4 | | # | Title | Solution | Difficulty | 5 | |---| ----- | -------- | ---------- | 6 | |1|[Trips and Users](https://leetcode.com/problems/trips-and-users/)| [MySQL](./TripsAndUsers.sql)|Hard| 7 | -------------------------------------------------------------------------------- /leetcode/database/TripsAndUsers.sql: -------------------------------------------------------------------------------- 1 | SELECT t.`Request_at` AS Day, 2 | ROUND(COUNT(CASE WHEN t.`Status` = 'cancelled_by_driver' OR t.`Status` = 'cancelled_by_client' THEN 1 END) / COUNT(*), 2) AS "Cancellation Rate" 3 | FROM Trips t 4 | INNER JOIN Users u 5 | ON t.Client_Id = u.Users_Id 6 | WHERE u.Banned = 'No' 7 | AND t.Request_at >= '2013-10-01' 8 | AND t.Request_at <= '2013-10-03' 9 | GROUP BY t.Request_at -------------------------------------------------------------------------------- /leetcode/shell/README.md: -------------------------------------------------------------------------------- 1 | ###LeetCode Shell 2 | 3 | 4 | | # | Title | Solution | Difficulty | 5 | |---| ----- | -------- | ---------- | 6 | |4|[Tenth Line](https://leetcode.com/problems/tenth-line/)| [Bash](./TenthLine.sh)|Easy| 7 | |3|[Transpose File](https://leetcode.com/problems/transpose-file/)| [Bash](./TransposeFile.sh)|Medium| 8 | |2|[Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers/)| [Bash](./ValidPhoneNumbers.sh)|Easy| 9 | |1|[Word Frequency](https://leetcode.com/problems/word-frequency/)| [Bash](./WordFrequency.sh)|Medium| 10 | -------------------------------------------------------------------------------- /translations/how-to.md: -------------------------------------------------------------------------------- 1 | Please put new translation README files here. 2 | 3 | I'll migrate the existing translations when they are ready. 4 | 5 | To start a new translation, please: 6 | 7 | 1. Make an issue (for collaboration with other translators) 8 | 2. Make a pull request to collaborate and commit to. 9 | 3. Let me know when it's ready to pull. 10 | 11 | Thank you! 12 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/db/api.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import "github.com/brecode/urlLookup/model" 4 | 5 | // API is the interface for accessing the underlying data store 6 | type API interface { 7 | // Get returns data information and true/false if the key is found 8 | Get(key string) (*model.URLData, bool) 9 | 10 | // Update exposes an API to save new data into the data store 11 | Update(url *model.URLData) error 12 | } 13 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/Dockerfile.updater: -------------------------------------------------------------------------------- 1 | FROM golang:1.13-alpine as builder 2 | 3 | # we want a static binary 4 | ENV CGO_ENABLED=0 5 | 6 | RUN apk add --update git make 7 | 8 | COPY . /go/src/github.com/brecode/urlLookup 9 | 10 | WORKDIR /go/src/github.com/brecode/urlLookup/cmd/updater 11 | 12 | RUN go build -i -v -o updater 13 | 14 | FROM scratch 15 | 16 | COPY --from=builder /go/src/github.com/brecode/urlLookup/cmd/updater/updater /updater 17 | 18 | COPY --from=builder /go/src/github.com/brecode/urlLookup/docker/updater-conf/updater.conf /opt/updater/updater.conf 19 | 20 | ENTRYPOINT ["/updater", "-c", "/opt/updater/updater.conf"] 21 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/Dockerfile.webservice: -------------------------------------------------------------------------------- 1 | FROM golang:1.13-alpine as builder 2 | 3 | # we want a static binary 4 | ENV CGO_ENABLED=0 5 | 6 | RUN apk add --update git make 7 | 8 | COPY . /go/src/github.com/brecode/urlLookup 9 | 10 | WORKDIR /go/src/github.com/brecode/urlLookup/cmd/svc 11 | 12 | RUN go build -i -v -o svc 13 | 14 | FROM scratch 15 | 16 | COPY --from=builder /go/src/github.com/brecode/urlLookup/cmd/svc/svc /svc 17 | 18 | COPY --from=builder /go/src/github.com/brecode/urlLookup/docker/svc-conf/svc.conf /opt/svc/svc.conf 19 | 20 | ENTRYPOINT ["/svc", "-c", "/opt/svc/svc.conf", "-p", "${LISTEN_PORT}", "-a", "${LISTEN_ADDR}"] 21 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/nginx-conf/nginx.conf: -------------------------------------------------------------------------------- 1 | events { 2 | worker_connections 1024; # default is 1024, and this section is required 3 | } 4 | 5 | http { 6 | resolver 127.0.0.11 ipv6=off valid=30s; # required for proxy_pass if you append URL bits ($1 below). this is Docker's static DNS IP 7 | server { 8 | listen 80; 9 | 10 | location / { 11 | proxy_pass http://urllookup:32697; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/redis-conf/redis-1-master.conf: -------------------------------------------------------------------------------- 1 | protected-mode no 2 | port 6379 3 | dir . 4 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/redis-conf/redis-1-slave.conf: -------------------------------------------------------------------------------- 1 | protected-mode no 2 | port 6379 3 | dir . 4 | slaveof 10.5.5.91 6379 5 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/svc-conf/svc.conf: -------------------------------------------------------------------------------- 1 | redis: 2 | address: redis1:6379 3 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/docker/updater-conf/updater.conf: -------------------------------------------------------------------------------- 1 | redis: 2 | address: redis1:6379 3 | updater: 4 | timeInterval: 10 5 | dirPath: "/data/blacklist" 6 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/brecode/urlLookup 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/ghodss/yaml v1.0.0 7 | github.com/go-redis/redis v6.15.6+incompatible 8 | github.com/gorilla/mux v1.7.3 9 | github.com/kr/pretty v0.1.0 // indirect 10 | github.com/onsi/ginkgo v1.10.3 // indirect 11 | github.com/onsi/gomega v1.7.1 // indirect 12 | github.com/sirupsen/logrus v1.4.2 13 | github.com/spf13/pflag v1.0.5 14 | golang.org/x/net v0.0.0-20191126235420-ef20fe5d7933 15 | golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect 16 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect 17 | ) 18 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/handler/api.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | // API is the interface for accessing the handler's functions for defined CRUD operations 8 | type API interface { 9 | // GetUrlInfo is the handler for the query of a malicious URL (GET) 10 | GetURLData() http.HandlerFunc 11 | 12 | // UpdateUrlInfo is the handler for adding malicious url (POST) 13 | UpdateURLData() http.HandlerFunc 14 | } 15 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/model/url.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | // URLData hols the information of a URL query 4 | type URLData struct { 5 | // URL holds the original URL path 6 | Url string `json:"url"` 7 | // isSafe returns the result of a proxy query 8 | IsSafe bool `json:"isSafe"` 9 | } 10 | -------------------------------------------------------------------------------- /urlLookup-codingchallenge/utils.go: -------------------------------------------------------------------------------- 1 | package urlLookup 2 | 3 | import ( 4 | "crypto/sha1" 5 | "strings" 6 | 7 | "golang.org/x/net/publicsuffix" 8 | ) 9 | 10 | // GetSha calculates a sha1 hash value 11 | func GetSha(k string) []byte { 12 | h := sha1.New() 13 | h.Write([]byte(k)) 14 | bs := h.Sum(nil) 15 | 16 | return bs 17 | } 18 | 19 | // GetTLDPlusOne returns the effective top level domain plus one more label. 20 | func GetTLDPlusOne(k string) string { 21 | h := strings.Split(k, ":") 22 | v, _ := publicsuffix.EffectiveTLDPlusOne(h[0]) 23 | 24 | return v 25 | } 26 | --------------------------------------------------------------------------------