├── .gitignore ├── LICENSE.txt ├── README.md ├── algoexpert.io ├── python │ ├── Airport_Connections.py │ ├── Apartment_Hunting.py │ ├── BST_Construction_Iterative.py │ ├── BST_Construction_Recursive.py │ ├── BST_Traversal.py │ ├── Balanced_Bracket.py │ ├── Binary_Search.py │ ├── Boggle_Board.py │ ├── Branch_Sums.py │ ├── Breadth_First_Search.py │ ├── Bubble_Sort.py │ ├── Caesar_Cipher_Encryptor.py │ ├── Calendar_Matching.py │ ├── Continuous_Median.py │ ├── Depth_First_Search.py │ ├── Disk_Stacking.py │ ├── Find_Closest_Value_in_BST.py │ ├── Find_Loop.py │ ├── Find_Three_Largest_Number.py │ ├── Flatten_Binary_Tree.py │ ├── Four_Number_Sum.py │ ├── Group_Anagrams.py │ ├── Heap_Sort.py │ ├── Insertion_Sort.py │ ├── Interweaving_Strings.py │ ├── Invert_Binary_Tree.py │ ├── Iterative_In-order_Traversal.py │ ├── KMP_Algorithm.py │ ├── Kadane's_Algorithm.py │ ├── Knapsack_Problem.py │ ├── LRU_Cache.py │ ├── Largest_Range.py │ ├── Levenshtein_Distance.py │ ├── Linked_List_Construction.py │ ├── Longest_Common_Subsequence.py │ ├── Longest_Increasing_Subsequence.py │ ├── Longest_Palindromic_Substring.py │ ├── Longest_Peak.py │ ├── Longest_String_Chain.py │ ├── Longest_Substring_Without_Duplication.py │ ├── Lowest_Common_Manager.py │ ├── Max_Path_Sum_In_Binary_Tree.py │ ├── Max_Profit_With_K_Transactions.py │ ├── Max_Sum_Increasing_Subsequence.py │ ├── Maximum_Subset_Sum_With_No_Adjacent_Element.py │ ├── Merge_Linked_List.py │ ├── Merge_Sort.py │ ├── Min_Heap_Construction.py │ ├── Min_Max_Stack_Construction.py │ ├── Min_Number_Of_Jumps.py │ ├── Min_Rewards.py │ ├── Minimum_Number_Of_Coins_For_Change.py │ ├── Monotonic_Array.py │ ├── Move_Element_To_End.py │ ├── Multi_String_Search.py │ ├── Nth_Fibonacci.py │ ├── Number_Of_Binary_Tree_Topologies.py │ ├── Number_Of_Possible_Binary_Tree_Topologies.py │ ├── Number_Of_Ways_To_Make_Changes.py │ ├── Numbers_In_Pi.py │ ├── Palindrom_Check.py │ ├── Palindrome_Partitioning_Min_Cuts.py │ ├── Pattern_Matcher.py │ ├── Permutations.py │ ├── Powerset.py │ ├── Product_Sum.py │ ├── Quick_Select.py │ ├── Quick_Sort.py │ ├── Rectangle_Mania.py │ ├── Remove_Kth_Node_From_End.py │ ├── Reverse_Linked_List.py │ ├── Right_Sibling_Tree.py │ ├── River_Sizes.py │ ├── Same_BSTs.py │ ├── Search_For_Range.py │ ├── Search_In_Sorted_Matrix.py │ ├── Selection_Sort.py │ ├── Shifted_Binary_Search.py │ ├── Single_Cycle_Check.py │ ├── Smallest_Difference.py │ ├── Smallest_Substring_Containing.py │ ├── Spiral_Traverse.py │ ├── Subarray_Sort.py │ ├── Suffix_Trie_Construction.py │ ├── Three_Number_Sum.py │ ├── Topological_Sort.py │ ├── Two_Number_Sum.py │ ├── Underscorify_Substring.py │ ├── Validate_BST.py │ ├── Water_Area.py │ ├── Youngest_Common_Ancestor.py │ └── Zigzag_Traverse.py └── swift │ └── Two_Number_Sum.swift ├── algoexpert.png ├── leetcode.com ├── objective-c │ └── DS_ALGO_PRAC │ │ ├── DS_ALGO_PRAC.xcodeproj │ │ ├── project.pbxproj │ │ └── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── DS_ALGO_PRAC │ │ ├── Problems │ │ └── 226_Invert_Binary_Tree.m │ │ └── main.m ├── python │ ├── 1007_Minimum_Domino_Rotations_For_Equal_Row.py │ ├── 1008_Construct_Binary_Search_Tree_from_Preorder_Traversal.py │ ├── 100_Same_Tree.py │ ├── 1011_Capacity_To_Ship_Packages_Within_D_Days.py │ ├── 101_Symmetric_Tree.py │ ├── 1027_Longest_Arithmetic_Sequence.py │ ├── 102_Binary_Tree_Level_Order_Traversal.py │ ├── 103_Binary_Tree_Zigzag_Level_Order_Traversal.py │ ├── 1042_Flower_Planting_With_No_Adjacent.py │ ├── 1048_Longest_String_Chain.py │ ├── 104_Maximum_Depth_of_Binary_Tree.py │ ├── 1051_Height_Checker.py │ ├── 1055_Shortest_Way_to_Form_String.py │ ├── 1057_Campus_Bikes.py │ ├── 105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py │ ├── 1060_Missing_Element_in_Sorted_Array.py │ ├── 1066_Campus_Bikes_II.py │ ├── 106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py │ ├── 1074_Number_of_Submatrices_That_Sum_to_Target.py │ ├── 1079_Letter_Tile_Possibilities.py │ ├── 107_Binary_Tree_Level_Order_Traversal_II.py │ ├── 1087_Brace_Expansion.py │ ├── 1088_Confusing_Number_II.py │ ├── 1089_Duplicate_Zeros.py │ ├── 108_Convert_Sorted_Array_to_Binary_Search_Tree.py │ ├── 1092_Shortest_Common_Supersequence.py │ ├── 1099_Two_Sum_Less_Than_K.py │ ├── 109_Convert_Sorted_List_to_Binary_Search_Tree.py │ ├── 1102_Path_With_Maximum_Minimum_Value.py │ ├── 110_Balanced_Binary_Tree.py │ ├── 1110_Delete_Nodes_And_Return_Forest.py │ ├── 1113_Parallel_Courses.py │ ├── 1118_-Number_of_Days_in_a_Month.py │ ├── 1119_Remove_Vowels_from_a_String.py │ ├── 111_Minimum_Depth_of_Binary_Tree.py │ ├── 112_Path_Sum.py │ ├── 113_Path_Sum_II.py │ ├── 1143_Longest_Common_Subsequence.py │ ├── 1145_Binary_Tree_Coloring_Game.py │ ├── 1146_Snapshot_Array.py │ ├── 114_Flatten_Binary_Tree_to_Linked_List.py │ ├── 1152_Analyze_User_Website_Visit_Pattern.py │ ├── 1153_String_Transforms_Into_Another_String.py │ ├── 115_Distinct_Subsequences.py │ ├── 1167_Minimum_Cost_to_Connect_Sticks.py │ ├── 1168_Optimize_Water_Distribution_in_a_Village.py │ ├── 116_Populating_Next_Right_Pointers_in_Each_Node.py │ ├── 1170_Compare_Strings_by_Frequency_of_the_Smallest_Character.py │ ├── 117_Populating_Next_Right_Pointers_in_Each_Node_II.py │ ├── 118_Pascal's_Triangle.py │ ├── 1192_Critical_Connections_in_a_Network.py │ ├── 1197_Minimum_Knight_Moves.py │ ├── 119_Pascal's_Triangle_II.py │ ├── 11_Container_With_Most_Water.py │ ├── 1203_Sort_Items_by_Groups_Respecting_Dependencies.py │ ├── 1219_Path_with_Maximum_Gold.py │ ├── 121_Best_Time_to_Buy_and_Sell_Stock.py │ ├── 1229_Meeting_Scheduler.py │ ├── 122_Best_Time_to_Buy_and_Sell_Stock_II.py │ ├── 1231_Divide_Chocolate.py │ ├── 1232_Check_If_It_Is_a_Straight_Line.py │ ├── 123_Best_Time_to_Buy_and_Sell_Stock_III.py │ ├── 124_Binary_Tree_Maximum_Path_Sum.py │ ├── 125_Valid_Palindrome.py │ ├── 1268_Search_Suggestions_System.py │ ├── 126_Word_Ladder_II.py │ ├── 1272_Remove_Interval.py │ ├── 127_Word_Ladder.py │ ├── 1288_Remove_Covered_Intervals.py │ ├── 1292_Maximum_Side_Length_of_a_Square_with_Sum_Less_than_or_Equal_to_Threshold.py │ ├── 130_Surrounded_Regions.py │ ├── 1312_Minimum_Insertion_Steps_to_Make_a_String_Palindrome.py │ ├── 1315_Sum_of_Nodes_with_Even_Valued_Grandparent.py │ ├── 1320_Minimum_Distance_to_Type_a_Word_Using_Two_Fingers.py │ ├── 132_Palindrome_Partitioning_II.py │ ├── 133_Clone_Graph.py │ ├── 134_Gas_Station.py │ ├── 1358_Number_of_Substrings_Containing_All_Three_Characters.py │ ├── 136_Single_Number.py │ ├── 137_Single_Number_II.py │ ├── 138_Copy_List_with_Random_Pointer.py │ ├── 139_Word_Break.py │ ├── 13_Roman_to_Integer.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 │ ├── 1477_Find_Two_Non_overlapping_Sub_arrays_Each_With_Target_Sum.py │ ├── 148_Sort_List.py │ ├── 150_Evaluate_Reverse_Polish_Notation.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 │ ├── 159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py │ ├── 15_3Sum.py │ ├── 160_Intersection_of_Tw_Linked_Lists.py │ ├── 161_One_Edit_Distance.py │ ├── 162_Find_Peak_Element.py │ ├── 163_Missing_Ranges.py │ ├── 166_Fraction_to_Recurring_Decimal.py │ ├── 167_Two_Sum_II_-_Input_array_is_sorted.py │ ├── 169_Majority_Element.py │ ├── 16_3Sum_Closest.py │ ├── 173_Binary_Search_Tree_Iterator.py │ ├── 17_Letter_Combinations_of_a_Phone_Number.py │ ├── 187_Repeated_DNA_Sequences.py │ ├── 188_Best_Time_to_Buy_and_Sell_Stock_IV.py │ ├── 18_4Sum.py │ ├── 191_Number_of_1_Bits.py │ ├── 198_House_Robber.py │ ├── 199_Binary_Tree_Right_Side_View.py │ ├── 19_Remove_Nth_Node_From_End_of_List.py │ ├── 1_Two_Sum.py │ ├── 200_Number_of_Islands.py │ ├── 202_Happy_Number.py │ ├── 206_Reverse_Linked_List.py │ ├── 207_Course_Schedule.py │ ├── 208_Implement_Trie_(Prefix_Tree).py │ ├── 209_Minimum_Size_Subarray_Sum.py │ ├── 20_Valid_Parentheses.py │ ├── 210_Course_Schedule_II.py │ ├── 211_Add_and_Search_Word_Data_structure_design.py │ ├── 212_Word_Search_II.py │ ├── 213_House_Robber_II.py │ ├── 215_Kth_Largest_Element_in_an_Array.py │ ├── 21_Merge_Two_Sorted_Lists.py │ ├── 221_Maximal_Square.py │ ├── 222_Count_Complete_Tree_Nodes.py │ ├── 226_Invert_Binary_Tree.py │ ├── 22_Generate_Parentheses.py │ ├── 231_Power_of_Two.py │ ├── 234_Palindrome_Linked_List.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 │ ├── 239_Sliding_Window_Maximum.py │ ├── 23_Merge_k_Sorted_Lists.py │ ├── 240_Search_a_2D_Matrix_II.py │ ├── 242_Valid_Anagram.py │ ├── 246_Strobogrammatic_Number.py │ ├── 24_Swap_Nodes_in_Pairs.py │ ├── 252_Meeting_Rooms.py │ ├── 253_Meeting_Rooms_II.py │ ├── 257_Binary_Tree_Paths.py │ ├── 259_3Sum_Smaller.py │ ├── 25_Reverse_Nodes_in_k-Group.py │ ├── 260_Single_Number_III.py │ ├── 261_Graph_Valid_Tree.py │ ├── 268_Missing_Number.py │ ├── 269_Alien_Dictionary.py │ ├── 26_Remove_Duplicates_from_Sorted_Array.py │ ├── 270_Closest_Binary_Search_Tree_Value.py │ ├── 271_Encode_and_Decode_Strings.py │ ├── 273_Integer_to_English_Words.py │ ├── 278_First_Bad_Version.py │ ├── 279_Perfect_Squares.py │ ├── 280_Wiggle_Sort.py │ ├── 281_Zigzag_Iterator.py │ ├── 282_Expression_Add_Operators.py │ ├── 283_Move_Zeroes.py │ ├── 284_Peeking_Iterator.py │ ├── 285_Inorder_Successor_in_BST.py │ ├── 286_Walls_and_Gates.py │ ├── 287_Find_the_Duplicate_Number.py │ ├── 289_Game_of_Life.py │ ├── 295_Find_Median_from_Data_Stream.py │ ├── 297_Serialize_and_Deserialize_Binary_Tree.py │ ├── 298_Binary_Tree_Longest_Consecutive_Sequence.py │ ├── 299_Bulls_and_Cows.py │ ├── 2_Add_Two_Numbers.py │ ├── 300_Longest_Increasing_Subsequence.py │ ├── 301_Remove_Invalid_Parentheses.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 │ ├── 309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown.py │ ├── 310_Minimum_Height_Trees.py │ ├── 314_Binary_Tree_Vertical_Order_Traversal.py │ ├── 315_Count_of_Smaller_Numbers_After_Self.py │ ├── 319_Bulb_Switcher.py │ ├── 31_Next_Permutation.py │ ├── 322_Coin_Change.py │ ├── 325_Maximum_Size_Subarray_Sum_Equals_k.py │ ├── 327_Count_of_Rang_Sum.py │ ├── 328_Odd_Even_Linked_List.py │ ├── 329_Longest_Increasing_Path_in_a_Matrix.py │ ├── 332_Reconstruct_Itinerary.py │ ├── 334_Increasing_Triplet_Subsequence.py │ ├── 337_House_Robber_III.py │ ├── 33_Search_in_Rotated_Sorted_Array.py │ ├── 340_Longest_Substring_with_At_Most_K_Distinct_Characters.py │ ├── 341_Flatten_Nested_List_Iterator.py │ ├── 343_Integer_Break.py │ ├── 344_Reverse_String.py │ ├── 346_Moving_Average_from_Data_Stream.py │ ├── 347_Top_K_Frequent_Elements.py │ ├── 348_Design_Tic-Tac-Toe.py │ ├── 349_Intersection_of_Two_Arrays.py │ ├── 34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py │ ├── 350_Intersection_of_Two_Arrays_II.py │ ├── 358_Rearrange_String_k_Distance_Apart.py │ ├── 359_Logger_Rate_Limiter.py │ ├── 362_Design_Hit_Counter.py │ ├── 363_Max_Sum_of_Rectangle_No_Larger_Than_K.py │ ├── 368_Largest_Divisible_Subset.py │ ├── 371_Sum_of_Two_Integers.py │ ├── 373_Find_K_Pairs_with_Smallest_Sums.py │ ├── 374_Guess_Number_Higher_or_Lower.py │ ├── 375_Guess_Number_Higher_or_Lower_II.py │ ├── 378_Kth_Smallest_Element_in_a_Sorted_Matrix.py │ ├── 379_Design_Phone_Directory.py │ ├── 37_Sudoku_Solver.py │ ├── 380_Insert_Delete_GetRandom_O(1).py │ ├── 388_Longest_Absolute_File_Path.py │ ├── 389_Find_the_Difference.py │ ├── 392_Is_Subsequence.py │ ├── 394_Decode_String.py │ ├── 398_Random_Pick_Index.py │ ├── 399_Evaluate_Division.py │ ├── 39_Combination_Sum.py │ ├── 3_Longest_Substring_Without_Repeating_Characters.py │ ├── 406_Queue_Reconstruction_by_Height.py │ ├── 40_Combination_Sum_II.py │ ├── 410_Split_Array_Largest_Sum.py │ ├── 414_Third_Maximum_Number.py │ ├── 416_Partition_Equal_Subset_Sum.py │ ├── 41_First_Missing_Positive.py │ ├── 424_Longest_Repeating_Character_Replacement.py │ ├── 428_Serialize_and_Deserialize_N-ary_Tree.py │ ├── 429_N-ary_Tree_Level_Order_Traversal.py │ ├── 42_Trapping_Rain_Water.py │ ├── 430_Flatten_a_Multilevel_Doubly_Linked_List.py │ ├── 431_Encode_N-ary_Tree_to_Binary_Tree.py │ ├── 435_Non-overlapping_Intervals.py │ ├── 437_Path_Sum_III.py │ ├── 438_Find_All_Anagrams_in_a_String.py │ ├── 442_Find_All_Duplicates_in_an_Array.py │ ├── 444_Sequence_Reconstruction.py │ ├── 448_Find_All_Numbers_Disappeared_in_an_Array.py │ ├── 449_Serialize_and_Deserialize_BST.py │ ├── 450_Delete_Node_in_a_BST.py │ ├── 451_Sort_Characters_By_Frequency.py │ ├── 457_Circular_Array_Loop.py │ ├── 459_Repeated_Substring_Pattern.py │ ├── 45_Jump_Game_II.py │ ├── 460_LFU_Cache.py │ ├── 461_Hamming_Distance.py │ ├── 463_Island_Perimeter.py │ ├── 465_Optimal_Account_Balancing.py │ ├── 46_Permutations.py │ ├── 472_Concatenated_Words.py │ ├── 476_Number_Complement.py │ ├── 47_Permutations_II.py │ ├── 480_Sliding_Window_Median.py │ ├── 482_License_Key_Formatting.py │ ├── 489_Robot_Room_Cleaner.py │ ├── 48_Rotate_Image.py │ ├── 490_The_Maze.py │ ├── 494_Target_Sum.py │ ├── 49_Group_Anagrams.py │ ├── 4_Median_of_Two_Sorted_Arrays.py │ ├── 509_Fibonacci_Number.py │ ├── 50_Pow(x,_n).py │ ├── 516_Longest_Palindromic_Subsequence.py │ ├── 518_Coin_Change_2.py │ ├── 525_Contiguous_Array.py │ ├── 528_Random_Pick_with_Weight.py │ ├── 52_N-Queens_II.py │ ├── 53_Maximum_Subarray.py │ ├── 540_Single_Element_in_a_Sorted_Array.py │ ├── 543_Diameter_of_Binary_Tree.py │ ├── 54_Spiral_Matrix.py │ ├── 551_Student_Attendance_Record_I.py │ ├── 552_Student_Attendance_Record_II.py │ ├── 559_Maximum_Depth_of_N-ary_Tree.py │ ├── 55_Jump_Game.py │ ├── 560_Subarray_Sum_Equals_K.py │ ├── 562_Longest_Line_of_Consecutive_One_in_Matrix.py │ ├── 567_Permutation_in_String.py │ ├── 56_Merge_Intervals.py │ ├── 572_Subtree_of_Another_Tree.py │ ├── 57_Insert_Interval.py │ ├── 581_Shortest_Unsorted_Continuous_Subarray.py │ ├── 583_Delete_Operation_for_Two_Strings.py │ ├── 588_Design_In_Memory_File_System.py │ ├── 589_N-ary_Tree_Preorder_Traversal.py │ ├── 590_N-ary_Tree_Postorder_Traversal.py │ ├── 593_Valid_Square.py │ ├── 59_Spiral_Matrix_II.py │ ├── 5_Longest_Palindromic_Substring.py │ ├── 60_Permutation_Sequence.py │ ├── 616_Add_Bold_Tag_in_String.py │ ├── 61_Rotate_List.py │ ├── 621_Task_Scheduler.py │ ├── 62_Unique_Paths.py │ ├── 632_Smallest_Range_Covering_Elements_from_K_Lists.py │ ├── 642_Design_Search_Autocomplete_System.py │ ├── 647_Palindromic_Substrings.py │ ├── 64_Minimum_Path_Sum.py │ ├── 653_Two_Sum_IV_Input_is_a_BST.py │ ├── 658_Find_K_Closest_Elements.py │ ├── 659_Split_Array_into_Consecutive_Subsequences.py │ ├── 66_Plus_One.py │ ├── 671_Second_Minimum_Node_In_a_Binary_Tree.py │ ├── 678_Valid_Parenthesis_String.py │ ├── 679_24_Game.py │ ├── 680_Valid_Palindrome_II.py │ ├── 681_Next_Closest_Time.py │ ├── 683_K_Empty_Slots.py │ ├── 688_Knight_Probability_in_Chessboard.py │ ├── 68_Text_Justification.py │ ├── 692_Top_K_Frequent_Words.py │ ├── 694_Number_of_Distinct_Islands.py │ ├── 695_Max_Area_of_Island.py │ ├── 698_Partition_to_K_Equal_Sum_Subsets.py │ ├── 69_Sqrt(x).py │ ├── 700_Search_in_a_Binary_Search_Tree.py │ ├── 701_Insert_into_a_Binary_Search_Tree.py │ ├── 702_Search_in_a_Sorted_Array_of_Unknown_Size.py │ ├── 703_Kth_Largest_Element_in_a_Stream.py │ ├── 704_Binary_Search.py │ ├── 707_Design_Linked_List.py │ ├── 70_Climbing_Stairs.py │ ├── 713_Subarray_Product_Less_Than_K.py │ ├── 714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py │ ├── 718_Maximum_Length_of_Repeated_Subarray.py │ ├── 71_Simplify_Path.py │ ├── 724_Find_Pivot_Index.py │ ├── 727_Minimum_Window_Subsequence.py │ ├── 729_My_Calendar_I.py │ ├── 72_Edit_Distance.py │ ├── 731_My_Calendar_II.py │ ├── 733_Flood_Fill.py │ ├── 739_Daily_Temperatures.py │ ├── 743_Network_Delay_Time.py │ ├── 747_Largest_Number_At_Least_Twice_of_Others.py │ ├── 74_Search_a_2D_Matrix.py │ ├── 752_Open_the_Lock.py │ ├── 759_Employee_Free_Time.py │ ├── 75_Sort_Colors.py │ ├── 763_Partition_Labels.py │ ├── 767_Reorganize_String.py │ ├── 76_Minimum_Window_Substring.py │ ├── 771_Jewels_and_Stones.py │ ├── 774_Minimize_Max_Distance_to_Gas_Station.py │ ├── 77_Combinations.py │ ├── 784_Letter_Case_Permutation.py │ ├── 785_Is_Graph_Bipartite.py │ ├── 788_Rotated_Digits.py │ ├── 78_Subsets.py │ ├── 792_Number_of_Matching_Subsequences.py │ ├── 79_Word_Search.py │ ├── 7_Reverse_Integer.py │ ├── 801_Minimum_Swaps_To_Make_Sequences_Increasing.py │ ├── 809_Expressive_Words.py │ ├── 811_Subdomain_Visit_Count.py │ ├── 817_Linked_List_Components.py │ ├── 819_Most_Common_Word.py │ ├── 81_Search_in_Rotated_Sorted_Array_II.py │ ├── 832_Flipping_an_Image.py │ ├── 833_Find_And_Replace_in_String.py │ ├── 835_Image_Overlap.py │ ├── 841_Keys_and_Rooms.py │ ├── 843_Guess_the_Word.py │ ├── 844_Backspace_String_Compare.py │ ├── 845_Longest_Mountain_in_Array.py │ ├── 846_Hand_of_Straights.py │ ├── 849_Maximize_Distance_to_Closest_Person.py │ ├── 84_Largest_Rectangle_in_Histogram.py │ ├── 850_Rectangle_Area_II.py │ ├── 852_Peak_Index_in_a_Mountain_Array.py │ ├── 85_Maximal_Rectangle.py │ ├── 862_Shortest_Subarray_with_Sum_at_Least_K.py │ ├── 863_All_Nodes_Distance_K_in_Binary_Tree.py │ ├── 865_Smallest_Subtree_with_all_the_Deepest_Nodes.py │ ├── 875_Koko_Eatin_Bananas.py │ ├── 876_Middle_of_the_Linked_List.py │ ├── 889_Construct_Binary_Tree_from_Preorder_and_Postorder_Traversal.py │ ├── 88_Merge_Sorted_Array.py │ ├── 895_Maximum_Frequency_Stack.py │ ├── 904_Fruit_Into_Baskets.py │ ├── 909_Snakes_and_Ladders.py │ ├── 90_Subsets_II.py │ ├── 912_Sort_an_Array_(Merge__Sort).py │ ├── 91_Decode_Ways.py │ ├── 925_Long_Pressed_Name.py │ ├── 929_Unique_Email_Addresses.py │ ├── 92_Reverse_Linked_List_II.py │ ├── 937_Reorder_Log_Files.py │ ├── 939_Minimum_Area_Rectangle.py │ ├── 941_Valid_Mountain_Array.py │ ├── 946_Validate_Stack_Sequences.py │ ├── 947_Most_Stones_Removed_with_Same_Row_or_Column.py │ ├── 949_Largest_Time_for_Given_Digits.py │ ├── 94_Binary_Tree_Inorder_Traversal.py │ ├── 951_Flip_Equivalent_Binary_Trees.py │ ├── 953_Verifying_an_Alien_Dictionary.py │ ├── 957_Prison_Cells_After_N_Days.py │ ├── 958_Check_Completeness_of_a_Binary_Tree.py │ ├── 95_Unique_Binary_Search_Trees_II.py │ ├── 96_Unique_Binary_Search_Trees.py │ ├── 973_K_Closest_Points_to_Origin.py │ ├── 975_Odd_Even_Jump.py │ ├── 977_Squares_of_a_Sorted_Array.py │ ├── 979_Distribute_Coins_in_Binary_Tree.py │ ├── 97_Interleaving_String.py │ ├── 981_Time_Based_Key-Value_Store.py │ ├── 986_Interval_List_Intersections.py │ ├── 987_Vertical_Order_Traversal_of_a_Binary_Tree.py │ ├── 98_Validate_Binary_Search_Tree.py │ ├── 993_Cousins_in_Binary_Tree.py │ ├── 994_Rotting_Oranges.py │ ├── 997_Find_the_Town_Judge.py │ ├── 99_Recover_Binary_Search_Tree.py │ └── 9_Palindrome_Number.py └── swift │ ├── DS_ALGO_PRAC.playground │ ├── Contents.swift │ ├── Sources │ │ ├── DS │ │ │ └── Heap.swift │ │ └── swift │ │ │ ├── 1004_Max_Consecutive_Ones_III.swift │ │ │ ├── 1026_Maximum_Difference_Between_Node_and_Ancestor.swift │ │ │ ├── 1031_Maximum_Sum_of_Two_Non_Overlapping_Subarrays.swift │ │ │ ├── 106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.swift │ │ │ ├── 1091_Shortest_Path_in_Binary_Matrix.swift │ │ │ ├── 1123_Lowest_Common_Ancestor_of_Deepest_Leaves.swift │ │ │ ├── 1138_Alphabet_Board_Path.swift │ │ │ ├── 1166_Design_File_System.swift │ │ │ ├── 1209_Remove_All_Adjacent_Duplicates_in_String_II.swift │ │ │ ├── 1216_Valid_Palindrome_III.swift │ │ │ ├── 1233_Remove_Sub_Folders_from_the_Filesystem.swift │ │ │ ├── 1245_Tree_Diameter.swift │ │ │ ├── 1249_Minimum_Remove_to_Make_Valid_Parentheses.swift │ │ │ ├── 124_Binary_Tree_Maximum_Path_Sum.swift │ │ │ ├── 1254_Number_of_Closed_Islands.swift │ │ │ ├── 125_Valid_Palindrome.swift │ │ │ ├── 1265_Print_Immutable_Linked_List_in_Reverse.swift │ │ │ ├── 1269_Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.swift │ │ │ ├── 1275_Find_Winner_on_a_Tic_Tac_Toe_Game.swift │ │ │ ├── 1276_Number_of_Burgers_with_No_Waste_of_Ingredients.swift │ │ │ ├── 1277_Count_Square_Submatrices_with_All_Ones.swift │ │ │ ├── 128_Longest_Consecutive_Sequence.swift │ │ │ ├── 1293_Shortest_Path_in_a_Grid_with_Obstacles_Elimination.swift │ │ │ ├── 1296_Divide_Array_in_Sets_of_K_Consecutive_Numbers.swift │ │ │ ├── 129_Sum_Root_to_Leaf_Numbers.swift │ │ │ ├── 1305_All_Elements_in_Two_Binary_Search_Trees.swift │ │ │ ├── 1333_Filter_Restaurants_by_Vegan-Friendly_Price_and_Distance.swift │ │ │ ├── 133_Clone_Graph.swift │ │ │ ├── 1344_Angle_Between_Hands_of_a_Clock.swift │ │ │ ├── 134_Gas_Station.swift │ │ │ ├── 1376_Time_Needed_to_Inform_All_Employees.swift │ │ │ ├── 1382_Balance_a_Binary_Search_Tree.swift │ │ │ ├── 138_Copy_List_with_Random_Pointer.swift │ │ │ ├── 1423_Maximum_Points_You_Can_Obtain_from_Cards.swift │ │ │ ├── 1424_Diagonal_Traverse_II.swift │ │ │ ├── 1428_Leftmost_Column_with_at_Least_a_One.swift │ │ │ ├── 1438_Longest_Continuous_Subarray_With_Absolute_Diff_Less_Than_or_Equal_to_Limit.swift │ │ │ ├── 146_LRU_Cache.swift │ │ │ ├── 1487_Making_File_Names_Unique.swift │ │ │ ├── 150_Evaluate_Reverse_Polish_Notation.swift │ │ │ ├── 1522_Diameter_of_N-Ary_Tree.swift │ │ │ ├── 1525_Number_of_Good_Ways_to_Split_a_String.swift │ │ │ ├── 152_Maximum_Product_Subarray.swift │ │ │ ├── 153_Find_Minimum_in_Rotated_Sorted_Array.swift │ │ │ ├── 1541_Minimum_Insertions_to_Balance_a_Parentheses_String.swift │ │ │ ├── 154_Find_Minimum_in_Rotated_Sorted_Array_II.swift │ │ │ ├── 1559_Detect_Cycles_in_2D_Grid.swift │ │ │ ├── 1570_Dot_Product_of_Two_Sparse_Vectors.swift │ │ │ ├── 157_Read_N_Characte_Given_Read4.swift │ │ │ ├── 158_Read_N_Characters_Given_Read4_II_Call_multiple_times.swift │ │ │ ├── 1629_Slowest_Key.swift │ │ │ ├── 1631_Path_With_Minimum_Effort.swift │ │ │ ├── 1642_Furthest_Building_You_Can_Reach.swift │ │ │ ├── 1650_Lowest_Common_Ancestor_of_a_Binary_Tree_III.swift │ │ │ ├── 166_Fraction_to_Recurring_Decimal.swift │ │ │ ├── 173_Binary_Search_Tree_Iterator.swift │ │ │ ├── 1762_Buildings_With_an_Ocean_View.swift │ │ │ ├── 1834_Single_Threaded_CPU.swift │ │ │ ├── 1870_Minimum_Speed_to_Arrive_on_Time.swift │ │ │ ├── 1877_Minimize_Maximum_Pair_Sum_in_Array.swift │ │ │ ├── 1891_Cutting_Ribbons.swift │ │ │ ├── 189_Rotate_Array.swift │ │ │ ├── 1937_Maximum_Number_of_Points_with_Cost.swift │ │ │ ├── 1944_Number_of_Visible_People_in_a_Queue.swift │ │ │ ├── 199_Binary_Tree_Right_Side_View.swift │ │ │ ├── 1_Two_Sum.swift │ │ │ ├── 2007_Find_Original_Array_From_Doubled_Array.swift │ │ │ ├── 203_Remove_Linked_List_Elements.swift │ │ │ ├── 212_Word_Search_II.swift │ │ │ ├── 215_Kth_Largest_Element_in_an_Array.swift │ │ │ ├── 218_Longest_Arithmetic_Subsequence_of_Given_Difference.swift │ │ │ ├── 222_Count_Complete_Tree_Nodes.swift │ │ │ ├── 224_Basic_Calculator.swift │ │ │ ├── 226_Invert_Binary_Tree.swift │ │ │ ├── 227_Basic_Calculator_II.swift │ │ │ ├── 230_Kth_Smallest_Element_in_a_BST.swift │ │ │ ├── 236_Lowest_Common_Ancestor_of_a_Binary_Tree.swift │ │ │ ├── 238_Product_of_Array_Except_Self.swift │ │ │ ├── 242_Valid_Anagram.swift │ │ │ ├── 249_Group_Shifted_Strings.swift │ │ │ ├── 253_Meeting_Rooms_II.swift │ │ │ ├── 269_Alien_Dictionary.swift │ │ │ ├── 270_Closest_Binary_Search_Tree_Value.swift │ │ │ ├── 286_Walls_and_Gates.swift │ │ │ ├── 289_Game_of_Life.swift │ │ │ ├── 2_Add_Two_Numbers.swift │ │ │ ├── 311_Sparse_Matrix_Multiplication.swift │ │ │ ├── 314_Binary_Tree_Vertical_Order_Traversa.swift │ │ │ ├── 317_Shortest_Distance_from_All_Buildings.swift │ │ │ ├── 31_Next_Permutation.swift │ │ │ ├── 338_Counting_Bits.swift │ │ │ ├── 339_Nested_List_Weight_Sum.swift │ │ │ ├── 33_Search_in_Rotated_Sorted_Array.swift │ │ │ ├── 340_Longest_Substring_with_At_Most_K_Distinct_Characters.swift │ │ │ ├── 341_Flatten_Nested_List_Iterator.swift │ │ │ ├── 346_Moving_Average_from_Data_Stream.swift │ │ │ ├── 34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.swift │ │ │ ├── 355_Design_Twitter.swift │ │ │ ├── 362_Design_Hit_Counter.swift │ │ │ ├── 364_Nested_List_Weight_Sum_II.swift │ │ │ ├── 366_Find_Leaves_of_Binary_Tree.swift │ │ │ ├── 380_Insert_Delete_GetRandom_O(1).swift │ │ │ ├── 3_Longest Substring_Without_Repeating Characters.swift │ │ │ ├── 408_Valid_Word_Abbreviation.swift │ │ │ ├── 412_Fizz_Buzz.swift │ │ │ ├── 415_Add_Strings.swift │ │ │ ├── 418_Sentence_Screen_Fitting .swift │ │ │ ├── 419_Battleships_in_a_Board.swift │ │ │ ├── 426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.swift │ │ │ ├── 428_Serialize_and_Deserialize_N-ary_Tree.swift │ │ │ ├── 432_All_O_one_Data_Structure.swift │ │ │ ├── 438_Find_All_Anagrams_in_a_String.swift │ │ │ ├── 441_Arranging_Coins.swift │ │ │ ├── 443_String_Compression.swift │ │ │ ├── 461_Hamming_Distance.swift │ │ │ ├── 476_Number_Complement.swift │ │ │ ├── 498_Diagonal_Traverse.swift │ │ │ ├── 503_Next_Greater_Element_II.swift │ │ │ ├── 50_Pow(x, n).swift │ │ │ ├── 515_Find_Largest_Value_in_Each_Tree_Row.swift │ │ │ ├── 523_Continuous_Subarray_Sum.swift │ │ │ ├── 528_Random_Pick_with_Weight.swift │ │ │ ├── 532_K-diff_Pairs_in_an_Array.swift │ │ │ ├── 536_Construct_Binary_Tree_from_String.swift │ │ │ ├── 542_01_Matrix.swift │ │ │ ├── 543_Diameter_of_Binary_Tree.swift │ │ │ ├── 547_Friend_Circles.swift │ │ │ ├── 54_Spiral_Matrix.swift │ │ │ ├── 556_Next_Greater_Element_III.swift │ │ │ ├── 560_Subarray_Sum_Equals_K.swift │ │ │ ├── 562_Longest_Line_of_Consecutive_One_in_Matrix.swift │ │ │ ├── 56_Merge_Intervals.swift │ │ │ ├── 60_Permutation_Sequence.swift │ │ │ ├── 621_Task_Scheduler.swift │ │ │ ├── 62_Unique_Paths.swift │ │ │ ├── 636_Exclusive_Time_of_Functions.swift │ │ │ ├── 63_Unique_Paths_II.swift │ │ │ ├── 64_Minimum_Path_Sum.swift │ │ │ ├── 652_Find_Duplicate_Subtrees.swift │ │ │ ├── 65_Valid_Number.swift │ │ │ ├── 670_Maximum_Swap.swift │ │ │ ├── 67_Add_Binary.swift │ │ │ ├── 689_Maximum_Sum_of_3_Non_Overlapping_Subarrays.swift │ │ │ ├── 690_Employee_Importance.swift │ │ │ ├── 708_Insert_into_a_Sorted_Circular_Linked_List.swift │ │ │ ├── 71_Simplify_Path.swift │ │ │ ├── 721_Accounts_Merge.swift │ │ │ ├── 722_Remove_Comments.swift │ │ │ ├── 729_My_Calendar_I.swift │ │ │ ├── 735_Asteroid_Collision.swift │ │ │ ├── 742_Closest_Leaf_in_a_Binary_Tree.swift │ │ │ ├── 763_Partition_Labels.swift │ │ │ ├── 766_Toeplitz_Matrix.swift │ │ │ ├── 777_Swap_Adjacent_in_LR_String.swift │ │ │ ├── 785_Is_Graph_Bipartite.swift │ │ │ ├── 791_Custom_Sort_String.swift │ │ │ ├── 825_Friends_Of_Appropriate_Ages.swift │ │ │ ├── 827_Making_A_Large_Island.swift │ │ │ ├── 852_Peak_Index_in_a_Mountain_Array.swift │ │ │ ├── 853_Car_Fleet.swift │ │ │ ├── 855_Exam_Room.swift │ │ │ ├── 896_Monotonic_Array.swift │ │ │ ├── 900_RLE_Iterator.swift │ │ │ ├── 914_X_of_a_Kind_in_a_Deck_of_Cards.swift │ │ │ ├── 91_Decode_Ways.swift │ │ │ ├── 921_Minimum_Add_to_Make_Parentheses_Valid.swift │ │ │ ├── 934_Shortest_Bridge.swift │ │ │ ├── 938_Range_Sum_of_BST.swift │ │ │ ├── 93_Restore_IP_Addresses.swift │ │ │ ├── 949_Largest_Time_for_Given_Digits.swift │ │ │ ├── 94_Binary_Tree_Inorder_Traversal.swift │ │ │ ├── 953_Verifying_an_Alien_Dictionary.swift │ │ │ ├── 954_Array_of_Doubled_Pairs.swift │ │ │ ├── 975_Odd_Even_Jump.swift │ │ │ ├── 983_Minimum_Cost_For_Tickets.swift │ │ │ ├── 984_String_Without_AAA_or_BBB.swift │ │ │ ├── 986_Interval_List_Intersections.swift │ │ │ ├── 987_Vertical_Order_Traversal_of_a_Binary_Tree.swift │ │ │ ├── 990_Satisfiability_of_Equality_Equations.swift │ │ │ └── 993_Cousins_in_Binary_Tree.swift │ └── contents.xcplayground │ └── DS_ALGO_PRAC │ ├── DS_ALGO_PRAC.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist │ └── DS_ALGO_PRAC │ └── main.swift └── leetcode.png /algoexpert.io/python/Balanced_Bracket.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Balanced%20Brackets 2 | 3 | 4 | # O(n) time | O(n space) 5 | def balancedBrackets(string): 6 | opening_brackets = "([{" 7 | closing_brackets = ")]}" 8 | matching_brackets = {")": "(", "]": "[", "}": "{"} 9 | stack = [] 10 | for char in string: 11 | if char in opening_brackets: 12 | stack.append(char) 13 | elif char in closing_brackets: 14 | if len(stack) == 0: 15 | return False 16 | if stack[-1] == matching_brackets[char]: 17 | stack.pop() 18 | else: 19 | return False 20 | return len(stack) == 0 21 | 22 | -------------------------------------------------------------------------------- /algoexpert.io/python/Binary_Search.py: -------------------------------------------------------------------------------- 1 | def binarySearch(array, target): 2 | left, right = 0, len(array) - 1 3 | while left <= right: 4 | mid = (left + right) // 2 5 | if array[mid] == target: 6 | return mid 7 | elif array[mid] > target: 8 | right = mid - 1 9 | else: 10 | left = mid + 1 11 | return -1 -------------------------------------------------------------------------------- /algoexpert.io/python/Branch_Sums.py: -------------------------------------------------------------------------------- 1 | # This is the class of the input root. Do not edit it. 2 | class BinaryTree: 3 | def __init__(self, value): 4 | self.value = value 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | def branchSums(root): 10 | # Write your code here. 11 | sums = [] 12 | branchSumsHelper(root, root.value, sums) 13 | return sums 14 | 15 | 16 | def branchSumsHelper(root, runningSum, sums): 17 | if not root.left and not root.right: 18 | sums.append(runningSum) 19 | return 20 | 21 | if root.left: 22 | runningSum += root.left.value 23 | branchSumsHelper(root.left, runningSum, sums) 24 | runningSum -= root.left.value 25 | 26 | if root.right: 27 | runningSum += root.right.value 28 | branchSumsHelper(root.right, runningSum, sums) 29 | runningSum -= root.right.value 30 | 31 | 32 | -------------------------------------------------------------------------------- /algoexpert.io/python/Breadth_First_Search.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Breadth-first%20Search 2 | class Node: 3 | def __init__(self, name): 4 | self.children = [] 5 | self.name = name 6 | 7 | def addChild(self, name): 8 | self.children.append(Node(name)) 9 | return self 10 | 11 | def breadthFirstSearch(self, array): 12 | queue = [self] # step 1 > add root node to the queue, the node on which we are calling BFS 13 | while len(queue) > 0: 14 | current = queue.pop(0) # step 2 > pop the root/current node 15 | array.append(current.name) # step 3 > add the current node to the final array 16 | for child in current.children: # step 4 > add the children of the current node to the queue 17 | queue.append(child) 18 | return array 19 | 20 | 21 | -------------------------------------------------------------------------------- /algoexpert.io/python/Bubble_Sort.py: -------------------------------------------------------------------------------- 1 | 2 | # Best: O(n) time | O(1) space 3 | # Average: O(n^2) time | O(1) space 4 | # Worst: O(n^2) time | O(1) space 5 | def bubbleSort(array): 6 | isSorted = False 7 | counter = 0 8 | while not isSorted: 9 | isSorted = True 10 | for i in range(len(array) - 1 - counter): 11 | if array[i] > array[i + 1]: 12 | swap(i, i + 1, array) 13 | isSorted = False 14 | counter += 1 15 | return array 16 | 17 | def swap(i, j, array): 18 | array[i], array[j] = array[j], array[i] 19 | 20 | -------------------------------------------------------------------------------- /algoexpert.io/python/Caesar_Cipher_Encryptor.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Caesar%20Cipher%20Encryptor 2 | 3 | # Solution 1 4 | # O(n) time | O(n) space 5 | def caesarCipherEncryptor(string, key): 6 | new_letters = [] 7 | new_key = key % 26 8 | for letter in string: 9 | new_letters.append(get_new_letter(letter, new_key)) 10 | return "".join(new_letters) 11 | 12 | def get_new_letter(letter, key): 13 | newLetterCode = ord(letter) + key 14 | return chr(newLetterCode) if newLetterCode <= 122 else chr(96 + newLetterCode % 122) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /algoexpert.io/python/Depth_First_Search.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, name): 3 | self.children = [] 4 | self.name = name 5 | 6 | def addChild(self, name): 7 | self.children.append(Node(name)) 8 | return self 9 | 10 | def depthFirstSearch(self, array): 11 | array.append(self.name) 12 | for child in self.children: 13 | child.depthFirstSearch(array) 14 | return array 15 | 16 | 17 | result1 = [] 18 | test1 = Node("A") 19 | test1.add_child("B").add_child("C") 20 | test1.children[0].add_child("D") 21 | print(test1.depth_first_search(result1)) 22 | 23 | result2 = [] 24 | test2 = Node("A") 25 | test2.add_child("B").add_child("C").add_child("D").add_child("E") 26 | test2.children[1].add_child("F") 27 | print(test2.depth_first_search(result2)) -------------------------------------------------------------------------------- /algoexpert.io/python/Find_Loop.py: -------------------------------------------------------------------------------- 1 | 2 | # O(n) time | O(1) space 3 | class LinkedList: 4 | def __init__(self, value): 5 | self.value = value 6 | self.next = None 7 | 8 | def findLoop(head): 9 | if not head and not head.next: 10 | return None 11 | slowPtr, fastPtr = head.next, head.next.next 12 | while slowPtr != fastPtr: 13 | slowPtr = slowPtr.next 14 | fastPtr = fastPtr.next.next 15 | fastPtr = head 16 | while fastPtr != slowPtr: 17 | slowPtr = slowPtr.next 18 | fastPtr = fastPtr.next 19 | return fastPtr -------------------------------------------------------------------------------- /algoexpert.io/python/Flatten_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # This is the class of the input root. Do not edit it. 2 | class BinaryTree: 3 | def __init__(self, value, left=None, right=None): 4 | self.value = value 5 | self.left = left 6 | self.right = right 7 | 8 | def flattenBinaryTree(root): 9 | iorderNodes = getNodesInOrder(root, []) 10 | for i in range(0, len(iorderNodes) - 1): 11 | leftNode = iorderNodes[i] 12 | rightNode = iorderNodes[i + 1] 13 | leftNode.right = rightNode 14 | rightNode.left = leftNode 15 | return iorderNodes[0] 16 | 17 | 18 | def getNodesInOrder(tree, array): 19 | if tree is not None: 20 | getNodesInOrder(tree.left, array) 21 | array.append(tree) 22 | getNodesInOrder(tree.right, array) 23 | return array 24 | 25 | -------------------------------------------------------------------------------- /algoexpert.io/python/Group_Anagrams.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | def groupAnagrams(words): 3 | anagrams = defaultdict(list) 4 | for word in words: 5 | sortedWord = "".join(sorted(word)) 6 | anagrams[sortedWord].append(word) 7 | return list(anagrams.values()) -------------------------------------------------------------------------------- /algoexpert.io/python/Insertion_Sort.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Best: O(n) time | O(1) space 5 | # Average: O(n^2) time | O(1) space 6 | # Worst: O(n^2) time | O(1) space 7 | def insertionSort(array): 8 | for i in range(1, len(array)): 9 | j = i 10 | while j > 0 and array[j] < array[j - 1]: 11 | swap(j, j - 1, array) 12 | j -= 1 13 | return array 14 | def swap(i, j, array): 15 | array[i], array[j] = array[j], array[i] 16 | 17 | 18 | input_array = [8, 5, 2, 9, 5, 6, 3] 19 | sorted_array = insertionSort(input_array) 20 | print("Sorted Array: ", sorted_array) -------------------------------------------------------------------------------- /algoexpert.io/python/Interweaving_Strings.py: -------------------------------------------------------------------------------- 1 | def interweavingStrings(one, two, three): 2 | if len(three) != len(one) + len(two): 3 | return False 4 | 5 | cache = [[None for j in range(len(two) + 1)] for i in range(len(one) + 1)] 6 | return areInterwoven(one, two, three, 0, 0, cache) 7 | 8 | 9 | def areInterwoven(one, two, three, i, j, cache): 10 | if cache[i][j] is not None: 11 | return cache[i][j] 12 | 13 | k = i + j 14 | if k == len(three): 15 | return True 16 | 17 | if i < len(one) and one[i] == three[k]: 18 | cache[i][j] = areInterwoven(one, two, three, i + 1, j, cache) 19 | if cache[i][j]: 20 | return True 21 | 22 | if j < len(two) and two[j] == three[k]: 23 | cache[i][j] = areInterwoven(one, two, three, i, j + 1, cache) 24 | return cache[i][j] 25 | 26 | cache[i][j] = False 27 | return False 28 | 29 | -------------------------------------------------------------------------------- /algoexpert.io/python/Iterative_In-order_Traversal.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # O(n) time | O(1) space 4 | def iterativeInOrderTraversal(tree, callback): 5 | previousNode = None 6 | currentNode = tree 7 | while currentNode is not None: 8 | if previousNode is None or previousNode == currentNode.parennt: 9 | if currentNode.left is not None: 10 | nextNode = currentNode.left 11 | else: 12 | callback(currentNode) 13 | nextNode = currentNode.right if currentNode.right is not None else currentNode.parennt 14 | elif previousNode == currentNode.left: 15 | callback(currentNode) 16 | nextNode = currentNode.right if currentNode.right is not None else currentNode.parennt 17 | else: 18 | nextNode = currentNode.parennt 19 | previousNode = currentNode 20 | currentNode = nextNode 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /algoexpert.io/python/KMP_Algorithm.py: -------------------------------------------------------------------------------- 1 | def knuthMorrisPrattAlgorithm(string, substring): 2 | pattern = buildPattern(substring) 3 | return doesMatch(string, substring, pattern) 4 | 5 | def buildPattern(substring): 6 | pattern = [-1 for _ in substring] 7 | j, i = 0, 1 8 | while i < len(substring): 9 | if substring[i] == substring[j]: 10 | pattern[i] = j 11 | i += 1 12 | j += 1 13 | elif j > 0: 14 | j = pattern[j - 1] + 1 15 | else: 16 | i += 1 17 | return pattern 18 | 19 | def doesMatch(string, substring, pattern): 20 | i, j = 0, 0 21 | while i + len(substring) - j <= len(string): 22 | if string[i] == substring[j]: 23 | if j == len(substring) - 1: 24 | return True 25 | i += 1 26 | j += 1 27 | elif j > 0: 28 | j = pattern[j - 1] + 1 29 | else: 30 | i += 1 31 | return False 32 | -------------------------------------------------------------------------------- /algoexpert.io/python/Kadane's_Algorithm.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Kadane's%20Algorithm 2 | 3 | 4 | # O(n) time | O(1) space - where n is the length of the input array 5 | def kadanesAlgorithm(array): 6 | maxEdingHere, maxSoFar = array[0], array[0] 7 | for i in range(1, len(array)): 8 | num = array[i] 9 | maxEdingAtPrevIdx = maxEdingHere 10 | maxEdingHere = max(num, num + maxEdingAtPrevIdx) 11 | maxSoFar = max(maxSoFar, maxEdingHere) 12 | return maxSoFar 13 | 14 | -------------------------------------------------------------------------------- /algoexpert.io/python/Largest_Range.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # O(n) time | O(n) space 4 | def largestRange(array): 5 | bestRange = [] 6 | longestLength = 0 7 | nums = {} 8 | for num in array: 9 | nums[num] = True 10 | for num in array: 11 | if not nums[num]: 12 | continue 13 | nums[num] = False 14 | currentLenght = 1 15 | left = num - 1 16 | right = num + 1 17 | while left in nums: 18 | nums[left] = False 19 | currentLenght += 1 20 | left -= 1 21 | while right in nums: 22 | nums[right] = False 23 | currentLenght += 1 24 | right += 1 25 | if currentLenght > longestLength: 26 | longestLength = currentLenght 27 | bestRange = [left + 1, right - 1] 28 | return bestRange 29 | -------------------------------------------------------------------------------- /algoexpert.io/python/Longest_Common_Subsequence.py: -------------------------------------------------------------------------------- 1 | # Solution: My solution using 2d dp 2 | # O(nm) time | O(nm) space 3 | def longestCommonSubsequence(string1, string2): 4 | dp = [[[] for _ in range(len(string2) + 1)] for _ in range(len(string1) + 1)] 5 | for i in range(1, len(string1) + 1): 6 | x = string1[i - 1] 7 | for j in range(1, len(string2) + 1): 8 | rx = string2[j - 1] 9 | if x == rx: 10 | dp[i][j] = dp[i - 1][j - 1] + [x] 11 | else: 12 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j], key=len) 13 | return dp[-1][-1] 14 | 15 | 16 | -------------------------------------------------------------------------------- /algoexpert.io/python/Longest_Peak.py: -------------------------------------------------------------------------------- 1 | def longestPeak(array): 2 | longestPeakLen = 0 3 | i = 1 4 | while i < len(array) - 1: 5 | isPeak = array[i - 1] < array[i] > array[i + 1] 6 | if not isPeak: 7 | i += 1 8 | continue 9 | 10 | leftIdx = i - 2 11 | while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]: 12 | leftIdx -= 1 13 | 14 | rightIdx = i + 2 15 | while rightIdx < len(array) and array[rightIdx - 1] > array[rightIdx]: 16 | rightIdx += 1 17 | 18 | currentPeakLen = rightIdx - leftIdx - 1 19 | longestPeakLen = max(longestPeakLen, currentPeakLen) 20 | i = rightIdx 21 | 22 | return longestPeakLen 23 | 24 | -------------------------------------------------------------------------------- /algoexpert.io/python/Longest_Substring_Without_Duplication.py: -------------------------------------------------------------------------------- 1 | 2 | # O(n) time | O(min(n, a)) space 3 | def longestSubstringWithoutDuplication(string): 4 | lastSeen = {} 5 | longest = [0, 1] # Here 0 and 1 is the values in the 0 and 1 index. This variable stores the start and end index of of the longest string. 6 | startIndex = 0 7 | for i, char in enumerate(string): 8 | if char in lastSeen: 9 | startIndex = max(startIndex, lastSeen[char] + 1) 10 | if longest[1] - longest[0] < i + 1 - startIndex: # Here 0 and 1 is the index of the value of longest array 11 | longest = [startIndex, i + 1] 12 | lastSeen[char] = i 13 | return string[longest[0]:longest[1]] 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /algoexpert.io/python/Max_Path_Sum_In_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Time O(n) | Space O(logn) 2 | def maxPathSum(tree): 3 | _, maxSum = findMaxSum(tree) 4 | return maxSum 5 | 6 | def findMaxSum(tree): 7 | if tree is None: 8 | return (0, 0) 9 | leftMaxSumAsBranch, leftMaxPathSum = findMaxSum(tree.left) 10 | rightMaxSumAsBranch, rightMaxPathSum = findMaxSum(tree.right) 11 | maxChildSumAsBranch = max(leftMaxSumAsBranch, rightMaxSumAsBranch) 12 | 13 | value = tree.value 14 | maxSumAsBrach = max(maxChildSumAsBranch + value, value) 15 | maxSumAsRootNoode = max(leftMaxSumAsBranch + value + rightMaxSumAsBranch, maxSumAsBrach) 16 | maxPathSum = max(leftMaxPathSum, rightMaxPathSum, maxSumAsRootNoode) 17 | 18 | return (maxSumAsBrach, maxPathSum) 19 | -------------------------------------------------------------------------------- /algoexpert.io/python/Max_Sum_Increasing_Subsequence.py: -------------------------------------------------------------------------------- 1 | def maxSumIncreasingSubsequence(array): 2 | sequeces = [None for _ in array] 3 | sums = [num for num in array] 4 | maxSumIdx = 0 5 | for i in range(len(array)): 6 | currentum = array[i] 7 | for j in range(0, i): 8 | otherum = array[j] 9 | if otherum < currentum and sums[j] + currentum >= sums[i]: 10 | sums[i] = sums[j] + currentum 11 | sequeces[i] = j 12 | if sums[maxSumIdx] <= sums[i]: 13 | maxSumIdx = i 14 | increasigSequence = buildSequece(array, sequeces, maxSumIdx) 15 | return [sums[maxSumIdx], increasigSequence] 16 | 17 | def buildSequece(array, sequeces, curIdx): 18 | sequen = [] 19 | while curIdx is not None: 20 | sequen.append(array[curIdx]) 21 | curIdx = sequeces[curIdx] 22 | return list(reversed(sequen)) 23 | 24 | -------------------------------------------------------------------------------- /algoexpert.io/python/Maximum_Subset_Sum_With_No_Adjacent_Element.py: -------------------------------------------------------------------------------- 1 | 2 | # Solution 1 3 | # O(n) time | O(n) space 4 | def max_subset_sum_with_no_adjacent(array): 5 | if not len(array): 6 | return 0 7 | if len(array) == 1: 8 | return array[0] 9 | max_sum = array[:] # copying the array into max_sum 10 | max_sum[1] = max(array[0], array[1]) 11 | for i in range(2, len(array)): 12 | max_sum[i] = max_sum(max_sum[i - 1], max_sum[i - 2] + array[i]) 13 | return max_sum[-1] # -1 refers to the last index 14 | 15 | # Solution 2 16 | # O(n) time | O(1) space 17 | def max_subset_sum_with_no_adjacent(array): 18 | if not len(array): 19 | return 0 20 | if len(array) == 1: 21 | return array[0] 22 | second = array[0] 23 | first = max(array[0], array[1]) 24 | for i in range(2, len(array)): 25 | current = max(first, second + array[i]) 26 | second = first 27 | first = current 28 | return first 29 | 30 | -------------------------------------------------------------------------------- /algoexpert.io/python/Merge_Linked_List.py: -------------------------------------------------------------------------------- 1 | # This is an input class. Do not edit. 2 | class LinkedList: 3 | def __init__(self, value): 4 | self.value = value 5 | self.next = None 6 | 7 | 8 | def mergeLinkedLists(headOne, headTwo): 9 | p1, p2 = headOne, headTwo 10 | p1Prev = None 11 | while p1 and p2: 12 | if p1.value < p2.value: 13 | p1Prev = p1 14 | p1 = p1.next 15 | else: 16 | if p1Prev: 17 | p1Prev.next = p2 18 | p1Prev = p2 19 | p2 = p2.next 20 | p1Prev.next = p1 21 | if not p1: 22 | p1Prev.next = p2 23 | return headOne if headOne.value < headTwo.value else headTwo 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /algoexpert.io/python/Min_Number_Of_Jumps.py: -------------------------------------------------------------------------------- 1 | # Solution #1 2 | # O(n^2) time | O(n) space 3 | def minNumberOfJumps(array): 4 | aLen = len(array) 5 | if aLen == 1: 6 | return 0 7 | dp = [float("inf") for _ in range(aLen)] 8 | dp[0] = 0 9 | for destiinationIdx in range(1, aLen): 10 | for sourceIdx in range(0, destiinationIdx): 11 | if sourceIdx + array[sourceIdx] >= destiinationIdx: 12 | dp[destiinationIdx] = min(dp[destiinationIdx], dp[sourceIdx] + 1) 13 | return dp[-1] 14 | 15 | # Solution #2 16 | # O(n) time | O(1) space 17 | def minNumberOfJumps(array): 18 | if len(array) == 1: 19 | return 0 20 | jumps = 0 21 | maxReach = array[0] 22 | steps = array[0] 23 | for i in range(1, len(array) - 1): 24 | maxReach = max(maxReach, i + array[i]) 25 | steps -= 1 26 | if steps == 0: 27 | jumps += 1 28 | steps = maxReach - 1 29 | return jumps + 1 -------------------------------------------------------------------------------- /algoexpert.io/python/Monotonic_Array.py: -------------------------------------------------------------------------------- 1 | def isMonotonic(array): 2 | if len(array) <= 2: 3 | return True 4 | for i in range(1, len(array) - 1): 5 | prevN = array[i - 1] 6 | currN = array[i] 7 | nextN = array[i + 1] 8 | if prevN <= currN <= nextN or prevN >= currN >= nextN: 9 | continue 10 | else: 11 | return False 12 | return True 13 | 14 | -------------------------------------------------------------------------------- /algoexpert.io/python/Move_Element_To_End.py: -------------------------------------------------------------------------------- 1 | def moveElementToEnd(array, toMove): 2 | left, right = 0, len(array) - 1 3 | while left < right: 4 | if array[right] == toMove: 5 | right -= 1 6 | if array[left] != toMove: 7 | left += 1 8 | if array[left] == toMove and array[right] != toMove: 9 | array[left], array[right] = array[right], array[left] 10 | return array 11 | -------------------------------------------------------------------------------- /algoexpert.io/python/Number_Of_Binary_Tree_Topologies.py: -------------------------------------------------------------------------------- 1 | def numberOfBinaryTreeTopologies(n, cache={0: 1}): 2 | if n in cache: 3 | return cache[n] 4 | numbersOfTree = 0 5 | for leftTreeSize in range(n): 6 | rightTreeSize = n - 1 - leftTreeSize 7 | numOfLeftTree = numberOfBinaryTreeTopologies(leftTreeSize, cache) 8 | numOfRigntTree = numberOfBinaryTreeTopologies(rightTreeSize, cache) 9 | numbersOfTree += numOfRigntTree * numOfLeftTree 10 | cache[n] = numbersOfTree 11 | return numbersOfTree -------------------------------------------------------------------------------- /algoexpert.io/python/Number_Of_Ways_To_Make_Changes.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Number%20Of%20Ways%20To%20Make%20Change 2 | 3 | 4 | # O(nd) time | O(n) space 5 | # Where, 'n' is amount and 'd' is number of denominators 6 | def number_of_ways_to_make_change(n, denoms): 7 | ways = [0 for amount in range(n + 1)] 8 | ways[0] = 1 9 | for denom in denoms: 10 | for amount in range(1, n + 1): 11 | if denom <= amount: 12 | ways[amount] += ways[amount - denom] 13 | return ways[n] 14 | 15 | -------------------------------------------------------------------------------- /algoexpert.io/python/Numbers_In_Pi.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # O(n^3) time | O(n + m) space 4 | def numbersInPi(pi, numbers): 5 | numbersTable = {number: True for number in numbers} 6 | minSpaces = getMinSpaces(pi, numbersTable, {}, 0) 7 | return -1 if minSpaces == float('inf') else minSpaces 8 | 9 | 10 | def getMinSpaces(pi, numbersTable, cache, idx): 11 | if idx == len(pi): 12 | return -1 13 | if idx in cache: 14 | return cache[idx] 15 | minSpaces = float('inf') 16 | for i in range(idx, len(pi)): 17 | prefix = pi[idx:i + 1] 18 | if prefix in numbersTable: 19 | minSpacesInSiffix = getMinSpaces(pi, numbersTable, cache, i + 1) 20 | minSpaces = min(minSpaces, minSpacesInSiffix + 1) 21 | cache[idx] = minSpaces 22 | return cache[idx] 23 | 24 | 25 | -------------------------------------------------------------------------------- /algoexpert.io/python/Powerset.py: -------------------------------------------------------------------------------- 1 | # Solution 1 - Recursive 2 | # O(n*2^n) time | O(n*2^n) space 3 | def power_set(array, index = None): 4 | if index is None: 5 | index = len(array) - 1 6 | if index < 0: 7 | return [[]] 8 | ele = array[index] 9 | subset = power_set(array, index - 1) 10 | for i in range(len(subset)): 11 | current_subset = subset[i] 12 | subset.append(current_subset + [ele]) 13 | return subset 14 | 15 | 16 | # Solution 2 - Iterative 17 | # O(n*2^n) time | O(n*2^n) space 18 | def power_set(array): 19 | subsets = [[]] 20 | for ele in array: 21 | for i in range(len(subsets)): 22 | current_subset = subsets[i] 23 | subsets.append(current_subset + [ele]) 24 | return subsets 25 | 26 | 27 | -------------------------------------------------------------------------------- /algoexpert.io/python/Product_Sum.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # O(n) time | O(d) space - where nn is the total number of elements in the array 4 | # including sub-elements, and d is the greatest depth of 'special' arrays in the array 5 | def productSum(array, multiplier = 1): 6 | sumProd = 0 7 | for element in array: 8 | if type(element) is list: 9 | sumProd += productSum(element, multiplier + 1) 10 | else: 11 | sumProd += element 12 | return sumProd * multiplier -------------------------------------------------------------------------------- /algoexpert.io/python/Quick_Select.py: -------------------------------------------------------------------------------- 1 | def quickselect(array, k): 2 | position = k - 1 3 | return quickSelectHelper(array, 0, len(array) - 1, position) 4 | 5 | def quickSelectHelper(array, srtIdx, endIdx, position): 6 | while True: 7 | if srtIdx > endIdx: 8 | raise Exception("Algorrithm should never be here!") 9 | pivotIdx = srtIdx 10 | leftIdx = srtIdx + 1 11 | rightIdx = endIdx 12 | while leftIdx <= rightIdx: 13 | if array[leftIdx] > array[pivotIdx] > array[rightIdx]: 14 | array[leftIdx], array[rightIdx] = array[rightIdx], array[leftIdx] 15 | if array[leftIdx] <= array[pivotIdx]: 16 | leftIdx += 1 17 | if array[rightIdx] >= array[pivotIdx]: 18 | rightIdx -= 1 19 | array[pivotIdx], array[rightIdx] = array[rightIdx], array[pivotIdx] 20 | if rightIdx == position: 21 | return array[position] 22 | elif rightIdx > position: 23 | endIdx = rightIdx - 1 24 | else: 25 | srtIdx = rightIdx + 1 26 | -------------------------------------------------------------------------------- /algoexpert.io/python/Rectangle_Mania.py: -------------------------------------------------------------------------------- 1 | """ 2 | x1,y1 3 | 4 | x2,y2 5 | """ 6 | 7 | 8 | def rectangleMania(coords): 9 | coordSet = set([(coord[0], coord[1]) for coord in coords]) 10 | rectangleCount = 0 11 | for i in range(len(coords)): 12 | for j in range(len(coords)): 13 | coordOne = coords[i] 14 | coordTwo = coords[j] 15 | if coordOne == coordTwo: 16 | continue 17 | if (coordOne[0] > coordTwo[0]) and (coordOne[1] > coordTwo[1]): 18 | if (coordOne[0], coordTwo[1]) in coordSet and (coordTwo[0], coordOne[1]) in coordSet: 19 | rectangleCount += 1 20 | return rectangleCount 21 | 22 | -------------------------------------------------------------------------------- /algoexpert.io/python/Remove_Kth_Node_From_End.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Remove%20Kth%20Node%20From%20End 2 | 3 | 4 | # O(n) time | O(1) space 5 | def remove_kth_node_from_end(head, k): 6 | counter = 1 7 | first = head 8 | second = head 9 | while counter <= k: 10 | second = second.next 11 | counter += 1 12 | if second is None: 13 | head.value = head.next.value 14 | head.next = head.next.next 15 | return 16 | while second.next is not None: 17 | second = second.next 18 | first = first.next 19 | first.next = first.next.next 20 | 21 | 22 | -------------------------------------------------------------------------------- /algoexpert.io/python/Reverse_Linked_List.py: -------------------------------------------------------------------------------- 1 | # O(n) time | O(1) space 2 | def reverseLinkedList(head): 3 | prevN, nextN = None, None 4 | while head is not None: 5 | nextN = head.next 6 | head.next = prevN 7 | prevN = head 8 | head = nextN 9 | return prevN -------------------------------------------------------------------------------- /algoexpert.io/python/Right_Sibling_Tree.py: -------------------------------------------------------------------------------- 1 | # This is the class of the input root. Do not edit it. 2 | class BinaryTree: 3 | def __init__(self, value, left=None, right=None): 4 | self.value = value 5 | self.left = left 6 | self.right = right 7 | 8 | def rightSiblingTree(root): 9 | mutate(root, None, None) 10 | return root 11 | 12 | def mutate(node, parent, isLeftChild): 13 | if node is None: 14 | return 15 | left, right = node.left, node.right 16 | mutate(left, node, True) 17 | if parent is None: 18 | node.right = None 19 | elif isLeftChild: 20 | node.right = parent.right 21 | else: 22 | if parent.right is None: 23 | node.right = None 24 | else: 25 | node.right = parent.right.left 26 | mutate(right, node, False) 27 | -------------------------------------------------------------------------------- /algoexpert.io/python/Same_BSTs.py: -------------------------------------------------------------------------------- 1 | def sameBsts(arrayOne, arrayTwo): 2 | if len(arrayOne) != len(arrayTwo): 3 | return False 4 | 5 | if len(arrayOne) == 0 and len(arrayTwo) == 0: 6 | return True 7 | 8 | if arrayOne[0] != arrayTwo[0]: 9 | return False 10 | 11 | leftOne = getSmaller(arrayOne) 12 | leftTwo = getSmaller(arrayTwo) 13 | rightOne = getBiggerOrEqual(arrayOne) 14 | rightTwo = getBiggerOrEqual(arrayTwo) 15 | 16 | return sameBsts(leftOne, leftTwo) and sameBsts(rightOne, rightTwo) 17 | 18 | 19 | def getSmaller(array): 20 | smaller = [] 21 | for i in range(1, len(array)): 22 | if array[i] < array[0]: 23 | smaller.append(array[i]) 24 | return smaller 25 | 26 | 27 | def getBiggerOrEqual(array): 28 | biggerOrEqual = [] 29 | for i in range(1, len(array)): 30 | if array[i] >= array[0]: 31 | biggerOrEqual.append(array[i]) 32 | return biggerOrEqual 33 | 34 | -------------------------------------------------------------------------------- /algoexpert.io/python/Search_In_Sorted_Matrix.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix 2 | 3 | 4 | # O(n + m) time | O(1) space 5 | # where 'n' is the length of row and 'm' is the length on column 6 | def search_in_sorted_matrix(matrix, target): 7 | row = 0 8 | col = len(matrix[0]) - 1 9 | while row < len(matrix) and col >= 0: 10 | if matrix[row][col] > target: 11 | col -= 1 12 | elif matrix[row][col] < row: 13 | row += 1 14 | else: 15 | return [row, col] 16 | return [-1, -1] 17 | 18 | -------------------------------------------------------------------------------- /algoexpert.io/python/Selection_Sort.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Selection%20Sort 2 | 3 | 4 | # Best: O(n^2) time | O(1) space 5 | # Avarage: O(n^2) time | O(1) space 6 | # Worst: O(n^2) time | O(1) space 7 | def selectionSort(array): 8 | current_index = 0 9 | while current_index < len(array) - 1: 10 | smallest_index = current_index 11 | for i in range(current_index + 1, len(array)): 12 | if array[i] < array[smallest_index]: 13 | smallest_index = i 14 | swap(current_index, smallest_index, array) 15 | current_index += 1 16 | return array 17 | 18 | def swap(i, j, array): 19 | array[i], array[j] = array[j], array[i] 20 | 21 | -------------------------------------------------------------------------------- /algoexpert.io/python/Single_Cycle_Check.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Single%20Cycle%20Check 2 | 3 | 4 | # O(n) time | O(1) space - where n is the length of the input array 5 | def has_single_cycle(array): 6 | number_of_elements_visited = 0 7 | current_index = 0 8 | while number_of_elements_visited < len(array): 9 | if number_of_elements_visited > 0 and current_index == 0: 10 | return False 11 | number_of_elements_visited += 1 12 | current_index = get_next_index(current_index, array) 13 | return current_index == 0 14 | 15 | 16 | def get_next_index(current_index, array): 17 | jump = array[current_index] 18 | next_index = (current_index + jump) % len(array) 19 | return next_index if next_index >= 0 else next_index + len(array) 20 | 21 | 22 | input_array = [2, -1, 1, 2, 2] 23 | print("Is Single Cycle: ", has_single_cycle(input_array)) 24 | 25 | -------------------------------------------------------------------------------- /algoexpert.io/python/Smallest_Difference.py: -------------------------------------------------------------------------------- 1 | # O(nlog(n) + mlon(m)) time | O(1) space 2 | def smallestDifference(arrayOne, arrayTwo): 3 | array_one, array_two = sorted(arrayOne), sorted(arrayTwo) 4 | index_one, index_two = 0, 0 5 | smallestDiff = float("inf") 6 | result_pair = [] 7 | while index_one < len(array_one) and index_two < len(array_two): 8 | first_num = array_one[index_one] 9 | second_num = array_two[index_two] 10 | currentDiff = abs(first_num - second_num) 11 | if currentDiff < smallestDiff: 12 | smallestDiff = currentDiff 13 | result_pair = [first_num, second_num] 14 | if first_num <= second_num: 15 | index_one += 1 16 | else: 17 | index_two += 1 18 | return result_pair 19 | 20 | 21 | -------------------------------------------------------------------------------- /algoexpert.io/python/Smallest_Substring_Containing.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | def smallestSubstringContaining(bigString, smallString): 3 | need = Counter(smallString) 4 | missing = len(smallString) 5 | left, windowStart, windowEnd = 0, 0, 0 6 | for right in range(0, len(bigString)): 7 | currChar = bigString[right] 8 | if need[currChar] > 0: 9 | missing -=1 10 | need[currChar] -= 1 11 | if missing == 0: 12 | if windowEnd == 0: 13 | windowStart, windowEnd = left, right 14 | while left < right and need[bigString[left]] < 0: 15 | need[bigString[left]] += 1 16 | left += 1 17 | if (right - left) <= (windowEnd - windowStart): 18 | windowStart, windowEnd = left, right 19 | return "" if missing > 0 else bigString[windowStart:windowEnd+1] -------------------------------------------------------------------------------- /algoexpert.io/python/Spiral_Traverse.py: -------------------------------------------------------------------------------- 1 | def spiralTraverse(matrix): 2 | result = [] 3 | sR, eR, sC, eC = 0, len(matrix) - 1, 0, len(matrix[0]) - 1 4 | while sR <= eR and sC <= eC: 5 | for i in range(sC, eC + 1): 6 | result.append(matrix[sR][i]) 7 | 8 | for i in range(sR + 1, eR + 1): 9 | result.append(matrix[i][eC]) 10 | 11 | for i in range(eC - 1, sC - 1, -1): 12 | if sR == eR: 13 | break 14 | result.append(matrix[eR][i]) 15 | 16 | for i in range(eR - 1, sR, -1): 17 | if sC == eC: 18 | break 19 | result.append(matrix[i][sC]) 20 | 21 | sR += 1 22 | eR -= 1 23 | sC += 1 24 | eC -= 1 25 | 26 | return result 27 | -------------------------------------------------------------------------------- /algoexpert.io/python/Subarray_Sort.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def subarraySort(array): 4 | minOutOfOrder = math.inf 5 | maxOutOfOrder = -math.inf 6 | for i in range(len(array)): 7 | num = array[i] 8 | if isOutOfOrder(i, num, array): 9 | minOutOfOrder = min(minOutOfOrder, num) 10 | maxOutOfOrder = max(maxOutOfOrder, num) 11 | if minOutOfOrder == math.inf: 12 | return [-1, -1] 13 | subArrayLeftIdx = 0 14 | while array[subArrayLeftIdx] <= minOutOfOrder: 15 | subArrayLeftIdx += 1 16 | subArrayRightIdx = len(array) - 1 17 | while maxOutOfOrder <= array[subArrayRightIdx]: 18 | subArrayRightIdx -= 1 19 | return [subArrayLeftIdx, subArrayRightIdx] 20 | 21 | 22 | def isOutOfOrder(i, num, array): 23 | if i == 0: 24 | return num > array[i + 1] 25 | if i == len(array) - 1: 26 | return num < array[i - 1] 27 | return num < array[i - 1] or num > array[i + 1] 28 | -------------------------------------------------------------------------------- /algoexpert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/algoexpert.png -------------------------------------------------------------------------------- /leetcode.com/objective-c/DS_ALGO_PRAC/DS_ALGO_PRAC.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /leetcode.com/objective-c/DS_ALGO_PRAC/DS_ALGO_PRAC.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /leetcode.com/objective-c/DS_ALGO_PRAC/DS_ALGO_PRAC/Problems/226_Invert_Binary_Tree.m: -------------------------------------------------------------------------------- 1 | // 2 | // 226_Invert_Binary_Tree.m 3 | // DS_ALGO_PRAC 4 | // 5 | // Created by Partho Biswas on 6/2/20. 6 | // Copyright © 2020 Partho Biswas. All rights reserved. 7 | // 8 | 9 | #import "226_Invert_Binary_Tree.h" 10 | 11 | struct TreeNode { 12 | int val; 13 | struct TreeNode *left; 14 | struct TreeNode *right; 15 | }; 16 | 17 | @implementation _26_Invert_Binary_Tree 18 | 19 | - (struct TreeNode *)invertTree:(struct TreeNode *)root { 20 | if (!root) { 21 | return nil; 22 | } 23 | 24 | struct TreeNode *left = [self invertTree:root->left]; 25 | struct TreeNode *right = [self invertTree:root->right]; 26 | root->left = right; 27 | root->right = left; 28 | return root; 29 | } 30 | 31 | @end 32 | -------------------------------------------------------------------------------- /leetcode.com/objective-c/DS_ALGO_PRAC/DS_ALGO_PRAC/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // DS_ALGO_PRAC 4 | // 5 | // Created by Partho Biswas on 6/2/20. 6 | // Copyright © 2020 Partho Biswas. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | int main(int argc, const char * argv[]) { 12 | @autoreleasepool { 13 | // insert code here... 14 | NSLog(@"Hello, World!"); 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /leetcode.com/python/100_Same_Tree.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class Solution: 5 | def isSameTree(self, p, q): 6 | """ 7 | :type p: TreeNode 8 | :type q: TreeNode 9 | :rtype: bool 10 | """ 11 | 12 | def check(p, q): 13 | # if both are None 14 | if not p and not q: 15 | return True 16 | # one of p and q is None 17 | if not q or not p: 18 | return False 19 | if p.val != q.val: 20 | return False 21 | return True 22 | 23 | deq = deque([(p, q), ]) 24 | while deq: 25 | p, q = deq.popleft() 26 | if not check(p, q): 27 | return False 28 | if p: 29 | deq.append((p.left, q.left)) 30 | deq.append((p.right, q.right)) 31 | return True -------------------------------------------------------------------------------- /leetcode.com/python/1027_Longest_Arithmetic_Sequence.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Solution(object): 5 | def longestArithSeqLength(self, A): 6 | """ 7 | :type A: List[int] 8 | :rtype: int 9 | """ 10 | dp = defaultdict(lambda: 1) # setting the default value of defaultdict to 1 11 | for i in range(len(A)): 12 | for j in range(i + 1, len(A)): 13 | ai, aj = A[i], A[j] 14 | dp[j, aj - ai] = dp[i, aj - ai] + 1 15 | return max(dp.values()) 16 | 17 | 18 | """ 19 | [9,4,7,2,10] >> [4,7,10] 20 | 21 | j> 22 | i 9,4,7,2,10 23 | V 24 | 9 x 25 | 4 x 26 | 7 x 27 | 2 x 28 | 10 x 29 | 30 | """ -------------------------------------------------------------------------------- /leetcode.com/python/102_Binary_Tree_Level_Order_Traversal.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 levelOrder(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: List[List[int]] 13 | """ 14 | levels = [] 15 | if not root: 16 | return levels 17 | 18 | currentLevel = 0 19 | queue = [root, ] 20 | while queue: 21 | levels.append([]) 22 | levelLength = len(queue) 23 | for i in range(levelLength): 24 | node = queue.pop(0) 25 | levels[currentLevel].append(node.val) 26 | if node.left: 27 | queue.append(node.left) 28 | if node.right: 29 | queue.append(node.right) 30 | 31 | currentLevel += 1 32 | 33 | return levels 34 | -------------------------------------------------------------------------------- /leetcode.com/python/1048_Longest_String_Chain.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution(object): 3 | def longestStrChain(self, words): 4 | """ 5 | :type words: List[str] 6 | :rtype: int 7 | """ 8 | if len(words) <= 1: 9 | return 1 10 | dp = defaultdict(int) 11 | words = sorted(words, key=len) 12 | for word in words: 13 | for i in range(len(word)): 14 | possiblePredecessor = word[:i] + word[i + 1:] 15 | dp[word] = max(dp[possiblePredecessor] + 1, dp[word]) 16 | return max(dp.values()) -------------------------------------------------------------------------------- /leetcode.com/python/104_Maximum_Depth_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 | def maxDepth(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | if root is None: 15 | return 0 16 | left_height = self.maxDepth(root.left) 17 | right_height = self.maxDepth(root.right) 18 | return max(left_height, right_height) + 1 19 | 20 | -------------------------------------------------------------------------------- /leetcode.com/python/1051_Height_Checker.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.com/python/1051_Height_Checker.py -------------------------------------------------------------------------------- /leetcode.com/python/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.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 buildTree(self, preorder, inorder): 10 | """ 11 | :type preorder: List[int] 12 | :type inorder: List[int] 13 | :rtype: TreeNode 14 | """ 15 | if len(inorder) == 0: 16 | return None 17 | rootIdxIntoInorder = inorder.index(preorder[0]) 18 | root = TreeNode(preorder[0]) 19 | root.left = self.buildTree(preorder[1:], inorder[:rootIdxIntoInorder]) 20 | root.right = self.buildTree(preorder[rootIdxIntoInorder + 1:], inorder[rootIdxIntoInorder + 1:]) 21 | return root 22 | 23 | 24 | sol = Solution() 25 | preorder = [3,9,20,15,7] 26 | inorder = [9,3,15,20,7] 27 | out = sol.buildTree(preorder, inorder) 28 | print("Res: ", out) 29 | 30 | -------------------------------------------------------------------------------- /leetcode.com/python/1079_Letter_Tile_Possibilities.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | class Solution(object): 3 | def numTilePossibilities(self, tiles): 4 | """ 5 | :type tiles: str 6 | :rtype: int 7 | """ 8 | sequeces = [] 9 | for i in range(len(tiles)): 10 | sequeces.extend(list(itertools.permutations(tiles, i + 1))) 11 | return len(set(sequeces)) -------------------------------------------------------------------------------- /leetcode.com/python/108_Convert_Sorted_Array_to_Binary_Search_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 sortedArrayToBST(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: TreeNode 13 | """ 14 | return self.sortedArrayToBSTHelper(nums, 0, len(nums) - 1) 15 | 16 | def sortedArrayToBSTHelper(self, nums, left, right): 17 | if left > right: 18 | return None 19 | rootIdx = (left + right) // 2 20 | root = TreeNode(nums[rootIdx]) 21 | root.left = self.sortedArrayToBSTHelper(nums, left, rootIdx - 1) 22 | root.right = self.sortedArrayToBSTHelper(nums, rootIdx + 1, right) 23 | return root 24 | 25 | -------------------------------------------------------------------------------- /leetcode.com/python/1092_Shortest_Common_Supersequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def shortestCommonSupersequence(self, str1, str2): 3 | """ 4 | :type str1: str 5 | :type str2: str 6 | :rtype: str 7 | """ 8 | str1Len, str2Len = len(str1), len(str2) 9 | dp = [["" for _ in range(str1Len + 1)] for _ in range(str2Len + 1)] 10 | 11 | # if one of the strings is of zero length, SCS would be equal to the length of the other string 12 | for i in range(1, str1Len + 1): 13 | dp[0][i] = str1[i - 1] 14 | for i in range(1, str2Len + 1): 15 | dp[i][0] = str2[i - 1] 16 | 17 | for i in range(1, str2Len + 1): 18 | for j in range(1, str1Len + 1): 19 | if str1[j - 1] == str2[i - 1]: 20 | dp[i][j] = str2[i - 1] + dp[i - 1][j - 1] 21 | else: 22 | dp[i][j] = str2[i - 1] + min(dp[i - 1][j], dp[i][j - 1]) 23 | return dp[-1][-1] 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /leetcode.com/python/1099_Two_Sum_Less_Than_K.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSumLessThanK(self, A, K): 3 | """ 4 | :type A: List[int] 5 | :type K: int 6 | :rtype: int 7 | """ 8 | A.sort() 9 | i, j = 0, len(A) - 1 10 | S = -1 11 | while i < j: 12 | currentSum = A[i] + A[j] 13 | if currentSum < K: 14 | S = max(S, currentSum) 15 | i += 1 16 | else: 17 | j -= 1 18 | return S 19 | -------------------------------------------------------------------------------- /leetcode.com/python/110_Balanced_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 | def check(node): 9 | if node == None: 10 | return (0, True) 11 | l_depth, l_balanced = check(node.left) 12 | r_depth, r_balanced = check(node.right) 13 | return max(l_depth, r_depth) + 1, l_balanced and r_balanced and abs(l_depth - r_depth) <= 1 14 | 15 | 16 | class Solution: 17 | def isBalanced(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: bool 21 | """ 22 | return check(root)[1] 23 | 24 | -------------------------------------------------------------------------------- /leetcode.com/python/1118_-Number_of_Days_in_a_Month.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | 3 | 4 | class Solution(object): 5 | def numberOfDays(self, Y, M): 6 | """ 7 | :type Y: int 8 | :type M: int 9 | :rtype: int 10 | """ 11 | monthDayDict = {'1': 31, '2': 28, '3': 31, '4': 30, '5': 31, '6': 30, '7': 31, '8': 31, '9': 30, '10': 31, 12 | '11': 30, '12': 31} 13 | days = monthDayDict[str(M)] 14 | if M == 2 and calendar.isleap(Y): 15 | days = 29 16 | 17 | return days 18 | -------------------------------------------------------------------------------- /leetcode.com/python/1119_Remove_Vowels_from_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeVowels(self, S): 3 | """ 4 | :type S: str 5 | :rtype: str 6 | """ 7 | vowels = 'aeiou' 8 | for char in S: 9 | if char in vowels: 10 | S = S.replace(char, '') 11 | return S 12 | -------------------------------------------------------------------------------- /leetcode.com/python/1153_String_Transforms_Into_Another_String.py: -------------------------------------------------------------------------------- 1 | # Source: https://tinyurl.com/tvppgc4 2 | 3 | class Solution(object): 4 | def canConvert(self, str1, str2): 5 | """ 6 | :type str1: str 7 | :type str2: str 8 | :rtype: bool 9 | """ 10 | if str1 == str2: 11 | return True 12 | m = {} 13 | for i in range(len(str1)): 14 | if str1[i] not in m: 15 | m[str1[i]] = str2[i] 16 | elif m[str1[i]] != str2[i]: 17 | return False 18 | return len(set(str2)) < 26 19 | -------------------------------------------------------------------------------- /leetcode.com/python/1167_Minimum_Cost_to_Connect_Sticks.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution(object): 4 | def connectSticks(self, sticks): 5 | """ 6 | :type sticks: List[int] 7 | :rtype: int 8 | """ 9 | sticksHeap = list(sticks) 10 | heapq.heapify(sticksHeap) 11 | minCost = 0 12 | while len(sticksHeap) > 1: 13 | firstNum = heapq.heappop(sticksHeap) 14 | secondNum = heapq.heappop(sticksHeap) 15 | minCost += firstNum 16 | minCost += secondNum 17 | sumNum = firstNum + secondNum 18 | heapq.heappush(sticksHeap, sumNum) 19 | return minCost 20 | 21 | 22 | """ 23 | Example 1 24 | sticks = [2,4,3] 25 | 26 | Step 1: 27 | cost -> 2+3 = 5 28 | result -> [5,4] 29 | 30 | Step 2: 31 | cost -> 5+4 = 9 32 | result -> [9] 33 | 34 | FINAL COST =5 + 9 = 14 35 | 36 | 2,4=6 37 | >6,3=9 38 | 39 | 6+9=15 40 | """ -------------------------------------------------------------------------------- /leetcode.com/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 | result = [[0 for x in range(y + 1)] for y in range(rowIndex + 1)] 8 | memo = {} 9 | for row in range(rowIndex + 1): 10 | for column in range(row + 1): 11 | num = self.generageNumber(row, column, memo) 12 | result[row][column] = num 13 | memo[str(row) + "-" + str(column)] = num 14 | return result[rowIndex] 15 | 16 | def generageNumber(self, row, column, memo): 17 | if column == 0 or row == column: 18 | memo[str(row) + "-" + str(column)] = 1 19 | return 1 20 | key = str(row) + "-" + str(column) 21 | if key in memo.keys(): 22 | return memo[str(row) + "-" + str(column)] 23 | else: 24 | return self.generageNumber(row - 1, column - 1, memo) + self.generageNumber(row - 1, column, memo) 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/11_Container_With_Most_Water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | left, right = 0, len(height) - 1 8 | maxWaterArea = 0 9 | while left < right: 10 | minHeight = min(height[left], height[right]) 11 | maxWaterArea = max(maxWaterArea, minHeight * (right - left)) 12 | if height[left] < height[right]: 13 | left += 1 14 | else: 15 | right -= 1 16 | return maxWaterArea 17 | -------------------------------------------------------------------------------- /leetcode.com/python/1203_Sort_Items_by_Groups_Respecting_Dependencies.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.com/python/1203_Sort_Items_by_Groups_Respecting_Dependencies.py -------------------------------------------------------------------------------- /leetcode.com/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 | minPrice = float("inf") 8 | maximumProfit = 0 9 | for price in prices: 10 | if price < minPrice: 11 | minPrice = price 12 | elif price - minPrice > maximumProfit: 13 | maximumProfit = price - minPrice 14 | return maximumProfit 15 | -------------------------------------------------------------------------------- /leetcode.com/python/1229_Meeting_Scheduler.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution(object): 3 | def minAvailableDuration(self, slots1, slots2, duration): 4 | """ 5 | :type slots1: List[List[int]] 6 | :type slots2: List[List[int]] 7 | :type duration: int 8 | :rtype: List[int] 9 | """ 10 | schedules = list(slots1 + slots2) 11 | schedules = filter(lambda slot: slot[1] - slot[0] >= duration, schedules) 12 | heapq.heapify(schedules) 13 | while len(schedules) > 1: 14 | if heapq.heappop(schedules)[1] >= schedules[0][0] + duration: 15 | return [schedules[0][0], schedules[0][0] + duration] 16 | return [] -------------------------------------------------------------------------------- /leetcode.com/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 | profit = 0 8 | for i in range(len(prices) - 1): 9 | if prices[i] < prices[i + 1]: 10 | profit += (prices[i + 1] - prices[i]) 11 | return profit 12 | 13 | 14 | sol = Solution() 15 | prices = [1,2,3,4,5] 16 | profit = sol.maxProfit(prices) 17 | print("Profit: ", profit) 18 | 19 | -------------------------------------------------------------------------------- /leetcode.com/python/1231_Divide_Chocolate.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maximizeSweetness(self, sweetness, K): 3 | """ 4 | :type sweetness: List[int] 5 | :type K: int 6 | :rtype: int 7 | """ 8 | low, high = min(sweetness), sum(sweetness) 9 | while low <= high: 10 | mid = low + (high - low) // 2 11 | cuts = self.split(sweetness, mid) 12 | if cuts > K: 13 | low = mid + 1 14 | else: 15 | high = mid - 1 16 | return high 17 | 18 | def split(self, nums, upperLimit): 19 | currentPrefixSum, currentCuts = 0, 0 20 | for num in nums: 21 | if (currentPrefixSum + num) >= upperLimit: 22 | currentPrefixSum = 0 23 | currentCuts += 1 24 | else: 25 | currentPrefixSum += num 26 | return currentCuts -------------------------------------------------------------------------------- /leetcode.com/python/123_Best_Time_to_Buy_and_Sell_Stock_III.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices): 3 | """ 4 | :type prices: List[int] 5 | :rtype: int 6 | """ 7 | return self.maxProfitWithKTransaction(prices, 2) 8 | 9 | 10 | def maxProfitWithKTransaction(self, prices, k): 11 | if not prices: 12 | return 0 13 | profits = [[0 for d in prices] for t in range(k + 1)] 14 | for t in range(1, k + 1): 15 | maxThusFar = float('-inf') 16 | for d in range(1, len(prices)): 17 | maxThusFar = max(maxThusFar, profits[t - 1][d - 1] - prices[d - 1]) 18 | profits[t][d] = max(profits[t][d - 1], maxThusFar + prices[d]) 19 | return profits[-1][-1] 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode.com/python/125_Valid_Palindrome.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution(object): 4 | def isPalindrome(self, s): 5 | """ 6 | :type s: str 7 | :rtype: bool 8 | """ 9 | s = s.lower() 10 | leftIndex = 0 11 | rightIndex = len(s) - 1 12 | while leftIndex < rightIndex: 13 | if s[leftIndex].isalnum() is False: 14 | leftIndex += 1 15 | continue 16 | if s[rightIndex].isalnum() is False: 17 | rightIndex -= 1 18 | continue 19 | if s[leftIndex] != s[rightIndex]: 20 | return False 21 | leftIndex += 1 22 | rightIndex -= 1 23 | return True 24 | 25 | 26 | obj = Solution() 27 | isPalin = obj.isPalindrome("A man, a plan, a canal: Panama") 28 | print("Result: ", isPalin) 29 | 30 | -------------------------------------------------------------------------------- /leetcode.com/python/1268_Search_Suggestions_System.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | # Usig binary search 4 | class Solution(object): 5 | def suggestedProducts(self, products, searchWord): 6 | """ 7 | :type products: List[str] 8 | :type searchWord: str 9 | :rtype: List[List[str]] 10 | """ 11 | products.sort() 12 | result, prefix, startIdx = [], "", 0 13 | for char in searchWord: 14 | prefix += char 15 | startIdx = bisect.bisect_left(products, prefix, startIdx) 16 | currnetSearchRes = [] 17 | for product in products[startIdx: startIdx + 3]: 18 | if product.startswith(prefix): 19 | currnetSearchRes.append(product) 20 | result.append(currnetSearchRes) 21 | return result 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode.com/python/1272_Remove_Interval.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeInterval(self, intervals, toBeRemoved): 3 | """ 4 | :type intervals: List[List[int]] 5 | :type toBeRemoved: List[int] 6 | :rtype: List[List[int]] 7 | """ 8 | removeStart, removeEnd = toBeRemoved 9 | output = [] 10 | for start, end in intervals: 11 | if end <= removeStart or start >= removeEnd: 12 | output.append([start, end]) 13 | elif start < removeStart and end > removeEnd: 14 | output.append([start, removeStart]) 15 | output.append([removeEnd, end]) 16 | elif start < removeStart and end <= removeEnd: 17 | output.append([start, removeStart]) 18 | elif start >= removeStart and end > removeEnd: 19 | output.append([removeEnd, end]) 20 | return output 21 | -------------------------------------------------------------------------------- /leetcode.com/python/1288_Remove_Covered_Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeCoveredIntervals(self, intervals): 3 | """ 4 | :type intervals: List[List[int]] 5 | :rtype: int 6 | """ 7 | # Sort by start point. 8 | # If two intervals share the same start point 9 | # put the longer one to be the first. 10 | intervals.sort(key=lambda x: (x[0], -x[1])) 11 | count = 0 12 | 13 | prevEnd = 0 14 | for _, end in intervals: 15 | # if current interval is not covered 16 | # by the previous one 17 | if end > prevEnd: 18 | count += 1 19 | prevEnd = end 20 | return count 21 | -------------------------------------------------------------------------------- /leetcode.com/python/1312_Minimum_Insertion_Steps_to_Make_a_String_Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minInsertions(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | stringLenght = len(s) 8 | 9 | # dp[i][j] stores the length of LPS from index 'i' to index 'j' 10 | dp = [[0 for _ in range(stringLenght)] for _ in range(stringLenght)] 11 | 12 | # every sequence with one element is a palindrome of length 1 13 | for i in range(stringLenght): 14 | dp[i][i] = 1 15 | 16 | for startIdx in range(stringLenght - 1, -1, -1): 17 | for endIdx in range(startIdx + 1, stringLenght): 18 | if s[startIdx] == s[endIdx]: 19 | dp[startIdx][endIdx] = dp[startIdx + 1][endIdx - 1] + 2 20 | else: 21 | dp[startIdx][endIdx] = max(dp[startIdx + 1][endIdx], dp[startIdx][endIdx -1]) 22 | 23 | numberOfInsersion = stringLenght - dp[0][-1] 24 | return numberOfInsersion 25 | -------------------------------------------------------------------------------- /leetcode.com/python/1358_Number_of_Substrings_Containing_All_Three_Characters.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution(object): 3 | def numberOfSubstrings(self, s): 4 | """ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | left, right = 0, 0 9 | subStringCount = 0 10 | couter = {c: 0 for c in 'abc'} 11 | while right < len(s): 12 | couter[s[right]] += 1 13 | while all(couter.values()): 14 | couter[s[left]] -= 1 15 | left += 1 16 | subStringCount += left 17 | right += 1 18 | return subStringCount -------------------------------------------------------------------------------- /leetcode.com/python/136_Single_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def singleNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | uniqueNum = 0 8 | for num in nums: 9 | uniqueNum ^= num 10 | return uniqueNum 11 | 12 | 13 | 14 | 15 | sol = Solution() 16 | input = [4,1,2,1,2] 17 | output = sol.singleNumber(input) 18 | print('Res: ',output) -------------------------------------------------------------------------------- /leetcode.com/python/137_Single_Number_II.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution(object): 3 | def singleNumber(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | seenOnce, seenTwice = 0, 0 9 | for num in nums: 10 | # first appearance: 11 | # add num to seen_once 12 | # don't add to seen_twice because of presence in seen_once 13 | 14 | # second appearance: 15 | # remove num from seen_once 16 | # add num to seen_twice 17 | 18 | # third appearance: 19 | # don't add to seen_once because of presence in seen_twice 20 | # remove num from seen_twice 21 | seenOnce = ~seenTwice & (seenOnce ^ num) 22 | seenTwice = ~seenOnce & (seenTwice ^ num) 23 | return seenOnce 24 | 25 | 26 | 27 | 28 | sol = Solution() 29 | input = [2,2,3,2] 30 | output = sol.singleNumber(input) 31 | print('Res: ', output) 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /leetcode.com/python/13_Roman_to_Integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def romanToInt(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | romanDict = {'I': 1, 8 | 'V': 5, 9 | 'X': 10, 10 | 'L': 50, 11 | 'C': 100, 12 | 'D': 500, 13 | 'M': 1000 14 | } 15 | intNum = 0 16 | if len(s) == 1: 17 | return romanDict[s] 18 | for i in range(len(s) - 1): 19 | v1 = romanDict[s[i]] 20 | v2 = romanDict[s[i + 1]] 21 | if romanDict[s[i]] >= romanDict[s[i + 1]]: 22 | intNum = romanDict[s[i]] + intNum 23 | else: 24 | intNum = intNum - romanDict[s[i]] 25 | return intNum + romanDict[s[-1]] 26 | 27 | 28 | sol = Solution() 29 | input = "MCMXCIV" 30 | value = sol.romanToInt(input) 31 | print("Value: ", value) 32 | 33 | 34 | -------------------------------------------------------------------------------- /leetcode.com/python/141_Linked_List_Cycle.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 hasCycle(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: bool 12 | """ 13 | fastPtr, slowPtr = head, head 14 | while fastPtr is not None and fastPtr.next is not None: 15 | fastPtr = fastPtr.next.next 16 | slowPtr = slowPtr.next 17 | if fastPtr == slowPtr: 18 | return True 19 | return False -------------------------------------------------------------------------------- /leetcode.com/python/142_Linked_List_Cycle_II.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 detectCycle(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | slow = fast = head 14 | while fast and fast.next: 15 | slow = slow.next 16 | fast = fast.next.next 17 | if slow == fast: 18 | break 19 | else: 20 | return None 21 | while head != slow: 22 | slow = slow.next 23 | head = head.next 24 | return head -------------------------------------------------------------------------------- /leetcode.com/python/145_Binary_Tree_Postorder_Traversal.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 postorderTraversal(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: List[int] 13 | """ 14 | result = [] 15 | return self.postorderTraversalHelper(root, result) 16 | 17 | def postorderTraversalHelper(self, root, result): 18 | if root: 19 | self.postorderTraversalHelper(root.left, result) 20 | self.postorderTraversalHelper(root.right, result) 21 | result.append(root.val) 22 | return result -------------------------------------------------------------------------------- /leetcode.com/python/1477_Find_Two_Non_overlapping_Sub_arrays_Each_With_Target_Sum.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution(object): 3 | def minSumOfLengths(self, arr, target): 4 | dp = defaultdict(lambda: float("inf")) 5 | left, currentWindowSum, result = 0, 0, float("inf") 6 | for right in range(len(arr)): 7 | currentWindowSum += arr[right] 8 | while currentWindowSum > target: 9 | currentWindowSum -= arr[left] 10 | left += 1 11 | if currentWindowSum == target: 12 | targetArrLen = right - left + 1 13 | dp[right] = targetArrLen 14 | result = min(result, dp[left - 1] + dp[right]) 15 | dp[right] = min(dp[right], dp[right - 1]) 16 | return result if result != float("inf") else -1 -------------------------------------------------------------------------------- /leetcode.com/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 | minProd, maxProd, bestSoFar = 1, 1, nums[0] 8 | for i in range(len(nums)): 9 | currentNum = nums[i] 10 | if currentNum < 0: 11 | minProd, maxProd = maxProd, minProd 12 | maxProd = max(maxProd*currentNum, currentNum) 13 | minProd = min(minProd*currentNum, currentNum) 14 | bestSoFar = max(bestSoFar, maxProd) 15 | return bestSoFar 16 | -------------------------------------------------------------------------------- /leetcode.com/python/155_Min_Stack.py: -------------------------------------------------------------------------------- 1 | class MinStack(object): 2 | 3 | def __init__(self): 4 | self.main = [] 5 | self.mins = [] 6 | 7 | def push(self, x): 8 | self.main.append(x) 9 | if not self.mins or x <= self.mins[-1]: 10 | self.mins.append(x) 11 | 12 | def pop(self): 13 | item = self.main.pop() 14 | if item == self.mins[-1]: 15 | self.mins.pop() 16 | 17 | def top(self): 18 | return self.main[-1] 19 | 20 | def getMin(self): 21 | return self.mins[-1] 22 | 23 | # Your MinStack object will be instantiated and called as such: 24 | # obj = MinStack() 25 | # obj.push(x) 26 | # obj.pop() 27 | # param_3 = obj.top() 28 | # param_4 = obj.getMin() -------------------------------------------------------------------------------- /leetcode.com/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 | nums.insert(0, lower - 1) 10 | nums.append(upper + 1) 11 | res = [] 12 | i = 0 13 | while i < len(nums) - 1: 14 | leftRage, rightRange = nums[i], nums[i + 1] 15 | if leftRage != (rightRange - 1): 16 | if rightRange - leftRage == 2: 17 | res.append(str(rightRange - 1)) 18 | elif rightRange - leftRage > 2: 19 | res.append("{}->{}".format(leftRage + 1, rightRange - 1)) 20 | i += 1 21 | return res -------------------------------------------------------------------------------- /leetcode.com/python/166_Fraction_to_Recurring_Decimal.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fractionToDecimal(self, numerator, denominator): 3 | num, den = numerator, denominator 4 | if not den: # denominator is 0 5 | return 6 | if not num: # numerator is 0 7 | return "0" 8 | res = [] 9 | if (num < 0) ^ (den < 0): 10 | res.append("-") # add the sign 11 | num, den = abs(num), abs(den) 12 | res.append(str(num//den)) 13 | rmd = num % den 14 | if not rmd: 15 | return "".join(res) # only has integral part 16 | res.append(".") # has frational part 17 | dic = {} 18 | while rmd: 19 | if rmd in dic: # the remainder recurs 20 | res.insert(dic[rmd], "(") 21 | res.append(")") 22 | break 23 | dic[rmd] = len(res) 24 | div, rmd = divmod(rmd*10, den) 25 | res.append(str(div)) 26 | return "".join(res) 27 | -------------------------------------------------------------------------------- /leetcode.com/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 | leftIdx, rightIdx = 0, len(numbers) - 1 9 | while leftIdx < rightIdx: 10 | twoSum = numbers[leftIdx] + numbers[rightIdx] 11 | if twoSum == target: 12 | break 13 | elif twoSum < target: 14 | leftIdx += 1 15 | else: 16 | rightIdx -= 1 17 | return [leftIdx + 1, rightIdx + 1] 18 | 19 | -------------------------------------------------------------------------------- /leetcode.com/python/187_Repeated_DNA_Sequences.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.com/python/187_Repeated_DNA_Sequences.py -------------------------------------------------------------------------------- /leetcode.com/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 | weight = 0 8 | while n: 9 | n &= n - 1 10 | weight += 1 11 | return weight 12 | -------------------------------------------------------------------------------- /leetcode.com/python/19_Remove_Nth_Node_From_End_of_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 removeNthFromEnd(self, head, n): 9 | """ 10 | :type head: ListNode 11 | :type n: int 12 | :rtype: ListNode 13 | """ 14 | dummyNode = ListNode(0) 15 | dummyNode.next = head 16 | fastNode, slowNode = dummyNode, dummyNode 17 | for _ in range(n): 18 | fastNode = fastNode.next 19 | while fastNode and fastNode.next: 20 | fastNode = fastNode.next 21 | slowNode = slowNode.next 22 | slowNode.next = slowNode.next.next 23 | return dummyNode.next 24 | 25 | -------------------------------------------------------------------------------- /leetcode.com/python/1_Two_Sum.py: -------------------------------------------------------------------------------- 1 | # https://www.algoexpert.io/questions/Two%20Number%20Sum 2 | 3 | class Solution(object): 4 | def twoSum(self, nums, target): 5 | indices = [] 6 | numIdxDict = {} 7 | for idx, num in enumerate(nums): 8 | numIdxDict[num] = idx 9 | for idx, num in enumerate(nums): 10 | expectedNum = target - num 11 | if expectedNum in numIdxDict: 12 | if idx != numIdxDict[expectedNum]: 13 | indices.extend([idx, numIdxDict[expectedNum]]) 14 | break 15 | return sorted(indices) 16 | 17 | 18 | sol = Solution() 19 | # nums = [2, 7, 11, 15] 20 | # target = 9 21 | nums = [3,2,4] 22 | target = 6 23 | out = sol.twoSum(nums, target) 24 | print("Res: ", out) 25 | -------------------------------------------------------------------------------- /leetcode.com/python/202_Happy_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isHappy(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | slowRuner, fastRunner = n, self.getNextNumer(n) 8 | while fastRunner != 1 and fastRunner != slowRuner: 9 | fastRunner = self.getNextNumer(self.getNextNumer(fastRunner)) 10 | slowRuner = self.getNextNumer(slowRuner) 11 | return fastRunner == 1 12 | 13 | def getNextNumer(self, num): 14 | totalSum = 0 15 | while num > 0: 16 | num, digit = divmod(num, 10) 17 | totalSum += (digit ** 2) 18 | return totalSum 19 | -------------------------------------------------------------------------------- /leetcode.com/python/206_Reverse_Linked_List.py: -------------------------------------------------------------------------------- 1 | # Explanations: 2 | # https://www.youtube.com/watch?v=sYcOK51hl-A 3 | # https://www.youtube.com/watch?v=O0By4Zq0OFc 4 | 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.next = None 11 | 12 | class Solution(object): 13 | def reverseList(self, head): 14 | """ 15 | :type head: ListNode 16 | :rtype: ListNode 17 | """ 18 | current = head 19 | prev = None 20 | while current is not None: 21 | next = current.next 22 | current.next = prev 23 | prev = current 24 | current = next 25 | head = prev 26 | return head 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /leetcode.com/python/209_Minimum_Size_Subarray_Sum.py: -------------------------------------------------------------------------------- 1 | # Approach 1: Sliding window. O(n) 2 | class Solution(object): 3 | def minSubArrayLen(self, s, nums): 4 | """ 5 | :type s: int 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | left, right, length = 0, 0, float("inf") 10 | sLen = len(nums) 11 | currentSum = 0 12 | while right < sLen: 13 | currentSum += nums[right] 14 | right += 1 15 | while currentSum >= s: 16 | length = min(length, right - left) 17 | currentSum -= nums[left] 18 | left += 1 19 | return length if length != float("inf") else 0 20 | 21 | -------------------------------------------------------------------------------- /leetcode.com/python/20_Valid_Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValid(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | parenthesesStack = [] 8 | parenthesesDictionary = {')': '(', '}': '{', ']': '['} 9 | for char in s: 10 | if char in parenthesesDictionary.values(): 11 | parenthesesStack.append(char) 12 | continue 13 | if char in parenthesesDictionary.keys(): 14 | if len(parenthesesStack) != 0: 15 | openBracket = parenthesesStack.pop() 16 | else: 17 | return False 18 | if openBracket is not None and parenthesesDictionary[char] == openBracket: 19 | continue 20 | else: 21 | return False 22 | if len(parenthesesStack) != 0: 23 | return False 24 | return True 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /leetcode.com/python/22_Generate_Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generateParenthesis(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[str] 6 | """ 7 | allCombinations = [] 8 | self.backtrack("", 0, 0, n, allCombinations) 9 | return allCombinations 10 | 11 | 12 | def backtrack(self, currentCombination, openCount, closeCount, n, allCombinations): 13 | if len(currentCombination) == n*2: 14 | allCombinations.append(currentCombination) 15 | return 16 | if openCount < n: 17 | self.backtrack(currentCombination + "(", openCount + 1, closeCount, n, allCombinations) 18 | if closeCount < openCount: 19 | self.backtrack(currentCombination + ")", openCount, closeCount + 1, n, allCombinations) 20 | 21 | 22 | sol = Solution() 23 | input = 3 24 | output = sol.generateParenthesis(input) 25 | print('Res: ', output) -------------------------------------------------------------------------------- /leetcode.com/python/231_Power_of_Two.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | 3 | # Solution 1 4 | def isPowerOfTwo(self, n): 5 | """ 6 | :type n: int 7 | :rtype: bool 8 | """ 9 | if n == 0: 10 | return False 11 | if (n & (~n + 1)) == n: # ~n + 1 = -n 12 | return True 13 | else: 14 | return False 15 | 16 | 17 | -------------------------------------------------------------------------------- /leetcode.com/python/236_Lowest_Common_Ancestor_of_a_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 | # https://tinyurl.com/tu7jdzq 9 | class Solution(object): 10 | def lowestCommonAncestor(self, root, p, q): 11 | """ 12 | :type root: TreeNode 13 | :type p: TreeNode 14 | :type q: TreeNode 15 | :rtype: TreeNode 16 | """ 17 | if not root: 18 | return None 19 | if p == root or q == root: 20 | return root 21 | left = self.lowestCommonAncestor(root.left, p, q) 22 | right = self.lowestCommonAncestor(root.right, p, q) 23 | if left and right: 24 | return root 25 | if not left: 26 | return right 27 | if not right: 28 | return left 29 | 30 | 31 | -------------------------------------------------------------------------------- /leetcode.com/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 15 | -------------------------------------------------------------------------------- /leetcode.com/python/242_Valid_Anagram.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution(object): 3 | def isAnagram(self, s, t): 4 | """ 5 | :type s: str 6 | :type t: str 7 | :rtype: bool 8 | """ 9 | sCounter = Counter(s) 10 | tCounter = Counter(t) 11 | return sCounter == tCounter 12 | 13 | -------------------------------------------------------------------------------- /leetcode.com/python/246_Strobogrammatic_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isStrobogrammatic(self, num): 3 | """ 4 | :type num: str 5 | :rtype: bool 6 | """ 7 | nsg = ["2", "3", "4", "5", "7"] 8 | sg = {"0": "0", "1": "1", "6": "9", "8": "8", "9": "6"} 9 | newNum = "" 10 | for n in num: 11 | if n in nsg: 12 | return False 13 | else: 14 | newNum += sg[n] 15 | newNum = newNum[::-1] 16 | return num == newNum 17 | -------------------------------------------------------------------------------- /leetcode.com/python/252_Meeting_Rooms.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canAttendMeetings(self, intervals): 3 | """ 4 | :type intervals: List[List[int]] 5 | :rtype: bool 6 | """ 7 | start, end = 0, 1 8 | intervals.sort(key = lambda x: x[end]) 9 | for idx in range(1, len(intervals)): 10 | if intervals[idx - 1][end] > intervals[idx][start]: 11 | return False 12 | return True -------------------------------------------------------------------------------- /leetcode.com/python/26_Remove_Duplicates_from_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) < 2: 8 | return len(nums) 9 | left, right = 0, 1 10 | while left < right and right < len(nums): 11 | if nums[left] == nums[right]: 12 | nums.pop(left) 13 | else: 14 | left += 1 15 | right += 1 16 | return len(nums) 17 | 18 | -------------------------------------------------------------------------------- /leetcode.com/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 = 0, n 13 | while left < right: 14 | mid = (left + right) // 2 15 | isBad = isBadVersion(mid) 16 | if isBad: 17 | right = mid 18 | else: 19 | left = mid + 1 20 | return left 21 | -------------------------------------------------------------------------------- /leetcode.com/python/279_Perfect_Squares.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.com/python/279_Perfect_Squares.py -------------------------------------------------------------------------------- /leetcode.com/python/280_Wiggle_Sort.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wiggleSort(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: None Do not return anything, modify nums in-place instead. 6 | """ 7 | nLen = len(nums) - 1 8 | nums.sort() 9 | fidx = nLen // 2 10 | sidx = nLen // 2 + 1 11 | 12 | swapIdx = 0 13 | while swapIdx < nLen - 1: 14 | nums[swapIdx], nums[fidx] = nums[fidx], nums[swapIdx] 15 | swapIdx += 1 16 | fidx += 1 17 | 18 | nums[swapIdx], nums[sidx] = nums[sidx], nums[swapIdx] 19 | swapIdx += 1 20 | sidx += 1 21 | -------------------------------------------------------------------------------- /leetcode.com/python/285_Inorder_Successor_in_BST.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 inorderSuccessor(self, root, p): 10 | """ 11 | :type root: TreeNode 12 | :type p: TreeNode 13 | :rtype: TreeNode 14 | """ 15 | -------------------------------------------------------------------------------- /leetcode.com/python/287_Find_the_Duplicate_Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | 3 | # Cyclic Sort approach, which actually modifies the input array 4 | def findDuplicate(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | currentIndex, length = 0, len(nums) 10 | while currentIndex < length: 11 | expectedCurrentNum = currentIndex + 1 12 | actualCurrentNum = nums[currentIndex] 13 | if actualCurrentNum != expectedCurrentNum: 14 | finalIndexOfActualCurrentNum = nums[currentIndex] - 1 15 | if nums[finalIndexOfActualCurrentNum] != nums[currentIndex]: 16 | nums[currentIndex], nums[finalIndexOfActualCurrentNum] = nums[finalIndexOfActualCurrentNum], nums[currentIndex] 17 | else: # we have found the duplicate 18 | return nums[finalIndexOfActualCurrentNum] 19 | else: 20 | currentIndex += 1 21 | return -1 22 | -------------------------------------------------------------------------------- /leetcode.com/python/299_Bulls_and_Cows.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution(object): 3 | def getHint(self, secret, guess): 4 | """ 5 | :type secret: str 6 | :type guess: str 7 | :rtype: str 8 | """ 9 | secretCounter = Counter(secret) 10 | guessCounter = Counter(guess) 11 | bulls, cows = 0, 0 12 | for guessDigit in guessCounter.keys(): # First get all the 'cows'. If you have cows then you may or may not have the bulls. So later you can convert the cows into bulls 13 | if secretCounter[guessDigit] > 0: 14 | cows += min(guessCounter[guessDigit], secretCounter[guessDigit]) 15 | if cows > 0: 16 | for secretDigit, guessDigit in zip(secret, guess): # Convert the cows into bulls 17 | if secretDigit == guessDigit: 18 | cows -= 1 19 | bulls += 1 20 | return '%sA%sB' % (bulls, cows) 21 | -------------------------------------------------------------------------------- /leetcode.com/python/300_Longest_Increasing_Subsequence.py: -------------------------------------------------------------------------------- 1 | 2 | # Approach 1: Typical DP 3 | class Solution(object): 4 | def lengthOfLIS(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | if len(nums) <= 0: 10 | return 0 11 | length = [1 for _ in nums] 12 | for i in range(len(nums)): 13 | currentNum = nums[i] 14 | for j in range(0, i): 15 | otherNum = nums[j] 16 | if otherNum < currentNum and length[j] + 1 >= length[i]: 17 | length[i] = length[j] + 1 18 | return max(length) 19 | 20 | 21 | 22 | # Approach 2: DP with Binary Search 23 | class Solution(object): 24 | def lengthOfLIS(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | 30 | 31 | 32 | 33 | sol = Solution() 34 | nums = [10,9,2,5,3,7,101,18] 35 | ourput = sol.lengthOfLIS(nums) 36 | print('Res: ', ourput) 37 | 38 | -------------------------------------------------------------------------------- /leetcode.com/python/303_Range_Sum_Query-Immutable.py: -------------------------------------------------------------------------------- 1 | class NumArray(object): 2 | 3 | def __init__(self, nums): 4 | """ 5 | :type nums: List[int] 6 | """ 7 | self.prefixSum = [0] * (len(nums) + 1) 8 | currentSum = 0 9 | for idx, num in enumerate(nums): 10 | currentSum += num 11 | self.prefixSum[idx + 1] = currentSum 12 | 13 | 14 | def sumRange(self, i, j): 15 | """ 16 | :type i: int 17 | :type j: int 18 | :rtype: int 19 | """ 20 | rangeSum = self.prefixSum[j + 1] - self.prefixSum[i] 21 | return rangeSum 22 | 23 | # Your NumArray object will be instantiated and called as such: 24 | nums = [-2,0,3,-5,2,-1] 25 | obj = NumArray(nums) 26 | param_1 = obj.sumRange(0,2) 27 | param_2 = obj.sumRange(2,5) 28 | param_3 = obj.sumRange(0,5) 29 | param_4 = obj.sumRange(4,3) 30 | print("Res: ", param_4) -------------------------------------------------------------------------------- /leetcode.com/python/319_Bulb_Switcher.py: -------------------------------------------------------------------------------- 1 | # My Initial solution. Got TLE offcourse 2 | class Solution(object): 3 | def bulbSwitch(self, n): 4 | """ 5 | :type n: int 6 | :rtype: int 7 | """ 8 | bulbs = [False] * n 9 | for i in range(1, n + 1): 10 | currentBuldIdx = 0 11 | while currentBuldIdx < n: 12 | currentBuldIdx += i 13 | if currentBuldIdx - 1 < n: 14 | bulbs[currentBuldIdx - 1] = not bulbs[currentBuldIdx - 1] 15 | else: 16 | break 17 | 18 | count = 0 19 | for bulb in bulbs: 20 | if bulb: 21 | count += 1 22 | return count 23 | 24 | 25 | """ 26 | [0, 0, 0] 27 | n**2 28 | """ 29 | 30 | 31 | 32 | 33 | class Solution(object): 34 | def bulbSwitch(self, n): 35 | """ 36 | :type n: int 37 | :rtype: int 38 | """ 39 | return int(math.sqrt(n)) -------------------------------------------------------------------------------- /leetcode.com/python/329_Longest_Increasing_Path_in_a_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestIncreasingPath(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: int 6 | """ 7 | -------------------------------------------------------------------------------- /leetcode.com/python/332_Reconstruct_Itinerary.py: -------------------------------------------------------------------------------- 1 | # Source: https://tinyurl.com/tsy24pl 2 | from collections import defaultdict 3 | class Solution(object): 4 | def findItinerary(self, tickets): 5 | """ 6 | :type tickets: List[List[str]] 7 | :rtype: List[str] 8 | """ 9 | graph = defaultdict(list) 10 | for source, destination in tickets: 11 | graph[source].append(destination) 12 | for source in graph.keys(): 13 | graph[source].sort(reverse=True) 14 | stack = ["JFK",] 15 | result = [] 16 | while stack: 17 | node = stack[-1] 18 | if node in graph and len(graph[node]) > 0: 19 | stack.append(graph[node].pop()) 20 | else: 21 | result.append(stack.pop()) 22 | return result[::-1] 23 | -------------------------------------------------------------------------------- /leetcode.com/python/337_House_Robber_III.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 | 9 | # Post-order DFS traversal 10 | class Solution(object): 11 | def rob(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: int 15 | """ 16 | return max(self.robHelper(root)) 17 | 18 | def robHelper(self, root): 19 | if not root: 20 | return (0, 0) 21 | leftHouseRobbery = self.robHelper(root.left) 22 | rightHouseRobbery = self.robHelper(root.right) 23 | robCurrentHouseNow = root.val + leftHouseRobbery[1] + rightHouseRobbery[1] 24 | robCurrentLaterLater = max(leftHouseRobbery) + max(rightHouseRobbery) 25 | return (robCurrentHouseNow, robCurrentLaterLater) 26 | -------------------------------------------------------------------------------- /leetcode.com/python/343_Integer_Break.py: -------------------------------------------------------------------------------- 1 | 2 | # Sourcce: https://tinyurl.com/smsj265 3 | class Solution(object): 4 | def integerBreak(self, n): 5 | """ 6 | :type n: int 7 | :rtype: int 8 | """ 9 | dp = [1] * (n + 1) 10 | dp[0] = None 11 | for m in range(1, n + 1): 12 | startNum = 1 13 | endum = m - startNum 14 | maxProd = 0 15 | while startNum <= endum: 16 | maxProd = max(maxProd, max(startNum, dp[startNum]) * max(endum, dp[endum])) 17 | startNum += 1 18 | endum -= 1 19 | dp[m] = maxProd 20 | return dp[-1] 21 | 22 | -------------------------------------------------------------------------------- /leetcode.com/python/344_Reverse_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseString(self, s): 3 | """ 4 | :type s: List[str] 5 | :rtype: None Do not return anything, modify s in-place instead. 6 | """ 7 | self.reverseStringHelper(0, len(s) - 1, s) 8 | 9 | def reverseStringHelper(self, start, end, newS): 10 | if start >= end: 11 | return 12 | newS[start], newS[end] = newS[end], newS[start] 13 | self.reverseStringHelper(start + 1, end - 1, newS) 14 | 15 | -------------------------------------------------------------------------------- /leetcode.com/python/346_Moving_Average_from_Data_Stream.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class MovingAverage(object): 4 | 5 | def __init__(self, size): 6 | """ 7 | Initialize your data structure here. 8 | :type size: int 9 | """ 10 | self.size = size 11 | self.nums = deque() 12 | 13 | def next(self, val): 14 | """ 15 | :type val: int 16 | :rtype: float 17 | """ 18 | if len(self.nums) >= self.size: 19 | self.nums.popleft() 20 | self.nums.append(val) 21 | return float(float(sum(self.nums)) / float(len(self.nums))) 22 | 23 | # Your MovingAverage object will be instantiated and called as such: 24 | # obj = MovingAverage(size) 25 | # param_1 = obj.next(val) 26 | 27 | 28 | -------------------------------------------------------------------------------- /leetcode.com/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 | set1 = set(nums1) 9 | set2 = set(nums2) 10 | 11 | # # Using manual Set Intersection 12 | # if len(set1) < len(set2): 13 | # return self.setIntersection(set1, set2) 14 | # else: 15 | # return self.setIntersection(set2, set1) 16 | 17 | # Using Build-in Set Intersection 18 | return list(set1 & set2) 19 | 20 | def setIntersection(self, set1, set2): 21 | return [x for x in set1 if x in set2] 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode.com/python/350_Intersection_of_Two_Arrays_II.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution(object): 5 | def intersect(self, nums1, nums2): 6 | """ 7 | :type nums1: List[int] 8 | :type nums2: List[int] 9 | :rtype: List[int] 10 | """ 11 | count1 = Counter(nums1) 12 | count2 = Counter(nums2) 13 | result = [] 14 | 15 | for key in count1: 16 | if key in count2: 17 | minFreq = min(count1[key], count2[key]) 18 | for i in range(minFreq): 19 | result.append(key) 20 | 21 | return result -------------------------------------------------------------------------------- /leetcode.com/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 | 7 | class Solution(object): 8 | def guessNumber(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | low = 1 14 | high = n 15 | while low <= high: 16 | mid = (low + high) // 2 17 | res = guess(mid) 18 | if res == 0: 19 | return mid 20 | elif res == -1: 21 | high = mid - 1 22 | else: 23 | low = mid + 1 24 | -------------------------------------------------------------------------------- /leetcode.com/python/375_Guess_Number_Higher_or_Lower_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def dfs(self, start, end, record): 3 | if start >= end: 4 | return 0 5 | 6 | if start + 1 == end: 7 | return start 8 | 9 | if record[start][end] is None: 10 | pays = [] 11 | for i in range(start, end + 1): 12 | prevPay = self.dfs(start, i - 1, record) 13 | nextPay = self.dfs(i + 1, end, record) 14 | currPay = i 15 | totlPay = currPay + max(prevPay, nextPay) 16 | pays.append(totlPay) 17 | 18 | record[start][end] = min(pays) 19 | 20 | return record[start][end] 21 | 22 | def getMoneyAmount(self, n): 23 | record = [[None] * (n + 1) for _ in range(n + 1)] 24 | return self.dfs(1, n, record) -------------------------------------------------------------------------------- /leetcode.com/python/378_Kth_Smallest_Element_in_a_Sorted_Matrix.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution(object): 4 | def kthSmallest(self, matrix, k): 5 | """ 6 | :type matrix: List[List[int]] 7 | :type k: int 8 | :rtype: int 9 | """ 10 | minHeap = [] 11 | 12 | # put the 1st element of each row in the min heap 13 | # we don't need to push more than 'k' elements in the heap 14 | for rowIdx in range(min(k, len(matrix))): 15 | heapq.heappush(minHeap, (matrix[rowIdx][0], 0, rowIdx)) 16 | 17 | currentNumber, currentNumerCount = 0, 0 18 | while minHeap: 19 | currentNumber, columnIdx, rowIdx = heapq.heappop(minHeap) 20 | currentNumerCount += 1 21 | if currentNumerCount == k: 22 | break 23 | else: 24 | if len(matrix[rowIdx]) > columnIdx + 1: 25 | heapq.heappush(minHeap, (matrix[rowIdx][columnIdx + 1], columnIdx + 1, rowIdx)) 26 | return currentNumber 27 | 28 | 29 | -------------------------------------------------------------------------------- /leetcode.com/python/388_Longest_Absolute_File_Path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthLongestPath(self, input): 3 | maxPath = 0 4 | paths = [0] 5 | for subDir in input.splitlines(): 6 | 7 | # getting the depth level of the current subpath 8 | level = subDir.count('\t') 9 | 10 | # increasing the size of the array of the parents subpaths, if needed 11 | if level >= len(paths): 12 | paths += [None] 13 | 14 | # updating the length of the current depth level 15 | if level > 0: 16 | paths[level] = paths[level - 1] + (len(subDir) - level) + 1 17 | else: 18 | paths[level] = len(subDir) 19 | 20 | # updating the maximum length 21 | if '.' in subDir: 22 | maxPath = max(maxPath, paths[level]) 23 | 24 | return maxPath -------------------------------------------------------------------------------- /leetcode.com/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 | ans = 0 9 | for char in s + t: 10 | ans ^= char 11 | return char(ans) 12 | 13 | 14 | 15 | 16 | sol = Solution() 17 | out = sol.findTheDifference("abcd", "abcde") 18 | print('Res: ',out) -------------------------------------------------------------------------------- /leetcode.com/python/398_Random_Pick_Index.py: -------------------------------------------------------------------------------- 1 | # https://tinyurl.com/yafb3esf 2 | class Solution(object): 3 | 4 | def __init__(self, nums): 5 | self.nums = nums 6 | 7 | def pick(self, target): 8 | res = None 9 | count = 0 10 | for i, x in enumerate(self.nums): 11 | if x == target: 12 | count += 1 13 | chance = random.randint(1, count) 14 | if chance == count: 15 | res = i 16 | return res 17 | 18 | # Your Solution object will be instantiated and called as such: 19 | # obj = Solution(nums) 20 | # param_1 = obj.pick(target) -------------------------------------------------------------------------------- /leetcode.com/python/406_Queue_Reconstruction_by_Height.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reconstructQueue(self, people): 3 | """ 4 | :type people: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | people.sort(key = lambda x: (-x[0], x[1])) 8 | output = [] 9 | for i in people: 10 | output.insert(i[1], i) 11 | return output 12 | 13 | 14 | 15 | sol = Solution() 16 | input = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 17 | output = sol.reconstructQueue(input) 18 | print("Res: ", output) 19 | -------------------------------------------------------------------------------- /leetcode.com/python/41_First_Missing_Positive.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def firstMissingPositive(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | currentIndex, length = 0, len(nums) 8 | while currentIndex < length: 9 | currentNum = nums[currentIndex] 10 | expectedCurrentIndex = currentNum - 1 11 | if currentNum > 0 and currentNum <= length and currentNum != nums[expectedCurrentIndex]: 12 | nums[currentIndex], nums[expectedCurrentIndex] = nums[expectedCurrentIndex], nums[currentIndex] 13 | else: 14 | currentIndex += 1 15 | for index in range(length): 16 | expectedCurrentNum = index + 1 17 | actualCurrentNum = nums[index] 18 | if actualCurrentNum != expectedCurrentNum: 19 | return expectedCurrentNum 20 | return length + 1 -------------------------------------------------------------------------------- /leetcode.com/python/429_N-ary_Tree_Level_Order_Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node(object): 4 | def __init__(self, val, children): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | 10 | class Solution(object): 11 | def levelOrder(self, root): 12 | """ 13 | :type root: Node 14 | :rtype: List[List[int]] 15 | """ 16 | result, queue = [], [root] if root else [] 17 | while queue: 18 | levelNode = [] 19 | for node in queue: # add value of every node in queue 20 | levelNode.append(node.val) 21 | result.append(levelNode) 22 | children = [] 23 | for node in queue: # for every node in queue add its children 24 | for child in node.children: 25 | children.append(child) 26 | queue = children # replaces the queue. 27 | 28 | return result 29 | -------------------------------------------------------------------------------- /leetcode.com/python/42_Trapping_Rain_Water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def trap(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | maxes = [0 for _ in height] # Initially this will store leftMax values 8 | leftMax = 0 9 | for i in range(len(height)): 10 | maxes[i] = leftMax 11 | leftMax = max(leftMax, height[i]) 12 | rightMax = 0 13 | for i in reversed(range(len(height))): 14 | minHeight = min(maxes[i], rightMax) 15 | if height[i] < minHeight: 16 | maxes[i] = minHeight - height[i] 17 | else: 18 | maxes[i] = 0 19 | rightMax = max(rightMax, height[i]) 20 | return sum(maxes) 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode.com/python/435_Non-overlapping_Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def eraseOverlapIntervals(self, intervals): 3 | """ 4 | :type intervals: List[List[int]] 5 | :rtype: int 6 | """ 7 | previousEnd = float('-inf') 8 | erased = 0 9 | for interval in sorted(intervals, key= lambda x: x[1]): 10 | currentStart = interval[0] 11 | if currentStart >= previousEnd: 12 | previousEnd = interval[1] 13 | else: 14 | erased += 1 15 | return erased 16 | 17 | 18 | 19 | sol = Solution() 20 | intervals = [[1,2],[1,2],[1,2]] 21 | out = sol.eraseOverlapIntervals(intervals) 22 | print("Res: ", out) 23 | -------------------------------------------------------------------------------- /leetcode.com/python/442_Find_All_Duplicates_in_an_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDuplicates(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | currentIndex, length = 0, len(nums) 8 | duplicateNums = [] 9 | while currentIndex < length: 10 | currentNum = nums[currentIndex] 11 | expectedCurrentIndex = currentNum - 1 12 | if nums[currentIndex] != nums[expectedCurrentIndex]: 13 | nums[currentIndex], nums[expectedCurrentIndex] = nums[expectedCurrentIndex], nums[currentIndex] 14 | else: 15 | currentIndex += 1 16 | for index in range(length): 17 | expectedCurrentNum = index + 1 18 | actualCurrentNum = nums[index] 19 | if actualCurrentNum != expectedCurrentNum: 20 | duplicateNums.append(nums[index]) 21 | return duplicateNums -------------------------------------------------------------------------------- /leetcode.com/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 | currentIndex, length = 0, len(nums) 8 | missingNumbers = [] 9 | while currentIndex < length: 10 | finalIndex = nums[currentIndex] - 1 11 | if nums[currentIndex] != nums[finalIndex]: 12 | nums[currentIndex], nums[finalIndex] = nums[finalIndex], nums[currentIndex] 13 | else: 14 | currentIndex += 1 15 | for index in range(length): # find the first number missing from its index, that will be our required number 16 | if nums[index] != index + 1: 17 | missingNumbers.append(index + 1) 18 | return missingNumbers -------------------------------------------------------------------------------- /leetcode.com/python/451_Sort_Characters_By_Frequency.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | import heapq 3 | 4 | class Solution(object): 5 | def frequencySort(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | charFrequencyCounter = Counter(s) # find the frequency of each character 11 | maxHeap = [] 12 | for char, frequency in charFrequencyCounter.items(): # add all characters to the max heap 13 | heapq.heappush(maxHeap, (-frequency, char)) 14 | 15 | sortedString = [] 16 | while maxHeap: # build a string, appending the most occurring characters first 17 | frequency, char = heapq.heappop(maxHeap) 18 | for _ in range(-frequency): 19 | sortedString.append(char) 20 | 21 | return "".join(sortedString) 22 | 23 | -------------------------------------------------------------------------------- /leetcode.com/python/459_Repeated_Substring_Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def repeatedSubstringPattern(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | if not s: 8 | return False 9 | ss = s + s 10 | ss = ss[1:-1] 11 | return ss.find(s) != -1 12 | 13 | 14 | 15 | # My solution duting Mock contest 16 | from collections import Counter 17 | class Solution(object): 18 | def repeatedSubstringPattern(self, s): 19 | """ 20 | :type s: str 21 | :rtype: bool 22 | """ 23 | if len(s) < 0: 24 | return False 25 | L = len(s) 26 | for i in range(L // 2): 27 | if L % (i + 1) == 0: 28 | pieces = [] 29 | for j in range(0, L, i + 1): 30 | pieces.append(s[j:j + i + 1]) 31 | counter = Counter(pieces) 32 | if len(counter) == 1: 33 | return True 34 | return False -------------------------------------------------------------------------------- /leetcode.com/python/45_Jump_Game_II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | 3 | # Greedy Approach. BFS to be precise. 4 | def jump(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | jumps, currentEnd, currentFarthest = 0, 0, 0 10 | for i in range(len(nums) - 1): 11 | currentFarthest = max(currentFarthest, i + nums[i]) 12 | if i == currentEnd: 13 | jumps += 1 14 | currentEnd = currentFarthest 15 | return jumps 16 | 17 | 18 | 19 | 20 | sol = Solution() 21 | input = [2,3,1,1,4] 22 | output = sol.jump(input) 23 | print("Res: ", output) -------------------------------------------------------------------------------- /leetcode.com/python/460_LFU_Cache.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.com/python/460_LFU_Cache.py -------------------------------------------------------------------------------- /leetcode.com/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 | distance = 0 9 | while x or y: 10 | distance += (x % 2) ^ (y % 2) 11 | x = x // 2 12 | y = y // 2 13 | return distance 14 | 15 | 16 | -------------------------------------------------------------------------------- /leetcode.com/python/463_Island_Perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def islandPerimeter(self, grid): 3 | """ 4 | :type grid: List[List[int]] 5 | :rtype: int 6 | """ 7 | perimeterCount = 0 8 | for row in range(len(grid)): 9 | for col in range(len(grid[0])): 10 | if grid[row][col] == 1: 11 | perimeterCount += 4 12 | neighbours = [(-1, 0), (0, 1), (1, 0), (0, -1)] 13 | for neighbour in neighbours: 14 | dR, dC = neighbour 15 | newR, newC = row + dR, col + dC 16 | if 0 <= newR < len(grid) and 0 <= newC < len(grid[0]) and grid[newR][newC] == 1: 17 | perimeterCount -= 1 18 | 19 | return perimeterCount 20 | -------------------------------------------------------------------------------- /leetcode.com/python/476_Number_Complement.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findComplement(self, num): 3 | """ 4 | :type num: int 5 | :rtype: int 6 | """ 7 | bitCount, numCopy = 0, num 8 | while numCopy > 0: 9 | bitCount += 1 10 | numCopy = numCopy >> 1 11 | 12 | allBitsSet = pow(2, bitCount) - 1 13 | return num ^ allBitsSet 14 | -------------------------------------------------------------------------------- /leetcode.com/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 | S = ''.join(S.split('-')).upper() 9 | reminder = K if len(S) % K == 0 else len(S) % K 10 | currentIdx = reminder 11 | resultS = S[:currentIdx] 12 | while currentIdx < len(S): 13 | resultS += '-' + S[currentIdx: currentIdx + K] 14 | currentIdx += K 15 | return resultS 16 | 17 | 18 | 19 | sol = Solution() 20 | input = "5F3Z-2e-9-w" 21 | output = sol.licenseKeyFormatting(input, 4) 22 | print('Output: ', output) -------------------------------------------------------------------------------- /leetcode.com/python/509_Fibonacci_Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fibonacci-number/ 2 | 3 | 4 | class Solution(object): 5 | def fib(self, N): 6 | if N == 0: 7 | return 0 8 | last_two = [1, 1] 9 | counter = 3 10 | while counter <= N: 11 | next_fib = last_two[0] + last_two[1] 12 | last_two[0] = last_two[1] 13 | last_two[1] = next_fib 14 | counter += 1 15 | return last_two[1] if N > 1 else last_two[0] 16 | -------------------------------------------------------------------------------- /leetcode.com/python/50_Pow(x,_n).py: -------------------------------------------------------------------------------- 1 | 2 | # Recursive Solution 3 | class Solution(object): 4 | def myPow(self, x, n): 5 | """ 6 | :type x: float 7 | :type n: int 8 | :rtype: float 9 | """ 10 | if n == 0: 11 | return 1 12 | if n < 0: 13 | return 1 / self.myPow(x, -n) 14 | half = self.myPow(x, n/2) 15 | if n % 2 == 0: 16 | return half*half 17 | else: 18 | return x*half*half 19 | -------------------------------------------------------------------------------- /leetcode.com/python/516_Longest_Palindromic_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestPalindromeSubseq(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | stringLenght = len(s) 8 | 9 | # dp[i][j] stores the length of LPS from index 'i' to index 'j' 10 | dp = [[0 for _ in range(stringLenght)] for _ in range(stringLenght)] 11 | 12 | # every sequence with one element is a palindrome of length 1 13 | for i in range(stringLenght): 14 | dp[i][i] = 1 15 | 16 | for startIdx in range(stringLenght - 1, -1, -1): 17 | for endIdx in range(startIdx + 1, stringLenght): 18 | if s[startIdx] == s[endIdx]: 19 | dp[startIdx][endIdx] = dp[startIdx + 1][endIdx - 1] + 2 20 | else: 21 | dp[startIdx][endIdx] = max(dp[startIdx + 1][endIdx], dp[startIdx][endIdx -1]) 22 | 23 | return dp[0][-1] -------------------------------------------------------------------------------- /leetcode.com/python/518_Coin_Change_2.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def change(self, amount, coins): 3 | """ 4 | :type amount: int 5 | :type coins: List[int] 6 | :rtype: int 7 | """ 8 | ways = [0 for n in range(amount + 1)] 9 | ways[0] = 1 10 | for coin in coins: 11 | for checkingAmount in range(1, amount + 1): 12 | if coin <= checkingAmount: 13 | ways[checkingAmount] += ways[checkingAmount - coin] 14 | return ways[-1] 15 | -------------------------------------------------------------------------------- /leetcode.com/python/525_Contiguous_Array.py: -------------------------------------------------------------------------------- 1 | # https://tinyurl.com/qmbd2vl 2 | class Solution(object): 3 | def findMaxLength(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | count, maxLenSoFar = 0, 0 9 | counterMap = {count: -1} # count:index, 10 | 11 | for i in range(len(nums)): 12 | currentNum = nums[i] 13 | if currentNum == 0: 14 | count -= 1 15 | else: 16 | count += 1 17 | 18 | if count in counterMap: 19 | maxLenSoFar = max(maxLenSoFar, i - counterMap[count]) 20 | else: 21 | counterMap[count] = i 22 | 23 | return maxLenSoFar 24 | -------------------------------------------------------------------------------- /leetcode.com/python/528_Random_Pick_with_Weight.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | import random 3 | class Solution(object): 4 | 5 | def __init__(self, w): 6 | """ 7 | :type w: List[int] 8 | """ 9 | self.prefisSum = w 10 | for i in range(1, len(self.prefisSum)): 11 | self.prefisSum[i] = self.prefisSum[i] + self.prefisSum[i - 1] 12 | 13 | 14 | def pickIndex(self): 15 | """ 16 | :rtype: int 17 | """ 18 | target = random.randint(1, self.prefisSum[-1]) 19 | return bisect.bisect_left(self.prefisSum, target) 20 | 21 | # Your Solution object will be instantiated and called as such: 22 | # obj = Solution(w) 23 | # param_1 = obj.pickIndex() -------------------------------------------------------------------------------- /leetcode.com/python/53_Maximum_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxSubArray(self, nums): 3 | max_ending_here = nums[0] 4 | max_so_far = nums[0] 5 | for i in range(1, len(nums)): 6 | num = nums[i] 7 | max_ending_here = max(num, max_ending_here + num) 8 | max_so_far = max(max_so_far, max_ending_here) 9 | return max_so_far 10 | 11 | -------------------------------------------------------------------------------- /leetcode.com/python/540_Single_Element_in_a_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | """ 2 | [1,1,2,3,3,4,4,8,8] 3 | 0 4 8 4 | """ 5 | 6 | 7 | class Solution(object): 8 | def singleNonDuplicate(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | numLen = len(nums) 14 | if numLen == 1: 15 | return nums[-1] 16 | left, right = 0, numLen - 1 17 | while left <= right: 18 | mid = left + ((right - left) // 2) 19 | 20 | if mid + 1 < numLen and nums[mid] == nums[mid + 1]: 21 | if (right - mid - 1) % 2 == 1: 22 | left = mid + 2 23 | else: 24 | right = mid - 1 25 | elif mid - 1 >= 0 and nums[mid] == nums[mid - 1]: 26 | if (mid - left - 1) % 2 == 1: 27 | right = mid - 2 28 | else: 29 | left = mid + 1 30 | else: 31 | return nums[mid] 32 | 33 | return nums[left] 34 | -------------------------------------------------------------------------------- /leetcode.com/python/551_Student_Attendance_Record_I.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def checkRecord(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | absentCount = 0 8 | lateCount = 0 9 | for char in s: 10 | if char == 'A': 11 | absentCount += 1 12 | lateCount = 0 13 | elif char == 'L': 14 | lateCount += 1 15 | else: 16 | lateCount = 0 17 | if absentCount > 1 or lateCount > 2: 18 | return False 19 | return True 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode.com/python/567_Permutation_in_String.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution(object): 5 | def checkInclusion(self, s1, s2): 6 | """ 7 | :type s1: str 8 | :type s2: str 9 | :rtype: bool 10 | """ 11 | s1Counter = Counter(s1) 12 | s2Counter = Counter(s2[:len(s1) - 1]) 13 | for right in range(len(s1) - 1, len(s2)): 14 | s2Counter[s2[right]] += 1 15 | if s1Counter == s2Counter: 16 | return True 17 | s2Counter[s2[right - len(s1) + 1]] -= 1 18 | if s2Counter[s2[right - len(s1) + 1]] == 0: 19 | del s2Counter[s2[right - len(s1) + 1]] 20 | return False 21 | 22 | -------------------------------------------------------------------------------- /leetcode.com/python/56_Merge_Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def merge(self, intervals): 3 | """ 4 | :type intervals: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | if len(intervals) <= 1: 8 | return intervals 9 | intervals = sorted(intervals, key = lambda x: x[0]) 10 | mergedIntervals = [] 11 | for i in range(len(intervals)): 12 | currentInterval = intervals[i] 13 | if mergedIntervals and currentInterval[0] <= mergedIntervals[-1][1]: 14 | mergedIntervals[-1][1] = max(mergedIntervals[-1][1], currentInterval[1]) 15 | else: 16 | mergedIntervals.append(currentInterval) 17 | return mergedIntervals 18 | 19 | 20 | 21 | sol = Solution() 22 | input = [[1,4],[0,4]] 23 | output = sol.merge(input) 24 | print('Res: ', output) -------------------------------------------------------------------------------- /leetcode.com/python/583_Delete_Operation_for_Two_Strings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minDistance(self, word1, word2): 3 | """ 4 | :type word1: str 5 | :type word2: str 6 | :rtype: int 7 | """ 8 | word1Len, word2Len = len(word1), len(word2) 9 | dp = [[0 for _ in range(word1Len + 1)] for _ in range(word2Len + 1)] 10 | maxSusequenceLen = 0 11 | for i in range(1, word2Len + 1): 12 | for j in range(1, word1Len + 1): 13 | if word2[i - 1] == word1[j - 1]: 14 | dp[i][j] = dp[i -1][j - 1] + 1 15 | else: 16 | dp[i][j] = max(dp[i][j - 1], dp[i -1][j]) 17 | maxSusequenceLen = max(maxSusequenceLen, dp[i][j]) 18 | return (word1Len - maxSusequenceLen) + (word2Len - maxSusequenceLen) -------------------------------------------------------------------------------- /leetcode.com/python/589_N-ary_Tree_Preorder_Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node(object): 4 | def __init__(self, val, children): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | 10 | class Solution(object): 11 | def preorder(self, root): 12 | """ 13 | :type root: Node 14 | :rtype: List[int] 15 | """ 16 | if root is None: 17 | return [] 18 | stack, result = [root, ], [] 19 | while stack: 20 | current = stack.pop() 21 | result.append(current.val) 22 | stack.extend(current.children[::-1]) 23 | return result 24 | -------------------------------------------------------------------------------- /leetcode.com/python/590_N-ary_Tree_Postorder_Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node(object): 4 | def __init__(self, val, children): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | 10 | class Solution(object): 11 | def postorder(self, root): 12 | """ 13 | :type root: Node 14 | :rtype: List[int] 15 | """ 16 | stack = [root, ] 17 | result = [] 18 | while stack: 19 | current = stack.pop() 20 | if current and current.children: 21 | stack.extend(current.children) 22 | if current: 23 | result.append(current.val) 24 | return result[::-1] 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/593_Valid_Square.py: -------------------------------------------------------------------------------- 1 | import math 2 | from collections import Counter 3 | class Solution(object): 4 | def validSquare(self, p1, p2, p3, p4): 5 | """ 6 | :type p1: List[int] 7 | :type p2: List[int] 8 | :type p3: List[int] 9 | :type p4: List[int] 10 | :rtype: bool 11 | """ 12 | points = [p1, p2, p3, p4] 13 | distanceCount = Counter() 14 | for i in range(len(points)): 15 | for j in range(i + 1, len(points)): 16 | distanceCount[self.distance(points[i], points[j])] += 1 17 | 18 | return len(distanceCount) == 2 and 4 in distanceCount.values() and 2 in distanceCount.values() 19 | 20 | 21 | def distance(self, p1, p2): 22 | val = (p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2 23 | return val 24 | 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/5_Longest_Palindromic_Substring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | currentLongest = [0, 1] 8 | for i in range(1, len(s)): 9 | odd = self.getLongestPalindromeFrom(s, i - 1, i + 1) 10 | even = self.getLongestPalindromeFrom(s, i - 1, i) 11 | longest = max(odd, even, key = lambda x: x[1] - x[0]) 12 | currentLongest = max(longest, currentLongest, key=lambda x: x[1] - x[0]) 13 | return s[currentLongest[0]:currentLongest[1]] 14 | 15 | 16 | def getLongestPalindromeFrom(self, string, leftIdx, rightIdx): 17 | while leftIdx >= 0 and rightIdx < len(string): 18 | if string[leftIdx] != string[rightIdx]: 19 | break 20 | else: 21 | leftIdx -= 1 22 | rightIdx += 1 23 | return [leftIdx + 1, rightIdx] -------------------------------------------------------------------------------- /leetcode.com/python/60_Permutation_Sequence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getPermutation(self, n, k): 3 | """ 4 | :type n: int 5 | :type k: int 6 | :rtype: str 7 | """ 8 | factorial = {1: 1, 2: 2, 3: 6, 4: 24, 5: 120, 6: 720, 7: (5040), 8: (40320), 9: (362880)} 9 | digits = [str(x) for x in range(1, n + 1)] 10 | 11 | number = [] 12 | currentDigitCount = 1 13 | currentK = k - 1 14 | 15 | while currentDigitCount < n: 16 | chosenDigitIndex, currentK = divmod(currentK, factorial[n - currentDigitCount]) 17 | number.append(digits.pop(chosenDigitIndex)) 18 | currentDigitCount += 1 19 | 20 | number.append(digits[0]) 21 | return ''.join(number) -------------------------------------------------------------------------------- /leetcode.com/python/653_Two_Sum_IV_Input_is_a_BST.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def findTarget(self, root, k): 9 | """ 10 | :type root: TreeNode 11 | :type k: int 12 | :rtype: bool 13 | """ 14 | diffSet = set() 15 | return self.findTargetHelper(root, k, diffSet) 16 | 17 | def findTargetHelper(self, root, k, diffSet): 18 | if not root: 19 | return False 20 | if root.val in diffSet: 21 | return True 22 | else: 23 | diffSet.add((k - root.val)) 24 | left = self.findTargetHelper(root.left, k, diffSet) 25 | right = self.findTargetHelper(root.right, k, diffSet) 26 | return left or right 27 | -------------------------------------------------------------------------------- /leetcode.com/python/659_Split_Array_into_Consecutive_Subsequences.py: -------------------------------------------------------------------------------- 1 | # Source: https://tinyurl.com/u2hnq84 and https://tinyurl.com/w3j4yqp 2 | from collections import defaultdict 3 | class Solution(object): 4 | def isPossible(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: bool 8 | """ 9 | occurrences, nextNums = defaultdict(int), defaultdict(int) 10 | for num in nums: 11 | occurrences[num] += 1 12 | for num in nums: 13 | if occurrences[num] == 0: 14 | continue 15 | elif nextNums[num] > 0: 16 | nextNums[num] -= 1 17 | nextNums[num + 1] += 1 18 | elif occurrences[num + 1] > 0 and occurrences[num + 2] > 0: 19 | occurrences[num + 1] -= 1 20 | occurrences[num + 2] -= 1 21 | nextNums[num + 3] += 1 22 | else: 23 | return False 24 | occurrences[num] -= 1 25 | return True -------------------------------------------------------------------------------- /leetcode.com/python/66_Plus_One.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def plusOne(self, digits): 3 | """ 4 | :type digits: List[int] 5 | :rtype: List[int] 6 | """ 7 | result = [] 8 | carrry = 0 9 | for i in range(len(digits) - 1, -1, -1): 10 | num = digits[i] 11 | if i == len(digits) - 1: 12 | num += 1 13 | 14 | if num + carrry > 9: 15 | if i == 0: 16 | result.append((num + carrry) % 10) 17 | result.append((num + carrry) // 10) 18 | else: 19 | result.append(0) 20 | carrry = 1 21 | else: 22 | result.append(num + carrry) 23 | carrry = 0 24 | return reversed(result) 25 | -------------------------------------------------------------------------------- /leetcode.com/python/671_Second_Minimum_Node_In_a_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 | def findSecondMinimumValue(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | 15 | -------------------------------------------------------------------------------- /leetcode.com/python/678_Valid_Parenthesis_String.py: -------------------------------------------------------------------------------- 1 | # Source: https://tinyurl.com/yad2akx6 2 | class Solution(object): 3 | def checkValidString(self, s): 4 | """ 5 | :type s: str 6 | :rtype: bool 7 | """ 8 | cmin, cmax = 0, 0 # openCount in range [cmin, cmax] 9 | for ch in s: 10 | if ch == "(": 11 | cmin += 1 12 | cmax += 1 13 | elif ch == ")": 14 | cmin -= 1 15 | cmax -= 1 16 | elif ch == "*": 17 | cmax += 1 # if `*` become `(` then openCount++ 18 | cmin -= 1 # if `*` become `)` then openCount-- 19 | # if `*` become `` then nothing happens 20 | # So openCount will be in new range [cmin-1, cmax+1] 21 | if cmax < 0: 22 | return False # Don't have enough openCount -> Invalid 23 | cmin = max(cmin, 0) # Keep openCount >= 0 24 | return cmin == 0 # Return true if can found `openCount == 0` in range [cmin, cmax] 25 | -------------------------------------------------------------------------------- /leetcode.com/python/692_Top_K_Frequent_Words.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | import heapq 3 | 4 | 5 | class Solution(object): 6 | def topKFrequent(self, words, k): 7 | """ 8 | :type words: List[str] 9 | :type k: int 10 | :rtype: List[str] 11 | """ 12 | wordFrequencyMap = Counter(words) 13 | 14 | maxHeap = [] 15 | for word, frequency in wordFrequencyMap.items(): 16 | heapq.heappush(maxHeap, (-frequency, word)) 17 | 18 | wordList = [] 19 | while k > 0: 20 | frequency, word = heapq.heappop(maxHeap) 21 | wordList.append(word) 22 | k -= 1 23 | 24 | return wordList 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/69_Sqrt(x).py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mySqrt(self, x): 3 | """ 4 | :type x: int 5 | :rtype: int 6 | """ 7 | if x < 2: 8 | return x 9 | left, right = 0, x // 2 10 | while left <= right: 11 | mid = left + (right - left) // 2 12 | num = mid * mid 13 | if num > x: 14 | right = mid - 1 15 | elif num < x: 16 | left = mid + 1 17 | else: 18 | return mid 19 | return right 20 | 21 | 22 | 23 | 24 | sol = Solution() 25 | x = 6 26 | out = sol.mySqrt(x) 27 | print("Res: ", out) -------------------------------------------------------------------------------- /leetcode.com/python/700_Search_in_a_Binary_Search_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 searchBST(self, root, val): 10 | """ 11 | :type root: TreeNode 12 | :type val: int 13 | :rtype: TreeNode 14 | """ 15 | currentNode = root 16 | while True: 17 | if val < currentNode.val: 18 | if currentNode.left is None: 19 | return None 20 | else: 21 | currentNode = currentNode.left 22 | elif val > currentNode.val: 23 | if currentNode.right is None: 24 | return None 25 | else: 26 | currentNode = currentNode.right 27 | else: 28 | return currentNode 29 | -------------------------------------------------------------------------------- /leetcode.com/python/701_Insert_into_a_Binary_Search_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 insertIntoBST(self, root, val): 10 | """ 11 | :type root: TreeNode 12 | :type val: int 13 | :rtype: TreeNode 14 | """ 15 | currentNode = root 16 | while True: 17 | if val < currentNode.val: 18 | if currentNode.left is not None: 19 | currentNode = currentNode.left 20 | else: 21 | currentNode.left = TreeNode(val) 22 | break 23 | elif val > currentNode.val: 24 | if currentNode.right is not None: 25 | currentNode = currentNode.right 26 | else: 27 | currentNode.right = TreeNode(val) 28 | break 29 | return root 30 | 31 | -------------------------------------------------------------------------------- /leetcode.com/python/704_Binary_Search.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-search/ 2 | 3 | 4 | class Solution: 5 | def search(self, nums, target): 6 | l, r = 0, len(nums) - 1 7 | while l <= r: 8 | mid = (l + r) // 2 9 | if nums[mid] < target: 10 | l = mid 11 | elif nums[mid] > target: 12 | r = mid 13 | else: 14 | return mid 15 | return -1 16 | 17 | 18 | 19 | 20 | # Your MyLinkedList object will be instantiated and called as such: 21 | obj = Solution() 22 | 23 | index = obj.search([2], 2) 24 | print("Index: ", index) -------------------------------------------------------------------------------- /leetcode.com/python/713_Subarray_Product_Less_Than_K.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numSubarrayProductLessThanK(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | if len(nums) <= 0 or k <= 1: 9 | return 0 10 | cumulativeProduct = 1 11 | left, subarrayCount = 0, 0 12 | for right, num in enumerate(nums): 13 | cumulativeProduct *= num 14 | while cumulativeProduct >= k: 15 | cumulativeProduct /= nums[left] 16 | left += 1 17 | subarrayCount += (right - left + 1) 18 | return subarrayCount -------------------------------------------------------------------------------- /leetcode.com/python/714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProfit(self, prices, fee): 3 | """ 4 | :type prices: List[int] 5 | :type fee: int 6 | :rtype: int 7 | """ 8 | days = len(prices) 9 | totalProfit = 0 10 | minimumPrice = prices[0] 11 | for today in range(1, days): 12 | if prices[today] < minimumPrice: 13 | minimumPrice = prices[today] 14 | elif minimumPrice < (prices[today] - fee): 15 | totalProfit += (prices[today] - minimumPrice - fee) 16 | minimumPrice = prices[today] - fee # https://tinyurl.com/unnnjwx and https://tinyurl.com/umjax4y 17 | return totalProfit 18 | 19 | 20 | sol = Solution() 21 | prices = [1,3,7,5,10,3] 22 | fee = 3 23 | output = sol.maxProfit(prices, fee) 24 | print('Res: ', output) -------------------------------------------------------------------------------- /leetcode.com/python/718_Maximum_Length_of_Repeated_Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findLength(self, A, B): 3 | """ 4 | :type A: List[int] 5 | :type B: List[int] 6 | :rtype: int 7 | """ 8 | lenA, lenB = len(A), len(B) 9 | dp = [[0 for _ in range(lenA + 1)] for _ in range(lenB + 1)] 10 | maxLength = 0 11 | for i in range(1, lenB + 1): 12 | for j in range(1, lenA + 1): 13 | if B[i - 1] == A[j - 1]: 14 | dp[i][j] = 1 + dp[i - 1][j - 1] 15 | maxLength = max(maxLength, dp[i][j]) 16 | return maxLength 17 | -------------------------------------------------------------------------------- /leetcode.com/python/71_Simplify_Path.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def simplifyPath(self, path): 3 | """ 4 | :type path: str 5 | :rtype: str 6 | """ 7 | if not path: 8 | return path 9 | 10 | stack = [] 11 | for directory in path.split("/"): 12 | if directory == "..": 13 | if stack: 14 | stack.pop() 15 | elif directory == "." or not directory: 16 | continue 17 | else: 18 | stack.append(directory) 19 | 20 | finalDirectoryPath = "/" + "/".join(stack) 21 | return finalDirectoryPath 22 | 23 | -------------------------------------------------------------------------------- /leetcode.com/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 | S = sum(nums) 8 | leftSum = 0 9 | for i in range(len(nums)): 10 | if leftSum == (S - nums[i] - leftSum): 11 | return i 12 | leftSum += nums[i] 13 | return -1 14 | -------------------------------------------------------------------------------- /leetcode.com/python/72_Edit_Distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDistance(self, word1: str, word2: str) -> int: 3 | edits = [[x for x in range(len(word1) + 1)] for y in range(len(word2) + 1)] 4 | for i in range(1, len(word2) + 1): 5 | edits[i][0] = edits[i - 1][0] + 1 6 | for i in range(1, len(word2) + 1): 7 | for j in range(1, len(word1) + 1): 8 | if word2[i - 1] == word1[j - 1]: 9 | edits[i][j] = edits[i - 1][j - 1] 10 | else: 11 | edits[i][j] = 1 + min(edits[i][j - 1], edits[i - 1][j - 1], edits[i - 1][j]) 12 | return edits[-1][-1] 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /leetcode.com/python/731_My_Calendar_II.py: -------------------------------------------------------------------------------- 1 | class MyCalendarTwo(object): 2 | 3 | def __init__(self): 4 | self.bookings = [] 5 | 6 | def book(self, start, end): 7 | """ 8 | :type start: int 9 | :type end: int 10 | :rtype: bool 11 | """ 12 | # self.bookings = sorted(self.bookings) 13 | overlapCount = 0 14 | for slot in self.bookings: 15 | st, ed = slot 16 | if st < start < ed or st <= end < ed: 17 | overlapCount += 1 18 | if overlapCount >= 3: 19 | return False 20 | else: 21 | self.bookings.append([start, end]) 22 | return True 23 | 24 | # Your MyCalendarTwo object will be instantiated and called as such: 25 | # obj = MyCalendarTwo() 26 | # param_1 = obj.book(start,end) -------------------------------------------------------------------------------- /leetcode.com/python/739_Daily_Temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def dailyTemperatures(self, T): 3 | """ 4 | :type T: List[int] 5 | :rtype: List[int] 6 | """ 7 | result = [0 for _ in range(len(T))] 8 | stack = [] 9 | for i in range(len(T) - 1, -1, -1): 10 | while stack: 11 | temperature, day = stack[-1] 12 | if T[i] >= temperature: 13 | stack.pop() 14 | else: 15 | break 16 | if stack: 17 | temperature, day = stack[-1] 18 | result[i] = day - i 19 | stack.append((T[i], i)) 20 | return result -------------------------------------------------------------------------------- /leetcode.com/python/747_Largest_Number_At_Least_Twice_of_Others.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def dominantIndex(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | maxNum = -1 8 | maxIndex = -1 9 | for i in range(len(nums)): 10 | if nums[i] >= maxNum: 11 | maxNum = nums[i] 12 | maxIndex = i 13 | for i in range(len(nums)): 14 | num2X = nums[i] * 2 15 | if num2X > maxNum and i != maxIndex: 16 | return -1 17 | return maxIndex 18 | 19 | 20 | sol = Solution() 21 | inputNums = [0,0,2,3] 22 | output = sol.dominantIndex(inputNums) 23 | print('Output: ', output) -------------------------------------------------------------------------------- /leetcode.com/python/74_Search_a_2D_Matrix.py: -------------------------------------------------------------------------------- 1 | # Approach 4: Search Space Reduction 2 | class Solution(object): 3 | def searchMatrix(self, matrix, target): 4 | """ 5 | :type matrix: List[List[int]] 6 | :type target: int 7 | :rtype: bool 8 | """ 9 | if len(matrix) == 0 or len(matrix[0]) == 0: 10 | return False 11 | 12 | height = len(matrix) 13 | weidth = len(matrix[0]) 14 | 15 | row = height - 1 16 | col = 0 17 | 18 | while row >= 0 and col < weidth: 19 | if matrix[row][col] < target: 20 | col += 1 21 | elif matrix[row][col] > target: 22 | row -= 1 23 | else: 24 | return True 25 | return False -------------------------------------------------------------------------------- /leetcode.com/python/75_Sort_Colors.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sortColors(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: None Do not return anything, modify nums in-place instead. 6 | """ 7 | low, high = 0, len(nums) - 1 8 | iteratorIdx = 0 9 | while iteratorIdx <= high: 10 | if nums[iteratorIdx] == 0: 11 | nums[iteratorIdx], nums[low] = nums[low], nums[iteratorIdx] 12 | iteratorIdx += 1 13 | low += 1 14 | elif nums[iteratorIdx] == 2: 15 | nums[iteratorIdx], nums[high] = nums[high], nums[iteratorIdx] 16 | high -= 1 17 | else: 18 | iteratorIdx += 1 19 | return nums 20 | -------------------------------------------------------------------------------- /leetcode.com/python/763_Partition_Labels.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution(object): 3 | def partitionLabels(self, S): 4 | """ 5 | :type S: str 6 | :rtype: List[int] 7 | """ 8 | counter = Counter(S) 9 | windowChrSet = set() 10 | left, right = 0, 0 11 | partLabels = [] 12 | while left <= right and right < len(S): 13 | rightChr = S[right] 14 | windowChrSet.add(rightChr) 15 | counter[rightChr] -= 1 16 | 17 | if counter[rightChr] == 0: 18 | del counter[rightChr] 19 | windowChrSet.discard(rightChr) 20 | 21 | if len(windowChrSet) <= 0: 22 | partLabels.append(right - left + 1) 23 | left = right + 1 24 | right += 1 25 | return partLabels 26 | -------------------------------------------------------------------------------- /leetcode.com/python/771_Jewels_and_Stones.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class Solution(object): 3 | def numJewelsInStones(self, J, S): 4 | """ 5 | :type J: str 6 | :type S: str 7 | :rtype: int 8 | """ 9 | sCounter = Counter(S) 10 | j = set(J) 11 | jwels = 0 12 | for stone in sCounter: 13 | if stone in j: 14 | jwels += sCounter[stone] 15 | return jwels -------------------------------------------------------------------------------- /leetcode.com/python/77_Combinations.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def combine(self, n, k): 3 | """ 4 | :type n: int 5 | :type k: int 6 | :rtype: List[List[int]] 7 | """ 8 | allCombinations, currentCombinations = [], [] 9 | self.generateCombinations(n, k, 1, currentCombinations, allCombinations) 10 | return allCombinations 11 | 12 | def generateCombinations(self, n, k, startingNum, currentCombinations, allCombinations): 13 | if len(currentCombinations) == k: 14 | allCombinations.append(list(currentCombinations)) 15 | return 16 | for i in range(startingNum, n + 1): 17 | currentCombinations.append(i) 18 | self.generateCombinations(n, k, i + 1, currentCombinations, allCombinations) 19 | currentCombinations.pop() # Backtrack 20 | 21 | 22 | 23 | 24 | sol = Solution() 25 | n = 2 26 | k = 1 27 | out = sol.combine(n, k) 28 | print("Res: ", out) -------------------------------------------------------------------------------- /leetcode.com/python/784_Letter_Case_Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def letterCasePermutation(self, S): 3 | """ 4 | :type S: str 5 | :rtype: List[str] 6 | """ 7 | answer = [] 8 | self.backtrack(S, "", 0, answer) 9 | return answer 10 | 11 | 12 | def backtrack(self, originalString, path, index, cache): 13 | if index == len(originalString): 14 | cache.append(path) 15 | return 16 | if originalString[index].isalpha(): 17 | self.backtrack(originalString, path+originalString[index].upper(), index + 1, cache) 18 | self.backtrack(originalString, path + originalString[index].lower(), index + 1, cache) 19 | else: 20 | self.backtrack(originalString, path + originalString[index], index + 1, cache) 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode.com/python/785_Is_Graph_Bipartite.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class Solution(object): 5 | def isBipartite(self, graph): 6 | """ 7 | :type graph: List[List[int]] 8 | :rtype: bool 9 | """ 10 | color = {} 11 | for node in range(len(graph)): 12 | if node not in color and graph[node]: 13 | queue = deque([node]) 14 | color[node] = 0 15 | while queue: 16 | currentNode = queue.popleft() 17 | for neighbour in graph[currentNode]: 18 | if neighbour not in color: 19 | queue.append(neighbour) 20 | color[neighbour] = color[currentNode] ^ 1 21 | elif color[neighbour] == color[currentNode]: 22 | return False 23 | return True 24 | -------------------------------------------------------------------------------- /leetcode.com/python/792_Number_of_Matching_Subsequences.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Solution(object): 5 | 6 | def numMatchingSubseq(self, S, words): 7 | waiting = defaultdict(list) 8 | for w in words: 9 | waiting[w[0]].append(iter(w[1:])) 10 | for c in S: 11 | for it in waiting.pop(c, ()): 12 | waiting[next(it, None)].append(it) 13 | return len(waiting[None]) 14 | 15 | 16 | 17 | 18 | sol = Solution() 19 | S = "abcde" 20 | words = ["a", "bb", "acd", "ace"] 21 | out = sol.numMatchingSubseq(S, words) 22 | print('Res: ', out) -------------------------------------------------------------------------------- /leetcode.com/python/801_Minimum_Swaps_To_Make_Sequences_Increasing.py: -------------------------------------------------------------------------------- 1 | 2 | # Source: https://tinyurl.com/tzx7wpv 3 | class Solution(object): 4 | def minSwap(self, A, B): 5 | """ 6 | :type A: List[int] 7 | :type B: List[int] 8 | :rtype: int 9 | """ 10 | arrLen = len(A) 11 | swaps, noSwaps = [arrLen] * arrLen, [arrLen] * arrLen 12 | swaps[0], noSwaps[0] = 1, 0 13 | for i in range(1, arrLen): 14 | currentNumA, prevNumA = A[i], A[i - 1] 15 | currentNumB, prevNumB = B[i], B[i - 1] 16 | if currentNumA > prevNumA and currentNumB > prevNumB: 17 | noSwaps[i] = noSwaps[i - 1] 18 | swaps[i] = swaps[i - 1] + 1 19 | if currentNumB > prevNumA and currentNumA > prevNumB: 20 | noSwaps[i] = min(noSwaps[i], swaps[i - 1]) # If we do ot make the swap in this case 21 | swaps[i] = min(swaps[i], noSwaps[i - 1] + 1) # If we make the swap in this case 22 | return min(swaps[-1], noSwaps[-1]) 23 | -------------------------------------------------------------------------------- /leetcode.com/python/811_Subdomain_Visit_Count.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution(object): 5 | def subdomainVisits(self, cpdomains): 6 | """ 7 | :type cpdomains: List[str] 8 | :rtype: List[str] 9 | """ 10 | ans = collections.Counter() 11 | for cpdomain in cpdomains: 12 | count, domain = cpdomain.split() 13 | count = int(count) 14 | frags = domain.split('.') 15 | for i in range(len(frags)): 16 | ans[".".join(frags[i:])] += count 17 | return ["{} {}".format(ct, dom) for dom, ct in ans.items()] -------------------------------------------------------------------------------- /leetcode.com/python/817_Linked_List_Components.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 numComponents(self, head, G): 9 | """ 10 | :type head: ListNode 11 | :type G: List[int] 12 | :rtype: int 13 | """ 14 | setG = set(G) 15 | result, count = 0, 0 16 | while head: 17 | if head.val in setG: 18 | count += 1 19 | else: 20 | if count: 21 | result += 1 22 | count = 0 23 | head = head.next 24 | return result + 1 if count else result 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/819_Most_Common_Word.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | class Solution(object): 4 | def mostCommonWord(self, paragraph, banned): 5 | """ 6 | :type paragraph: str 7 | :type banned: List[str] 8 | :rtype: str 9 | """ 10 | ban = set(banned) 11 | words = re.findall(r'\w+', paragraph.lower()) 12 | return collections.Counter(w for w in words if w not in ban).most_common(1)[0][0] 13 | 14 | 15 | """ 16 | bannedSet - for quering 17 | 18 | split the paragraph and generate only a list of lowercase words 19 | 20 | 21 | """ -------------------------------------------------------------------------------- /leetcode.com/python/832_Flipping_an_Image.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def flipAndInvertImage(self, A): 3 | """ 4 | :type A: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | rowCount = len(A) 8 | columnCount = len(A[0]) 9 | for row in A: 10 | for columnIdx in range((columnCount + 1) // 2): 11 | row[columnIdx], row[columnCount - columnIdx - 1] = row[columnCount - columnIdx - 1] ^ 1, row[columnIdx] ^ 1 12 | return A -------------------------------------------------------------------------------- /leetcode.com/python/833_Find_And_Replace_in_String.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findReplaceString(self, S, indexes, sources, targets): 3 | """ 4 | :type S: str 5 | :type indexes: List[int] 6 | :type sources: List[str] 7 | :type targets: List[str] 8 | :rtype: str 9 | """ 10 | newS = list(S) 11 | for idx, source, target in zip(indexes, sources, targets): 12 | if not S[idx:].startswith(source): 13 | continue 14 | else: 15 | newS[idx] = target 16 | for i in range(idx + 1, idx + len(source)): 17 | newS[i] = "" 18 | return "".join(newS) 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode.com/python/835_Image_Overlap.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution(object): 3 | def largestOverlap(self, A, B): 4 | """ 5 | :type A: List[List[int]] 6 | :type B: List[List[int]] 7 | :rtype: int 8 | """ 9 | translationDistanceCount = defaultdict(int) 10 | a1Coordinates, b1Coordinates = [], [] 11 | for i in range(len(A)): 12 | for j in range(len(A[0])): 13 | if A[i][j] == 1: 14 | a1Coordinates.append((i, j)) 15 | if B[i][j] == 1: 16 | b1Coordinates.append((i, j)) 17 | 18 | for aRow, aCol in a1Coordinates: 19 | for bRow, bCol in b1Coordinates: 20 | translation = (bRow - aRow, bCol - aCol) 21 | translationDistanceCount[translation] += 1 22 | return max(translationDistanceCount.values()) if translationDistanceCount else 0 -------------------------------------------------------------------------------- /leetcode.com/python/841_Keys_and_Rooms.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canVisitAllRooms(self, rooms): 3 | """ 4 | :type rooms: List[List[int]] 5 | :rtype: bool 6 | """ 7 | seen = [False] * len(rooms) 8 | seen[0] = True 9 | stack = [0, ] 10 | while stack: 11 | roomIdx = stack.pop() 12 | for key in rooms[roomIdx]: 13 | if not seen[key]: 14 | seen[key] = True 15 | stack.append(key) 16 | return all(seen) 17 | -------------------------------------------------------------------------------- /leetcode.com/python/845_Longest_Mountain_in_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestMountain(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: int 6 | """ 7 | longestPeakLen = 0 8 | i = 1 9 | while i < len(A) - 1: 10 | isPeak = A[i - 1] < A[i] > A[i + 1] 11 | if not isPeak: 12 | i += 1 13 | continue 14 | 15 | leftIdx = i - 2 16 | while leftIdx >= 0 and A[leftIdx] < A[leftIdx + 1]: 17 | leftIdx -= 1 18 | 19 | rightIdx = i + 2 20 | while rightIdx < len(A) and A[rightIdx - 1] > A[rightIdx]: 21 | rightIdx += 1 22 | 23 | currentPeakLen = rightIdx - leftIdx - 1 24 | longestPeakLen = max(longestPeakLen, currentPeakLen) 25 | i = rightIdx 26 | 27 | return longestPeakLen 28 | 29 | -------------------------------------------------------------------------------- /leetcode.com/python/846_Hand_of_Straights.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from heapq import heappop, heapify 3 | 4 | # Source: https://tinyurl.com/tp46c6s 5 | class Solution: 6 | def isNStraightHand(self, hand, W): 7 | """ 8 | :type hand: List[int] 9 | :type W: int 10 | :rtype: bool 11 | """ 12 | l = len(hand) 13 | if l % W: 14 | return False 15 | if W == 1: 16 | return True 17 | counter = defaultdict(int) 18 | for i in hand: 19 | counter[i] += 1 20 | heapify(hand) 21 | for i in range(l // W): 22 | start = heappop(hand) 23 | while counter[start] == 0: 24 | start = heappop(hand) 25 | for i in range(W): 26 | counter[start] -= 1 27 | if counter[start] < 0: 28 | return False 29 | start += 1 30 | return True -------------------------------------------------------------------------------- /leetcode.com/python/84_Largest_Rectangle_in_Histogram.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution(object): 4 | def largestRectangleArea(self, heights): 5 | """ 6 | :type heights: List[int] 7 | :rtype: int 8 | """ 9 | heights.append(0) 10 | stack = [-1] 11 | finalArea = 0 12 | for i in range(len(heights)): 13 | while heights[i] < heights[stack[-1]]: 14 | height = heights[stack.pop()] 15 | width = i - stack[-1] - 1 16 | finalArea = max(finalArea, height*width) 17 | stack.append(i) 18 | heights.pop() 19 | return finalArea 20 | 21 | 22 | -------------------------------------------------------------------------------- /leetcode.com/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 | leftIdx, rightIdx = 0, len(A) - 1 8 | while leftIdx < rightIdx: 9 | midIdx = leftIdx + (rightIdx - leftIdx) // 2 10 | if A[midIdx] < A[midIdx + 1]: 11 | leftIdx = midIdx + 1 12 | else: 13 | rightIdx = midIdx 14 | return leftIdx 15 | -------------------------------------------------------------------------------- /leetcode.com/python/875_Koko_Eatin_Bananas.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution(object): 4 | def minEatingSpeed(self, piles, H): 5 | """ 6 | :type piles: List[int] 7 | :type H: int 8 | :rtype: int 9 | """ 10 | low, high = 1, max(piles) 11 | while low < high: 12 | mid = (low + high) / 2 13 | isPossible = self.isPossible(piles, H, mid) 14 | if isPossible: 15 | high = mid 16 | else: 17 | low = mid + 1 18 | return low 19 | 20 | def isPossible(self, piles, H, k): 21 | totalHours = 0 22 | for bananas in piles: 23 | totalHours += bananas / k 24 | if bananas % k != 0: 25 | totalHours += 1 26 | return totalHours <= H 27 | 28 | 29 | -------------------------------------------------------------------------------- /leetcode.com/python/876_Middle_of_the_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 middleNode(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | if not head: 14 | return None 15 | fastRuner, slowRuner = head, head 16 | while fastRuner and fastRuner.next: 17 | fastRuner = fastRuner.next.next 18 | slowRuner = slowRuner.next 19 | return slowRuner 20 | -------------------------------------------------------------------------------- /leetcode.com/python/88_Merge_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def merge(self, nums1, m, nums2, n): 3 | """ 4 | :type nums1: List[int] 5 | :type m: int 6 | :type nums2: List[int] 7 | :type n: int 8 | :rtype: None Do not return anything, modify nums1 in-place instead. 9 | """ 10 | nums1_copy = nums1[:m] 11 | nums1[:] = [] 12 | 13 | p1 = 0 14 | p2 = 0 15 | 16 | while p1 < m and p2 < n: 17 | if nums1_copy[p1] < nums2[p2]: 18 | nums1.append(nums1_copy[p1]) 19 | p1 += 1 20 | else: 21 | nums1.append(nums2[p2]) 22 | p2 += 1 23 | 24 | if p1 < m: 25 | nums1[p1 + p2:] = nums1_copy[p1:] 26 | if p2 < n: 27 | nums1[p1 + p2:] = nums2[p2:] -------------------------------------------------------------------------------- /leetcode.com/python/895_Maximum_Frequency_Stack.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | import heapq 3 | 4 | class FreqStack(object): 5 | 6 | def __init__(self): 7 | self.counter = defaultdict(int) 8 | self.stackIdx = -1 # initially the stack is empty 9 | self.maxHeap = [] 10 | 11 | def push(self, x): 12 | """ 13 | :type x: int 14 | :rtype: None 15 | """ 16 | self.counter[x] += 1 17 | self.stackIdx += 1 18 | heapq.heappush(self.maxHeap, (-self.counter[x], -self.stackIdx, x)) 19 | 20 | def pop(self): 21 | """ 22 | :rtype: int 23 | """ 24 | topElement = heapq.heappop(self.maxHeap) 25 | count, idx, x = -topElement[0], -topElement[1], topElement[2] 26 | self.counter[x] -= 1 27 | return x 28 | 29 | # Your FreqStack object will be instantiated and called as such: 30 | # obj = FreqStack() 31 | # obj.push(x) 32 | # param_2 = obj.pop() -------------------------------------------------------------------------------- /leetcode.com/python/90_Subsets_II.py: -------------------------------------------------------------------------------- 1 | # Source: https://tinyurl.com/wfkx3jt 2 | class Solution(object): 3 | def subsetsWithDup(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: List[List[int]] 7 | """ 8 | nums.sort() 9 | totalSubsets = [] 10 | totalSubsets.append([]) 11 | startIndex, endIndex = 0, 0 12 | for idx in range(len(nums)): 13 | startIndex = 0 14 | if idx > 0 and nums[idx] == nums[idx - 1]: 15 | startIndex = endIndex + 1 16 | endIndex = len(totalSubsets) - 1 17 | for j in range(startIndex, endIndex + 1): 18 | newSubset = list(totalSubsets[j]) 19 | newSubset.append(nums[idx]) 20 | totalSubsets.append(newSubset) 21 | return totalSubsets 22 | -------------------------------------------------------------------------------- /leetcode.com/python/925_Long_Pressed_Name.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isLongPressedName(self, name, typed): 3 | """ 4 | :type name: str 5 | :type typed: str 6 | :rtype: bool 7 | """ 8 | typedIdx = 0 9 | result = False 10 | for nameIdx in range(len(name)): 11 | if typedIdx >= len(typed): 12 | result = False 13 | while typedIdx < len(typed): 14 | if name[nameIdx] == typed[typedIdx]: 15 | typedIdx += 1 16 | result = True 17 | break 18 | else: 19 | typedIdx += 1 20 | result = False 21 | return result -------------------------------------------------------------------------------- /leetcode.com/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 | uniqueEmail = set() 8 | for email in emails: 9 | local, domain = email.split('@') 10 | if '+' in local: 11 | firstIndex = local.find('+') 12 | local = local[:firstIndex] 13 | uniqueEmail.add(local.replace('.','') + '@' + domain) 14 | return len(uniqueEmail) 15 | 16 | 17 | 18 | 19 | sol = Solution() 20 | emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] 21 | uniques = sol.numUniqueEmails(emails) 22 | print("Uniques: ", uniques) 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/937_Reorder_Log_Files.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | class Solution(object): 4 | def reorderLogFiles(self, logs): 5 | """ 6 | :type logs: List[str] 7 | :rtype: List[str] 8 | """ 9 | letterLogs = [] 10 | digitLogs = [] 11 | for log in logs: 12 | _id, words = log.split(' ')[:2] 13 | if words[0].isalpha(): 14 | letterLogs.append((log, log.replace(_id + ' ', '') + ' ' + _id)) 15 | else: 16 | digitLogs.append(log) 17 | letterLogs = [x[0] for x in sorted(letterLogs, key=lambda x: x[1])] 18 | return letterLogs + digitLogs 19 | 20 | 21 | sol = Solution() 22 | logFiles = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] 23 | sortedLogFiles = sol.reorderLogFiles(logFiles) 24 | print("Sorted Files: ", sortedLogFiles) 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/python/941_Valid_Mountain_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validMountainArray(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: bool 6 | """ 7 | aLen = len(A) 8 | if aLen < 3: 9 | return False 10 | peakCout, valleCount = 0, 0 11 | for i in range(1, aLen - 1): 12 | prevNum = A[i - 1] 13 | currNum = A[i] 14 | nextNum = A[i + 1] 15 | if (prevNum < currNum > nextNum): 16 | peakCout += 1 17 | if (prevNum >= currNum <= nextNum): 18 | valleCount += 1 19 | return peakCout == 1 and valleCount == 0 20 | -------------------------------------------------------------------------------- /leetcode.com/python/946_Validate_Stack_Sequences.py: -------------------------------------------------------------------------------- 1 | # Time and space both O(n) 2 | class Solution(object): 3 | def validateStackSequences(self, pushed, popped): 4 | """ 5 | :type pushed: List[int] 6 | :type popped: List[int] 7 | :rtype: bool 8 | """ 9 | stack = [] 10 | for i in range(len(pushed)): 11 | stack.append(pushed[i]) 12 | while stack and popped and popped[0] == stack[-1]: 13 | stack.pop() 14 | popped.pop(0) 15 | return len(stack) == 0 16 | 17 | 18 | 19 | 20 | 21 | # Time : :(n) | Space: O(1) 22 | class Solution(object): 23 | def validateStackSequences(self, pushed, popped): 24 | """ 25 | :type pushed: List[int] 26 | :type popped: List[int] 27 | :rtype: bool 28 | """ 29 | -------------------------------------------------------------------------------- /leetcode.com/python/949_Largest_Time_for_Given_Digits.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | class Solution(object): 3 | def largestTimeFromDigits(self, A): 4 | """ 5 | :type A: List[int] 6 | :rtype: str 7 | """ 8 | possibilities = sorted(list(itertools.permutations(sorted(A))), reverse=True) 9 | for i in possibilities: 10 | a, b, c, d = i 11 | hours = (a * 10 + b) 12 | minuites = (c * 10 + d) 13 | if hours < 24 and minuites < 60: 14 | return "{}{}:{}{}".format(a, b, c, d) 15 | return "" 16 | -------------------------------------------------------------------------------- /leetcode.com/python/958_Check_Completeness_of_a_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | from collections import deque 9 | 10 | 11 | class Solution(object): 12 | def isCompleteTree(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: bool 16 | """ 17 | bfsLevelOrder = [root] 18 | currentIdx = 0 19 | while bfsLevelOrder[currentIdx]: 20 | currentNode = bfsLevelOrder[currentIdx] 21 | bfsLevelOrder.append(currentNode.left) 22 | bfsLevelOrder.append(currentNode.right) 23 | currentIdx += 1 24 | return not any(bfsLevelOrder[currentIdx:]) 25 | -------------------------------------------------------------------------------- /leetcode.com/python/977_Squares_of_a_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sortedSquares(self, A): 3 | """ 4 | :type A: List[int] 5 | :rtype: List[int] 6 | """ 7 | left, right = 0, len(A) - 1 8 | result = [] 9 | while left <= right: 10 | leftSqr = A[left] * A[left] 11 | rightSqr = A[right] * A[right] 12 | if leftSqr >= rightSqr: 13 | result.insert(0, leftSqr) 14 | left += 1 15 | else: 16 | result.insert(0, rightSqr) 17 | right -= 1 18 | return result -------------------------------------------------------------------------------- /leetcode.com/python/9_Palindrome_Number.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.com/python/9_Palindrome_Number.py -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1004_Max_Consecutive_Ones_III.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func longestOnes(_ A: [Int], _ K: Int) -> Int { 4 | var (left, right, currentK, maxLength) = (0, 0, K, 0) 5 | while left <= right, right < A.count { 6 | if A[right] == 1 { 7 | right += 1 8 | } else { 9 | if currentK > 0 { 10 | right += 1 11 | currentK -= 1 12 | } else { 13 | // Window shrinking 14 | if A[left] == 0 { 15 | if currentK < K { 16 | currentK += 1 17 | } else { 18 | right += 1 19 | } 20 | } 21 | left += 1 22 | } 23 | } 24 | maxLength = max(maxLength, (right - left)) 25 | } 26 | return maxLength 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1265_Print_Immutable_Linked_List_in_Reverse.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for ImmutableListNode. 3 | * public class ImmutableListNode { 4 | * public func printValue() {} 5 | * public func getNext() -> ImmutableListNode? {} 6 | * } 7 | */ 8 | 9 | // Approach 1: Time O(n) , Space O(n) 10 | class Solution { 11 | func printLinkedListInReverse(_ head: ImmutableListNode?) { 12 | guard let head = head else { 13 | return 14 | } 15 | printLinkedListInReverse(head.getNext()) 16 | head.printValue() 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/128_Longest_Consecutive_Sequence.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func longestConsecutive(_ nums: [Int]) -> Int { 4 | let numsSet = Set(nums) 5 | var maxSequence = 0 6 | for num in numsSet { 7 | if !numsSet.contains(num - 1) { 8 | var end = num 9 | while numsSet.contains(end + 1) { 10 | end += 1 11 | } 12 | maxSequence = max(maxSequence, end - num + 1) 13 | } 14 | } 15 | return maxSequence 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1296_Divide_Array_in_Sets_of_K_Consecutive_Numbers.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func isPossibleDivide(_ nums: [Int], _ k: Int) -> Bool { 5 | var counter: [Int:Int] = [:] 6 | nums.forEach { num in 7 | counter[num, default: 0] += 1 8 | } 9 | print(counter) 10 | let sortedKeys = counter.keys.sorted() 11 | for key in sortedKeys { 12 | if counter[key] ?? 0 > 0 { 13 | let minus = counter[key] 14 | for i in key..<(key + k) { 15 | if counter[i] == nil || counter[i]! < minus! { 16 | return false 17 | } 18 | counter[i]! -= minus! 19 | } 20 | } 21 | } 22 | return true 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1344_Angle_Between_Hands_of_a_Clock.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func angleClock(_ hour: Int, _ minutes: Int) -> Double { 5 | let (h, m) = (Double(hour), Double(minutes)) 6 | var (hourPassed, minutesPassed) = (Double((30 * hour) % 360), Double((6 * minutes) % 360)) 7 | let hourAdjustmanentForMinute = 0.5 * Double(minutes) 8 | hourPassed += hourAdjustmanentForMinute 9 | 10 | var diff: Double = 0 11 | if minutesPassed == hourPassed { 12 | return diff 13 | } 14 | diff = Double(abs(minutesPassed - hourPassed)) 15 | return diff < Double(180) ? diff : Double(360 - diff) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/134_Gas_Station.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int { 5 | let stationCount = gas.count 6 | var startingStation = 0, gasSurplus = 0, gasDeficit = 0 7 | for i in 0..= 0 { 10 | gasSurplus += gasBalance 11 | } else { 12 | startingStation = i + 1 13 | gasDeficit += (gasBalance + gasSurplus) 14 | gasSurplus = 0 15 | } 16 | } 17 | return (gasSurplus + gasDeficit >= 0) ? startingStation : -1 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/138_Copy_List_with_Random_Pointer.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1525_Number_of_Good_Ways_to_Split_a_String.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func numSplits(_ s: String) -> Int { 3 | guard s.count > 1 else { return 0 } 4 | 5 | var (pDict, qDict, gSplitCount) = ([Character:Int](), [Character:Int](), 0) 6 | var stringArray = Array(s) 7 | stringArray.forEach { item in 8 | qDict[item, default: 0] += 1 9 | } 10 | for index in 0..<(stringArray.count - 1) { 11 | pDict[stringArray[index], default: 0] += 1 12 | qDict[stringArray[index], default: 0] -= 1 13 | if qDict[stringArray[index]] == 0 { 14 | qDict.removeValue(forKey:stringArray[index]) 15 | } 16 | if pDict.keys.count == qDict.keys.count { 17 | gSplitCount += 1 18 | } 19 | } 20 | return gSplitCount 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/152_Maximum_Product_Subarray.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func maxProduct(_ nums: [Int]) -> Int { 5 | var maxProd = 1 6 | var minProd = 1 7 | var best = nums[0] 8 | for i in 0 ..< nums.count { 9 | var currentNum = nums[i] 10 | if currentNum < 0 { 11 | swap(&maxProd, &minProd) 12 | } 13 | maxProd = max(maxProd * currentNum, currentNum) 14 | minProd = min(minProd * currentNum, currentNum) 15 | best = max(best, maxProd) 16 | } 17 | return best 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/153_Find_Minimum_in_Rotated_Sorted_Array.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func findMin(_ nums: [Int]) -> Int { 4 | var (leftIdx, rightIdx) = (0, nums.count - 1) 5 | var currentMin = Int.max 6 | while leftIdx <= rightIdx { 7 | let midIdx = leftIdx + (rightIdx - leftIdx) / 2 8 | if nums[leftIdx] <= nums[midIdx] { 9 | // Left side is sorted 10 | currentMin = min(currentMin, nums[leftIdx]) 11 | leftIdx = midIdx + 1 12 | } else { 13 | if nums[rightIdx] >= nums[midIdx] { 14 | // Right side is sorted 15 | currentMin = min(currentMin, nums[midIdx]) 16 | rightIdx = midIdx - 1 17 | } else { 18 | currentMin = min(currentMin, nums[midIdx]) 19 | } 20 | } 21 | } 22 | return currentMin 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/154_Find_Minimum_in_Rotated_Sorted_Array_II.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func findMin(_ nums: [Int]) -> Int { 4 | var (leftIdx, rightIdx) = (0, nums.count - 1) 5 | while leftIdx < rightIdx { 6 | let midIdx = leftIdx + (rightIdx - leftIdx) / 2 7 | if nums[midIdx] < nums[rightIdx] { 8 | rightIdx = midIdx 9 | } else if nums[midIdx] > nums[rightIdx] { 10 | leftIdx = midIdx + 1 11 | } else { 12 | rightIdx -= 1 13 | } 14 | } 15 | return nums[leftIdx] 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1629_Slowest_Key.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func slowestKey(_ releaseTimes: [Int], _ keysPressed: String) -> Character { 5 | let keys = Array(keysPressed) 6 | var (maxTime, maxTimeChar) = (releaseTimes.first!, keys.first!) 7 | for i in 1.. maxTime || (time == maxTime && keys[i] > maxTimeChar) { 10 | maxTimeChar = keys[i] 11 | maxTime = time 12 | } 13 | } 14 | return maxTimeChar 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1650_Lowest_Common_Ancestor_of_a_Binary_Tree_III.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func lowestCommonAncestor(_ p: Node?,_ q: Node?) -> Node? { 3 | var pDepth = getDepth(p, 0), qDepth = getDepth(q, 0) 4 | var pCopy = p, qCopy = q 5 | if pDepth > qDepth { 6 | while pDepth > qDepth { 7 | pCopy = pCopy.parent 8 | pDepth -= 1 9 | } 10 | } else if pDepth < qDepth { 11 | while pDepth < qDepth { 12 | qCopy = qCopy.parent 13 | qDepth -= 1 14 | } 15 | } 16 | 17 | while pCopy != qCopy { 18 | pCopy = pCopy.parent 19 | qCopy = qCopy.parent 20 | } 21 | 22 | return pCopy 23 | } 24 | 25 | func getDepth(_ node: Node?, _ depth: Int) -> Int { 26 | guard let node = node else { 27 | return depth 28 | } 29 | return getDepth(node.parent, depth + 1) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1762_Buildings_With_an_Ocean_View.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findBuildings(_ heights: [Int]) -> [Int] { 3 | var result = [Int](), currentMaxHeight = Int.min 4 | for i in stride(from: heights.count - 1, through: 0, by: -1) { 5 | let currentHeight = heights[i] 6 | if currentHeight > currentMaxHeight { 7 | result.append(i) 8 | currentMaxHeight = currentHeight 9 | } 10 | } 11 | return result.reversed() 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1891_Cutting_Ribbons.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func maxLength(_ ribbons: [Int], _ k: Int) -> Int { 3 | var start = 1, end = ribbons.max()!, sum = ribbons.reduce(0, +) 4 | if k > sum { 5 | return 0 6 | } 7 | while start <= end { 8 | let mid = start + ((end - start) / 2) 9 | if iSPossibleToCut(ribbons, k, mid) { 10 | start = mid + 1 11 | } else { 12 | end = mid - 1 13 | } 14 | } 15 | return start - 1 16 | } 17 | 18 | func iSPossibleToCut(_ ribbons: [Int], _ k: Int, _ targetLength: Int) -> Bool { 19 | var count = 0 20 | for ribbon in ribbons { 21 | count += (ribbon / targetLength) 22 | } 23 | return count >= k ? true : false 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/189_Rotate_Array.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func rotate(_ nums: inout [Int], _ k: Int) { 4 | var steps = k % nums.count 5 | if steps == 0 { 6 | return 7 | } 8 | nums.reverse() 9 | 10 | // Swap first portion 11 | var (left, right) = (0, steps - 1) 12 | while left < right { 13 | nums.swapAt(left, right) 14 | left += 1 15 | right -= 1 16 | } 17 | 18 | // Swap last portion 19 | (left, right) = (steps, nums.count - 1) 20 | while left < right { 21 | nums.swapAt(left, right) 22 | left += 1 23 | right -= 1 24 | } 25 | } 26 | } 27 | 28 | /* 29 | Input: nums = [1,2,3,4,5,6,7], k = 3 30 | Output: [5,6,7,1,2,3,4] 31 | 32 | 33 | 1,2,3,4, 5,6,7 34 | 35 | 1,2,3,4, 7,6,5 36 | 37 | 7,6,5, 4,3,2,1 38 | 39 | 40 | 41 | >5,6,7, 1,2,3,4 42 | 43 | >5,6,7,1,2,3,4 44 | */ 45 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/1_Two_Sum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 | var numIdxMap = [Int:Int]() 4 | for i in 0.. ListNode? { 12 | var dummyHead = ListNode(Int.max, head) 13 | var prev: ListNode? 14 | var current: ListNode? = dummyHead 15 | while current != nil { 16 | if current!.val == val { 17 | prev?.next = current?.next 18 | } else { 19 | prev = current 20 | } 21 | current = current?.next 22 | } 23 | return dummyHead.next 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/226_Invert_Binary_Tree.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * public var val: Int 7 | * public var left: TreeNode? 8 | * public var right: TreeNode? 9 | * public init(_ val: Int) { 10 | * self.val = val 11 | * self.left = nil 12 | * self.right = nil 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | func invertTree(_ root: TreeNode?) -> TreeNode? { 18 | guard let r = root else { 19 | return nil 20 | } 21 | 22 | var left = self.invertTree(r.left) 23 | var right = self.invertTree(r.right) 24 | r.left = right 25 | r.right = left 26 | return r 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/230_Kth_Smallest_Element_in_a_BST.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * public var val: Int 7 | * public var left: TreeNode? 8 | * public var right: TreeNode? 9 | * public init(_ val: Int) { 10 | * self.val = val 11 | * self.left = nil 12 | * self.right = nil 13 | * } 14 | * } 15 | */ 16 | 17 | // Brute force solution. Time and Space both O(n). It perfofms an exustive search through the whole BST 18 | class Solution { 19 | func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int { 20 | return inorderTraversal(root)[k - 1] 21 | } 22 | 23 | func inorderTraversal(_ root: TreeNode?) -> [Int] { 24 | guard let node = root else { return []} 25 | let leftNodes = inorderTraversal(node.left) 26 | let rightNode = inorderTraversal(node.right) 27 | return leftNodes + [node.val] + rightNode 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/242_Valid_Anagram.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func isAnagram(_ s: String, _ t: String) -> Bool { 5 | guard (s.count == t.count) else { 6 | return false 7 | } 8 | var sDict = [Character:Int]() 9 | var tDict = [Character:Int]() 10 | for char in s { 11 | if let count = sDict[char] { 12 | sDict[char]! += 1 13 | } else { 14 | sDict[char] = 1 15 | } 16 | } 17 | for char in t { 18 | if let count = tDict[char] { 19 | tDict[char]! += 1 20 | } else { 21 | tDict[char] = 1 22 | } 23 | } 24 | return sDict == tDict 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/249_Group_Shifted_Strings.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func groupStrings(_ strings: [String]) -> [[String]] { 3 | var groupMap = [String:[String]]() 4 | strings.forEach { string in 5 | let patttern = getPatternKey(string) 6 | groupMap[patttern, default: [String]()] += [string] 7 | } 8 | return Array(groupMap.values) 9 | } 10 | 11 | func getPatternKey(_ string: String) -> String { 12 | let asciiValues = string.unicodeScalars.map({ Int($0.value) }) 13 | let diffValue = asciiValues.map({ (26 + $0 - asciiValues[0]) % 26 }) 14 | return diffValue.reduce("", { $0 + " \($1)" }) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/340_Longest_Substring_with_At_Most_K_Distinct_Characters.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func lengthOfLongestSubstringKDistinct(_ s: String, _ k: Int) -> Int { 4 | guard k > 0 else { 5 | return 0 6 | } 7 | var sArr = Array(s) 8 | var counter = [Character:Int]() 9 | var maxLen = 0 10 | var (left, right) = (0, 0) 11 | while right < sArr.count { 12 | if counter[sArr[right]] != nil || counter.keys.count < k { 13 | counter[sArr[right], default: 0] += 1 14 | maxLen = max(maxLen, right - left + 1) 15 | right += 1 16 | } else { 17 | counter[sArr[left], default: 0] -= 1 18 | if counter[sArr[left]] == 0 { 19 | counter.removeValue(forKey: sArr[left]) 20 | } 21 | left += 1 22 | } 23 | } 24 | return maxLen 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/346_Moving_Average_from_Data_Stream.swift: -------------------------------------------------------------------------------- 1 | 2 | class MovingAverage { 3 | 4 | var queue = [Int]() 5 | var currentSum = 0 6 | let size: Int 7 | init(_ size: Int) { 8 | self.size = size 9 | } 10 | 11 | func next(_ val: Int) -> Double { 12 | queue.append(val) 13 | currentSum += val 14 | if queue.count <= size { 15 | return Double(currentSum) / Double(queue.count) 16 | } else { 17 | let first = queue.removeFirst() 18 | currentSum -= first 19 | return Double(currentSum) / Double(queue.count) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/366_Find_Leaves_of_Binary_Tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findLeaves(_ root: TreeNode?) -> [[Int]] { 3 | var result = [[Int]]() 4 | getHeight(root, &result) 5 | return result 6 | } 7 | 8 | @discardableResult 9 | func getHeight(_ root: TreeNode?, _ leaves: inout [[Int]]) -> Int { 10 | guard let root = root else { 11 | return -1 12 | } 13 | 14 | let (left, right) = (getHeight(root.left, &leaves), getHeight(root.right, &leaves)) 15 | let height = max(left, right) + 1 16 | if height < leaves.count { 17 | leaves[height].append(root.val) 18 | } else { 19 | leaves.append([root.val]) 20 | } 21 | return height 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/412_Fizz_Buzz.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func fizzBuzz(_ n: Int) -> [String] { 3 | var stringArr: [String] = [] 4 | 5 | for index in 1...n { 6 | if ((index % 3) == 0) && ((index % 5) == 0) { 7 | stringArr.append("FizzBuzz") 8 | print("FizzBuzz") 9 | } else if ((index % 3) == 0) { 10 | stringArr.append("Fizz") 11 | print("Fizz") 12 | } else if ((index % 5) == 0) { 13 | stringArr.append("Buzz") 14 | print("Buzz") 15 | } else { 16 | stringArr.append(String(index)) 17 | print(index) 18 | } 19 | } 20 | 21 | return stringArr 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/443_String_Compression.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func compress(_ chars: inout [Character]) -> Int { 4 | guard chars.count > 0 else { 5 | return 0 6 | } 7 | 8 | var (rPtr, wPtr) = (0, 0) 9 | while rPtr < chars.count { 10 | var (prevChar, frequency) = (chars[rPtr], 0) 11 | while rPtr < chars.count && prevChar == chars[rPtr] { 12 | frequency += 1 13 | rPtr += 1 14 | } 15 | chars[wPtr] = prevChar 16 | wPtr += 1 17 | if frequency > 1 { 18 | for num in Array(String(frequency)) { 19 | chars[wPtr] = num 20 | wPtr += 1 21 | } 22 | } 23 | } 24 | return wPtr 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/476_Number_Complement.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findComplement(_ num: Int) -> Int { 3 | var strNum = String(num, radix: 2) 4 | var strComplement = "" 5 | 6 | for index in 0.. [Int] { 4 | var nextGreater = Array(repeating: -1, count: nums.count), stack = [Int]() 5 | let len = nums.count 6 | for i in stride(from: 2 * len - 1, through: 0, by: -1) { 7 | while !stack.isEmpty && stack.last! <= nums[i % len] { 8 | stack.removeLast() 9 | } 10 | if !stack.isEmpty && i < len { 11 | nextGreater[i] = stack.last! 12 | } 13 | stack.append(nums[i % len]) 14 | } 15 | return nextGreater 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/50_Pow(x, n).swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | // Video: https://www.youtube.com/watch?v=g9YQyYi4IQQ 4 | class Solution { 5 | func myPow(_ x: Double, _ n: Int) -> Double { 6 | if n == 0 { 7 | return 1 8 | } 9 | if n < 0 { 10 | return 1 / myPow(x, -n) 11 | } 12 | let half = myPow(x, n/2) 13 | if n % 2 == 0 { 14 | return half * half 15 | } else { 16 | return x * half * half 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/515_Find_Largest_Value_in_Each_Tree_Row.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func largestValues(_ root: TreeNode?) -> [Int] { 3 | guard let root = root else { 4 | return [] 5 | } 6 | var result = [Int](), queue = [TreeNode]() 7 | queue.append(root) 8 | while !queue.isEmpty { 9 | var currentMax = Int.min 10 | let currentLevelLength = queue.count 11 | for i in 0.. Int { 17 | let randWeight = Int.random(in: 1...prefixSum.last!) 18 | var left = 0, right = prefixSum.count - 1 19 | while left < right { 20 | let mid = left + (right - left) / 2 21 | if prefixSum[mid] < randWeight { 22 | left = mid + 1 23 | } else { 24 | right = mid 25 | } 26 | } 27 | 28 | return left 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/532_K-diff_Pairs_in_an_Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findPairs(_ nums: [Int], _ k: Int) -> Int { 3 | var counter = [Int:Int]() 4 | for num in nums { 5 | counter[num, default: 0] += 1 6 | } 7 | 8 | var result = 0 9 | for (key, value) in counter { 10 | if k == 0 { 11 | if value > 1 { 12 | result += 1 13 | } 14 | } else if let count = counter[key + k] { 15 | result += 1 16 | } 17 | } 18 | return result 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/547_Friend_Circles.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func findCircleNum(_ M: [[Int]]) -> Int { 3 | var visited = Set() 4 | var circleCount = 0 5 | for i in 0.., _ node: Int) { 15 | for (neighbor, friendValue) in M[node].enumerated() { 16 | if friendValue == 1 && !visited.contains(neighbor) { 17 | visited.insert(neighbor) 18 | DFS(M, &visited, neighbor) 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/60_Permutation_Sequence.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func getPermutation(_ n: Int, _ k: Int) -> String { 3 | let factorialDict: [Int:Int] = [1: 1, 2: 2, 3: 6, 4: 24, 5: 120, 6: 720, 7: 5040, 8: 40320, 9: 362880] 4 | var digits = Array(1...n) 5 | 6 | var numbers = [String]() 7 | var currentK = k - 1 8 | 9 | while digits.count > 1 { 10 | guard let nextPurmutationCount = factorialDict[n - numbers.count - 1] else {break} 11 | var chosenDigitIndex = 0 12 | (chosenDigitIndex, currentK) = currentK.quotientAndRemainder(dividingBy: nextPurmutationCount) 13 | numbers.append(String(digits.remove(at: chosenDigitIndex))) 14 | } 15 | numbers.append(String(digits[0])) 16 | return numbers.joined(separator: "") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/621_Task_Scheduler.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/636_Exclusive_Time_of_Functions.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func exclusiveTime(_ n: Int, _ logs: [String]) -> [Int] { 4 | var funcTimeMap = Array(repeating: 0, count: n) 5 | var funcStack = [Int]() 6 | var prevTime = 0 7 | for log in logs { 8 | let logItem = log.split(separator: ":") 9 | let (funct, type, tim) = (Int(logItem[0]), logItem[1], Int(logItem[2])) 10 | guard let function = funct, let time = tim else {continue} 11 | if type == "start" { 12 | if funcStack.count > 0 { 13 | funcTimeMap[funcStack.last!] += (time - prevTime) 14 | } 15 | prevTime = time 16 | funcStack.append(function) 17 | } else { 18 | funcTimeMap[funcStack.popLast()!] += (time - prevTime + 1) 19 | prevTime = time + 1 20 | } 21 | } 22 | return funcTimeMap 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/63_Unique_Paths_II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int { 3 | var dp = Array(repeating: Array(repeating: 0, count: obstacleGrid[0].count + 1), count: obstacleGrid.count + 1) 4 | for i in 0.. Int { 5 | let row = grid.count + 1 6 | let column = grid[0].count + 1 7 | var dp = Array(repeating: [Int](repeating: Int.max, count: column), count: row) 8 | for i in 1 ..< row { 9 | for j in 1 ..< column { 10 | var up = dp[i - 1][j] 11 | var left = dp[i][j - 1] 12 | var minNum = min(up, left) 13 | if up == Int.max && left == Int.max { 14 | minNum = 0 15 | } 16 | var num = minNum + grid[i - 1][j - 1] 17 | dp[i][j] = num 18 | } 19 | } 20 | return dp[row - 1][column - 1] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/67_Add_Binary.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func addBinary(_ a: String, _ b: String) -> String { 3 | guard var x = Int(a, radix: 2), var y = Int(b, radix: 2) else { 4 | return "0" 5 | } 6 | while y > 0 { 7 | let answer = x ^ y 8 | let carry = (x & y) << 1 9 | (x, y) = (answer, carry) 10 | } 11 | let answer = String(x, radix: 2) 12 | return answer 13 | } 14 | } 15 | /* 16 | Input: 17 | a = "11" >> 3 18 | b = "1" >> 1 19 | 20 | Output: "100" >> 4 21 | 22 | 23 | 24 | Input: 25 | a = "1010" >> 10 26 | b = "1011" >> 11 27 | 28 | Output: "10101" >> 21 29 | */ 30 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/71_Simplify_Path.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func simplifyPath(_ path: String) -> String { 5 | var stack = [String]() 6 | let pathComponent = path.split(separator: "/") 7 | for component in pathComponent { 8 | if component == "" || component == "." || (stack.isEmpty && component == "..") { 9 | continue 10 | } 11 | if component == ".." { 12 | stack.removeLast() 13 | continue 14 | } 15 | stack.append(String(component)) 16 | } 17 | return stack.isEmpty ? "/" : stack.reduce("") { $0 + "/" + $1 } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/735_Asteroid_Collision.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func asteroidCollision(_ asteroids: [Int]) -> [Int] { 4 | var stack = [Int]() 5 | for item in asteroids { 6 | if item > 0 { 7 | stack.append(item) 8 | } else { 9 | while !stack.isEmpty && stack.last! > 0 && stack.last! < abs(item) { 10 | stack.removeLast() 11 | } 12 | if stack.isEmpty || stack.last! < 0 { 13 | stack.append(item) 14 | } else if stack.last! == -item { 15 | stack.removeLast() 16 | } 17 | } 18 | } 19 | return stack 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/791_Custom_Sort_String.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func customSortString(_ S: String, _ T: String) -> String { 4 | var tCounter = [Character: Int]() 5 | for character in T { 6 | tCounter[character, default: 0] += 1 7 | } 8 | 9 | var result = "" 10 | for character in S { 11 | if var count = tCounter[character] { 12 | while count > 0 { 13 | result += String(character) 14 | count -= 1 15 | } 16 | tCounter.removeValue(forKey: character) 17 | } 18 | } 19 | 20 | for character in tCounter.keys { 21 | if var count = tCounter[character] { 22 | while count > 0 { 23 | result += String(character) 24 | count -= 1 25 | } 26 | } 27 | } 28 | return result 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/852_Peak_Index_in_a_Mountain_Array.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func peakIndexInMountainArray(_ A: [Int]) -> Int { 5 | var leftIdx = 0, rightIdx = A.count - 1 6 | while leftIdx < rightIdx { 7 | var midIdx = leftIdx + Int((rightIdx - leftIdx) / 2) 8 | if A[midIdx] < A[midIdx + 1] { 9 | leftIdx = midIdx + 1 10 | } else { 11 | rightIdx = midIdx 12 | } 13 | } 14 | return leftIdx 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/853_Car_Fleet.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func carFleet(_ target: Int, _ position: [Int], _ speed: [Int]) -> Int { 3 | var (positionSpeedMap, sortedPositions, fleetCount, timeLastCarReached) = ([Int:Int](), position.sorted { $0 > $1 }, 0, -Double.infinity) 4 | for i in 0.. timeLastCarReached { 12 | fleetCount += 1 13 | timeLastCarReached = arrivalTime 14 | } 15 | } 16 | 17 | return fleetCount 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/855_Exam_Room.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class ExamRoom { 4 | var n = 1 5 | var occupiedSeates = Set() 6 | var maxIntervalHeap = [Int]() // A max Heap of interval value 7 | var maxIntervalRangeMap = [Int:[(Int, Int)]]() // key = max interval, value = lower and upper range of the interval 8 | 9 | init(_ N: Int) { 10 | self.n = N 11 | } 12 | 13 | func seat() -> Int { 14 | if occupiedSeates.count <= 0 { 15 | occupiedSeates.insert(0) 16 | return 0 17 | } else { 18 | 19 | } 20 | } 21 | 22 | func leave(_ p: Int) { 23 | occupiedSeates.remove(p) 24 | 25 | } 26 | } 27 | 28 | /** 29 | * Your ExamRoom object will be instantiated and called as such: 30 | * let obj = ExamRoom(N) 31 | * let ret_1: Int = obj.seat() 32 | * obj.leave(p) 33 | */ 34 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/896_Monotonic_Array.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | class Solution { 3 | func isMonotonic(_ A: [Int]) -> Bool { 4 | guard A.count > 2 else { 5 | return true 6 | } 7 | var (isIncreasing, isDecreasing) = (true, true) 8 | 9 | for i in 2..= A[i - 1] && A[i - 1] >= A[i]) { 20 | continue 21 | } else { 22 | isDecreasing = false 23 | break 24 | } 25 | } 26 | 27 | return (isIncreasing || isDecreasing) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/900_RLE_Iterator.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class RLEIterator { 4 | 5 | var A = [Int]() 6 | var current_counter_index = 0 7 | 8 | init(_ A: [Int]) { 9 | self.A = A 10 | } 11 | 12 | func next(_ n: Int) -> Int { 13 | guard current_counter_index < A.count - 1 else { 14 | return -1 15 | } 16 | var currentN = n 17 | 18 | while current_counter_index < A.count && currentN > A[current_counter_index] { 19 | currentN -= A[current_counter_index] 20 | current_counter_index += 2 21 | } 22 | 23 | if current_counter_index < A.count { 24 | A[current_counter_index] -= currentN 25 | return A[current_counter_index + 1] 26 | } 27 | 28 | return -1 29 | } 30 | } 31 | 32 | /** 33 | * Your RLEIterator object will be instantiated and called as such: 34 | * let obj = RLEIterator(A) 35 | * let ret_1: Int = obj.next(n) 36 | */ 37 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/91_Decode_Ways.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | class Solution { 4 | func numDecodings(_ s: String) -> Int { 5 | let sArray = Array(s) 6 | let sLen = sArray.count 7 | guard sLen > 0 else { 8 | return 0 9 | } 10 | var dp = Array(repeating: 0, count: sLen + 1) 11 | dp[0] = 1 12 | for i in 1.. 09 { 17 | dp[i] += dp[i - 2] 18 | } 19 | } 20 | return dp.last! 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/954_Array_of_Doubled_Pairs.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | func canReorderDoubled(_ arr: [Int]) -> Bool { 3 | let sortedArray = arr.sorted { abs($0) < abs($1) } 4 | var counterMap = [Int:Int]() 5 | sortedArray.forEach { item in 6 | counterMap[item, default: 0] += 1 7 | } 8 | 9 | for item in sortedArray { 10 | if counterMap[item]! == 0 { 11 | continue 12 | } else { 13 | counterMap[item]! -= 1 14 | } 15 | if let counter = counterMap[2 * item] { 16 | if counter == 0 { 17 | return false 18 | } else { 19 | counterMap[2 * item]! -= 1 20 | } 21 | } else { 22 | return false 23 | } 24 | } 25 | return true 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC/DS_ALGO_PRAC.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /leetcode.com/swift/DS_ALGO_PRAC/DS_ALGO_PRAC.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /leetcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/partho-maple/coding-interview-gym/20ae1a048eddbc9a32c819cf61258e2b57572f05/leetcode.png --------------------------------------------------------------------------------