├── 3sum.py ├── 4Sum.js ├── 4Sum.py ├── Add_Two_Numbers_II.cpp ├── Add_Two_Numbers_II.java ├── Add_Two_Numbers_II.js ├── Add_Two_Numbers_II.py ├── All_Nodes_Distance_K_in_Binary_Tree.cpp ├── All_Nodes_Distance_K_in_Binary_Tree.java ├── All_Nodes_Distance_K_in_Binary_Tree.js ├── All_Nodes_Distance_K_in_Binary_Tree.py ├── All_Possible_Full_Binary_Trees.cpp ├── All_Possible_Full_Binary_Trees.java ├── All_Possible_Full_Binary_Trees.js ├── All_Possible_Full_Binary_Trees.py ├── Amount_of_Time_for_Binary_Tree_to_Be_Infected.cpp ├── Amount_of_Time_for_Binary_Tree_to_Be_Infected.java ├── Amount_of_Time_for_Binary_Tree_to_Be_Infected.py ├── Arithmetic_Slices_II_Subsequence.cpp ├── Arithmetic_Slices_II_Subsequence.java ├── Arithmetic_Slices_II_Subsequence.js ├── Arithmetic_Slices_II_Subsequence.py ├── Assign_Cookies.cpp ├── Assign_Cookies.java ├── Assign_Cookies.js ├── Assign_Cookies.py ├── Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.cpp ├── Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.java ├── Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.js ├── Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py ├── Binary_Tree_Zigzag_Level_Order_Traversal.cpp ├── Binary_Tree_Zigzag_Level_Order_Traversal.java ├── Binary_Tree_Zigzag_Level_Order_Traversal.js ├── Binary_Tree_Zigzag_Level_Order_Traversal.py ├── Bitwise AND of Numbers Range.cpp ├── Bitwise AND of Numbers Range.java ├── Bitwise AND of Numbers Range.js ├── Bitwise AND of Numbers Range.py ├── Buddy_Strings.cpp ├── Buddy_Strings.java ├── Buddy_Strings.js ├── Buddy_Strings.py ├── Champagne_Tower_1d.cpp ├── Champagne_Tower_1d.java ├── Champagne_Tower_1d.js ├── Champagne_Tower_1d.py ├── Champagne_Tower_2d.cpp ├── Champagne_Tower_2d.java ├── Champagne_Tower_2d.js ├── Champagne_Tower_2d.py ├── Check_if_There_is_a_Valid_Partition_For_The_Array.cpp ├── Check_if_There_is_a_Valid_Partition_For_The_Array.java ├── Check_if_There_is_a_Valid_Partition_For_The_Array.js ├── Check_if_There_is_a_Valid_Partition_For_The_Array.py ├── Combinations.cpp ├── Combinations.java ├── Combinations.js ├── Combinations.py ├── Convert_an_Array_Into_a_2D_Array_With_Conditions.cpp ├── Convert_an_Array_Into_a_2D_Array_With_Conditions.java ├── Convert_an_Array_Into_a_2D_Array_With_Conditions.js ├── Convert_an_Array_Into_a_2D_Array_With_Conditions.py ├── Copy_List_with_Random_Pointer.cpp ├── Copy_List_with_Random_Pointer.java ├── Copy_List_with_Random_Pointer.js ├── Copy_List_with_Random_Pointer.py ├── Count_All_Valid_Pickup_and_Delivery_Options.cpp ├── Count_All_Valid_Pickup_and_Delivery_Options.java ├── Count_All_Valid_Pickup_and_Delivery_Options.js ├── Count_All_Valid_Pickup_and_Delivery_Options.py ├── Count_Negative_Numbers_in_a_Sorted_Matrix.cpp ├── Count_Negative_Numbers_in_a_Sorted_Matrix.java ├── Count_Negative_Numbers_in_a_Sorted_Matrix.js ├── Count_Negative_Numbers_in_a_Sorted_Matrix.py ├── Daily_Temperatures.cpp ├── Daily_Temperatures.java ├── Daily_Temperatures.js ├── Daily_Temperatures.py ├── Decoded_String_at_Index.cpp ├── Decoded_String_at_Index.java ├── Decoded_String_at_Index.py ├── Design_HashMap.cpp ├── Design_HashMap.java ├── Design_HashMap.js ├── Design_HashMap.py ├── Determine_if_String_Halves_Are_Alike.cpp ├── Determine_if_String_Halves_Are_Alike.java ├── Determine_if_String_Halves_Are_Alike.js ├── Determine_if_String_Halves_Are_Alike.py ├── Determine_if_Two_Strings_Are_Close.cpp ├── Determine_if_Two_Strings_Are_Close.java ├── Determine_if_Two_Strings_Are_Close.js ├── Determine_if_Two_Strings_Are_Close.py ├── Diameter_of_Binary_Tree.cpp ├── Diameter_of_Binary_Tree.java ├── Diameter_of_Binary_Tree.js ├── Diameter_of_Binary_Tree.py ├── Divide_Array_Into_Arrays_With_Max_Difference.cpp ├── Divide_Array_Into_Arrays_With_Max_Difference.java ├── Divide_Array_Into_Arrays_With_Max_Difference.js ├── Divide_Array_Into_Arrays_With_Max_Difference.py ├── Equa_Row_and_Column_Pairs.py ├── Equal_Row_and_Column_Pairs.cpp ├── Equal_Row_and_Column_Pairs.java ├── Equal_Row_and_Column_Pairs.js ├── Equal_Row_and_Column_Pairs.py ├── Evaluate_Reverse_Polish_Notation.cpp ├── Evaluate_Reverse_Polish_Notation.java ├── Evaluate_Reverse_Polish_Notation.js ├── Evaluate_Reverse_Polish_Notation.py ├── Even_Odd_Tree.cpp ├── Even_Odd_Tree.java ├── Even_Odd_Tree.js ├── Even_Odd_Tree.py ├── Excel_Sheet_Column_Title.cpp ├── Excel_Sheet_Column_Title.java ├── Excel_Sheet_Column_Title.js ├── Excel_Sheet_Column_Title.py ├── Extra_Characters_in_a_String.cpp ├── Extra_Characters_in_a_String.java ├── Extra_Characters_in_a_String.js ├── Extra_Characters_in_a_String.py ├── Extra_Characters_in_a_String_trie.cpp ├── Extra_Characters_in_a_String_trie.java ├── Extra_Characters_in_a_String_trie.js ├── Extra_Characters_in_a_String_trie.py ├── Fair_Distribution_of_Cookies.cpp ├── Fair_Distribution_of_Cookies.java ├── Fair_Distribution_of_Cookies.js ├── Fair_Distribution_of_Cookies.py ├── Find First Palindromic String in the Array.cpp ├── Find First Palindromic String in the Array.java ├── Find First Palindromic String in the Array.js ├── Find First Palindromic String in the Array.py ├── Find the Town Judge.cpp ├── Find the Town Judge.java ├── Find the Town Judge.js ├── Find the Town Judge.py ├── Find_Bottom_Left_Tree_Value.cpp ├── Find_Bottom_Left_Tree_Value.java ├── Find_Bottom_Left_Tree_Value.js ├── Find_Bottom_Left_Tree_Value.py ├── Find_Eventual_Safe_States.cpp ├── Find_Eventual_Safe_States.java ├── Find_Eventual_Safe_States.js ├── Find_Eventual_Safe_States.py ├── Find_K_Pairs_with_Smallest_Sums.cpp ├── Find_K_Pairs_with_Smallest_Sums.java ├── Find_K_Pairs_with_Smallest_Sums.js ├── Find_K_Pairs_with_Smallest_Sums.py ├── Find_Players_With_Zero_or_One_Losses.cpp ├── Find_Players_With_Zero_or_One_Losses.java ├── Find_Players_With_Zero_or_One_Losses.js ├── Find_Players_With_Zero_or_One_Losses.py ├── Find_Smallest_Letter_Greater_Than_Target.cpp ├── Find_Smallest_Letter_Greater_Than_Target.java ├── Find_Smallest_Letter_Greater_Than_Target.js ├── Find_Smallest_Letter_Greater_Than_Target.py ├── Find_the_Difference.cpp ├── Find_the_Difference.java ├── Find_the_Difference.js ├── Find_the_Difference.py ├── Find_the_Duplicate_Number.cpp ├── Find_the_Duplicate_Number.java ├── Find_the_Duplicate_Number.js ├── Find_the_Duplicate_Number.py ├── Find_the_Highest_Altitude.cpp ├── Find_the_Highest_Altitude.java ├── Find_the_Highest_Altitude.js ├── Find_the_Highest_Altitude.py ├── Find_the_Middle_Index_in_Array.cpp ├── Find_the_Middle_Index_in_Array.java ├── Find_the_Middle_Index_in_Array.js ├── Find_the_Middle_Index_in_Array.py ├── Frog_Jump.cpp ├── Frog_Jump.java ├── Frog_Jump.js ├── Frog_Jump.py ├── Furthest Building You Can Reach.cpp ├── Furthest Building You Can Reach.java ├── Furthest Building You Can Reach.py ├── Group_the_People_Given_the_Group_Size They_Belong_To.cpp ├── Group_the_People_Given_the_Group_Size They_Belong_To.java ├── Group_the_People_Given_the_Group_Size They_Belong_To.js ├── Group_the_People_Given_the_Group_Size They_Belong_To.py ├── House_Robber.cpp ├── House_Robber.java ├── House_Robber.js ├── House_Robber.py ├── House_Robber_III.cpp ├── House_Robber_III.java ├── House_Robber_III.js ├── House_Robber_III.py ├── Implement_Queue_using_Stacks.cpp ├── Implement_Queue_using_Stacks.java ├── Implement_Queue_using_Stacks.js ├── Implement_Queue_using_Stacks.py ├── Implement_Stack_using_Queues_one.cpp ├── Implement_Stack_using_Queues_one.java ├── Implement_Stack_using_Queues_one.js ├── Implement_Stack_using_Queues_one.py ├── Implement_Stack_using_Queues_two.cpp ├── Implement_Stack_using_Queues_two.java ├── Implement_Stack_using_Queues_two.js ├── Implement_Stack_using_Queues_two.py ├── Insert_Delete_GetRandom_O(1).cpp ├── Insert_Delete_GetRandom_O(1).java ├── Insert_Delete_GetRandom_O(1).js ├── Insert_Delete_GetRandom_O(1).py ├── Integer_Break.cpp ├── Integer_Break.java ├── Integer_Break.js ├── Integer_Break.py ├── K_Radius_Subarray_Averages.cpp ├── K_Radius_Subarray_Averages.java ├── K_Radius_Subarray_Averages.js ├── K_Radius_Subarray_Averages.py ├── Knight_Probability_in_Chessboard.java ├── Knight_Probability_in_Chessboard.js ├── Knight_Probability_in_Chessboard.py ├── Kth_Largest_Element_in_a_Stream.cpp ├── Kth_Largest_Element_in_a_Stream.java ├── Kth_Largest_Element_in_a_Stream.py ├── Kth_largest_element_in_a_stream.cpp ├── Kth_largest_element_in_a_stream.java ├── Kth_largest_element_in_a_stream.js ├── Kth_largest_element_in_a_stream.py ├── Kth_largest_element_in_an_array.cpp ├── Kth_largest_element_in_an_array.java ├── Kth_largest_element_in_an_array.js ├── Kth_largest_element_in_an_array.py ├── LRU Cache.cpp ├── LRU_Cache.java ├── LRU_Cache.js ├── LRU_Cache.py ├── Largest_Substring_Between_Two_Equal_Characters.cpp ├── Largest_Substring_Between_Two_Equal_Characters.java ├── Largest_Substring_Between_Two_Equal_Characters.js ├── Largest_Substring_Between_Two_Equal_Characters.py ├── Leaf-Similar_Trees.cpp ├── Leaf-Similar_Trees.java ├── Leaf-Similar_Trees.js ├── Leaf-Similar_Trees.py ├── Letter_Combinations_of_a_Phone_Number.cpp ├── Letter_Combinations_of_a_Phone_Number.java ├── Letter_Combinations_of_a_Phone_Number.js ├── Letter_Combinations_of_a_Phone_Number.py ├── Longest_Arithmetic_Subsequence.cpp ├── Longest_Arithmetic_Subsequence.java ├── Longest_Arithmetic_Subsequence.js ├── Longest_Arithmetic_Subsequence.py ├── Longest_Arithmetic_Subsequence_of_Given_Difference.cpp ├── Longest_Arithmetic_Subsequence_of_Given_Difference.java ├── Longest_Arithmetic_Subsequence_of_Given_Difference.js ├── Longest_Arithmetic_Subsequence_of_Given_Difference.py ├── Longest_Common_Subsequence.cpp ├── Longest_Common_Subsequence.java ├── Longest_Common_Subsequence.js ├── Longest_Common_Subsequence.py ├── Longest_Increasing_Subsequence.cpp ├── Longest_Increasing_Subsequence.java ├── Longest_Increasing_Subsequence.js ├── Longest_Increasing_Subsequence.py ├── Longest_String_Chain.cpp ├── Longest_String_Chain.java ├── Longest_String_Chain.js ├── Longest_String_Chain.py ├── Longest_Subarray_of_1's_After_Deleting_One_Element.cpp ├── Longest_Subarray_of_1's_After_Deleting_One_Element.java ├── Longest_Subarray_of_1's_After_Deleting_One_Element.js ├── Longest_Subarray_of_1's_After_Deleting_One_Element.py ├── Majority_Element_II.cpp ├── Majority_Element_II.java ├── Majority_Element_II.js ├── Majority_Element_II.py ├── Make_Array_Strictly_Increasing.cpp ├── Make_Array_Strictly_Increasing.java ├── Make_Array_Strictly_Increasing.js ├── Make_Array_Strictly_Increasing.py ├── Max_Dot_Product_of_Two_Subsequences.cpp ├── Max_Dot_Product_of_Two_Subsequences.java ├── Max_Dot_Product_of_Two_Subsequences.js ├── Max_Dot_Product_of_Two_Subsequences.py ├── Maximize_the_Confusion_of_an_Exam.cpp ├── Maximize_the_Confusion_of_an_Exam.java ├── Maximize_the_Confusion_of_an_Exam.js ├── Maximize_the_Confusion_of_an_Exam.py ├── Maximum_Difference_Between_Node_and_Ancestor.cpp ├── Maximum_Difference_Between_Node_and_Ancestor.java ├── Maximum_Difference_Between_Node_and_Ancestor.js ├── Maximum_Difference_Between_Node_and_Ancestor.py ├── Maximum_Length_of_Pair_Chain.cpp ├── Maximum_Length_of_Pair_Chain.java ├── Maximum_Length_of_Pair_Chain.js ├── Maximum_Length_of_Pair_Chain.py ├── Maximum_Length_of_a_Concatenated_String_with_Unique_Characters.cpp ├── Maximum_Length_of_a_Concatenated_String_with_Unique_Characters.java ├── Maximum_Length_of_a_Concatenated_String_with_Unique_Characters.js ├── Maximum_Length_of_a_Concatenated_String_with_Unique_Characters.py ├── Maximum_Level_Sum_of_a_Binary_Tree.cpp ├── Maximum_Level_Sum_of_a_Binary_Tree.java ├── Maximum_Level_Sum_of_a_Binary_Tree.js ├── Maximum_Level_Sum_of_a_Binary_Tree.py ├── Maximum_Number_of_Achievable_Transfer_Requests.cpp ├── Maximum_Number_of_Achievable_Transfer_Requests.java ├── Maximum_Number_of_Achievable_Transfer_Requests.js ├── Maximum_Number_of_Achievable_Transfer_Requests.py ├── Maximum_Number_of_Events_That_Can_Be_Attended_II.cpp ├── Maximum_Number_of_Events_That_Can_Be_Attended_II.java ├── Maximum_Number_of_Events_That_Can_Be_Attended_II.js ├── Maximum_Number_of_Events_That_Can_Be_Attended_II.py ├── Maximum_Profit_in_Job_Scheduling.cpp ├── Maximum_Profit_in_Job_Scheduling.java ├── Maximum_Profit_in_Job_Scheduling.py ├── Maximum_Running_Time_of_N_Computers.cpp ├── Maximum_Running_Time_of_N_Computers.java ├── Maximum_Running_Time_of_N_Computers.js ├── Maximum_Running_Time_of_N_Computers.py ├── Min_Cost_to_Connect_All_Points.cpp ├── Min_Cost_to_Connect_All_Points.java ├── Min_Cost_to_Connect_All_Points.js ├── Min_Cost_to_Connect_All_Points.py ├── Minimize_the_Maximum_Difference_of_Pairs.cpp ├── Minimize_the_Maximum_Difference_of_Pairs.java ├── Minimize_the_Maximum_Difference_of_Pairs.js ├── Minimize_the_Maximum_Difference_of_Pairs.py ├── Minimum Window Substring.cpp ├── Minimum Window Substring.java ├── Minimum Window Substring.js ├── Minimum Window Substring.py ├── Minimum_ASCII_Delete_Sum_for_Two_Strings.cpp ├── Minimum_ASCII_Delete_Sum_for_Two_Strings.java ├── Minimum_ASCII_Delete_Sum_for_Two_Strings.js ├── Minimum_ASCII_Delete_Sum_for_Two_Strings.py ├── Minimum_Absolute_Difference_in_BST.cpp ├── Minimum_Absolute_Difference_in_BST.java ├── Minimum_Absolute_Difference_in_BST.js ├── Minimum_Absolute_Difference_in_BST.py ├── Minimum_Deletions_to_Make_Character_Frequencies_Unique.cpp ├── Minimum_Deletions_to_Make_Character_Frequencies_Unique.java ├── Minimum_Deletions_to_Make_Character_Frequencies_Unique.js ├── Minimum_Deletions_to_Make_Character_Frequencies_Unique.py ├── Minimum_Depth_of_Binary_Tree.cpp ├── Minimum_Depth_of_Binary_Tree.java ├── Minimum_Depth_of_Binary_Tree.js ├── Minimum_Depth_of_Binary_Tree.py ├── Minimum_Depth_of_Binary_Tree_bfs.cpp ├── Minimum_Depth_of_Binary_Tree_bfs.java ├── Minimum_Depth_of_Binary_Tree_bfs.js ├── Minimum_Depth_of_Binary_Tree_bfs.py ├── Minimum_Falling_Path_Sum.cpp ├── Minimum_Falling_Path_Sum.java ├── Minimum_Falling_Path_Sum.js ├── Minimum_Falling_Path_Sum.py ├── Minimum_Number_of_Operations_to_Make_Array_Continuous.cpp ├── Minimum_Number_of_Operations_to_Make_Array_Continuous.java ├── Minimum_Number_of_Operations_to_Make_Array_Continuous.js ├── Minimum_Number_of_Operations_to_Make_Array_Continuous.py ├── Minimum_Number_of_Operations_to_Make_Array_Empty.cpp ├── Minimum_Number_of_Operations_to_Make_Array_Empty.java ├── Minimum_Number_of_Operations_to_Make_Array_Empty.js ├── Minimum_Number_of_Operations_to_Make_Array_Empty.py ├── Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.cpp ├── Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.java ├── Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.js ├── Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.py ├── Minimum_Number_of_Taps_to_Open_to_Water_a_Garden.cpp ├── Minimum_Number_of_Taps_to_Open_to_Water_a_Garden.java ├── Minimum_Number_of_Taps_to_Open_to_Water_a_Garden.js ├── Minimum_Number_of_Taps_to_Open_to_Water_a_Garden.py ├── Minimum_Operations_to_Reduce_X_to_Zero.cpp ├── Minimum_Operations_to_Reduce_X_to_Zero.java ├── Minimum_Operations_to_Reduce_X_to_Zero.js ├── Minimum_Operations_to_Reduce_X_to_Zero.py ├── Minimum_Penalty_for_a_Shop.cpp ├── Minimum_Penalty_for_a_Shop.java ├── Minimum_Penalty_for_a_Shop.js ├── Minimum_Penalty_for_a_Shop.py ├── Minimum_Replacements_to_Sort_the_Array.cpp ├── Minimum_Replacements_to_Sort_the_Array.java ├── Minimum_Replacements_to_Sort_the_Array.js ├── Minimum_Replacements_to_Sort_the_Array.py ├── Minimum_Size_Subarray_Sum.cpp ├── Minimum_Size_Subarray_Sum.java ├── Minimum_Size_Subarray_Sum.js ├── Minimum_Size_Subarray_Sum.py ├── Minimum_Speed_to_Arrive_on_Time.cpp ├── Minimum_Speed_to_Arrive_on_Time.java ├── Minimum_Speed_to_Arrive_on_Time.js ├── Minimum_Speed_to_Arrive_on_Time.py ├── Modify_the_Matrix.cpp ├── Modify_the_Matrix.java ├── Modify_the_Matrix.js ├── Modify_the_Matrix.py ├── Monotonic_Array.cpp ├── Monotonic_Array.java ├── Monotonic_Array.js ├── Monotonic_Array.py ├── Number_of_Good_Pairs.cpp ├── Number_of_Good_Pairs.java ├── Number_of_Good_Pairs.js ├── Number_of_Good_Pairs.py ├── Number_of_Increasing_Paths_in_a_Grid.cpp ├── Number_of_Increasing_Paths_in_a_Grid.java ├── Number_of_Increasing_Paths_in_a_Grid.js ├── Number_of_Increasing_Paths_in_a_Grid.py ├── Number_of_Laser_Beams_in_a_Bank.cpp ├── Number_of_Laser_Beams_in_a_Bank.java ├── Number_of_Laser_Beams_in_a_Bank.js ├── Number_of_Laser_Beams_in_a_Bank.py ├── Number_of_Longest_Increasing Subsequence.cpp ├── Number_of_Longest_Increasing Subsequence.java ├── Number_of_Longest_Increasing Subsequence.js ├── Number_of_Longest_Increasing Subsequence.py ├── Number_of_Music_Playlists.cpp ├── Number_of_Music_Playlists.java ├── Number_of_Music_Playlists.js ├── Number_of_Music_Playlists.py ├── Palindromic_Substrings.cpp ├── Palindromic_Substrings.java ├── Palindromic_Substrings.js ├── Palindromic_Substrings.py ├── Partition Array for Maximum Sum.cpp ├── Partition Array for Maximum Sum.java ├── Partition Array for Maximum Sum.js ├── Partition Array for Maximum Sum.py ├── Partition_List.cpp ├── Partition_List.java ├── Partition_List.js ├── Path_With_Minimum_Effort.cpp ├── Path_With_Minimum_Effort.java ├── Path_With_Minimum_Effort.js ├── Path_With_Minimum_Effort.py ├── Path_with_Maximum_Probability.cpp ├── Path_with_Maximum_Probability.java ├── Path_with_Maximum_Probability.js ├── Path_with_Maximum_Probability.py ├── Peak_Index_in_a_Mountain_Array.cpp ├── Peak_Index_in_a_Mountain_Array.java ├── Peak_Index_in_a_Mountain_Array.js ├── Peak_Index_in_a_Mountain_Array.py ├── Permutations.cpp ├── Permutations.java ├── Permutations.js ├── Permutations.py ├── Permutations2.cpp ├── Permutations2.java ├── Permutations2.js ├── Permutations2.py ├── Pow(x, n).cpp ├── Pow(x, n).java ├── Pow(x, n).js ├── Pow(x, n).py ├── Predict_the_Winner.cpp ├── Predict_the_Winner.java ├── Predict_the_Winner.js ├── Predict_the_Winner.py ├── Pseudo-Palindromic_Paths_in_a_Binary_Tree.cpp ├── Pseudo-Palindromic_Paths_in_a_Binary_Tree.java ├── Pseudo-Palindromic_Paths_in_a_Binary_Tree.js ├── Pseudo-Palindromic_Paths_in_a_Binary_Tree.py ├── Put_Marbles_in_Bags.cpp ├── Put_Marbles_in_Bags.java ├── Put_Marbles_in_Bags.js ├── Put_Marbles_in_Bags.py ├── README.md ├── Range_Sum_of_BST.cpp ├── Range_Sum_of_BST.java ├── Range_Sum_of_BST.js ├── Range_Sum_of_BST.py ├── Rearrange Array Elements by Sign.cpp ├── Rearrange Array Elements by Sign.java ├── Rearrange Array Elements by Sign.js ├── Rearrange Array Elements by Sign.py ├── Reconstruct_Itinerary.cpp ├── Reconstruct_Itinerary.java ├── Reconstruct_Itinerary.js ├── Reconstruct_Itinerary.py ├── Redistribute_Characters_to_Make_All_Strings_Equal.cpp ├── Redistribute_Characters_to_Make_All_Strings_Equal.java ├── Redistribute_Characters_to_Make_All_Strings_Equal.js ├── Redistribute_Characters_to_Make_All_Strings_Equal.py ├── Remove_Colored_Pieces_if_Both_Neighbors_are_the_Same_Color.cpp ├── Remove_Colored_Pieces_if_Both_Neighbors_are_the_Same_Color.java ├── Remove_Colored_Pieces_if_Both_Neighbors_are_the_Same_Color.js ├── Remove_Colored_Pieces_if_Both_Neighbors_are_the_Same_Color.py ├── Remove_Duplicate_Letters.cpp ├── Remove_Duplicate_Letters.java ├── Remove_Duplicate_Letters.js ├── Remove_Duplicate_Letters.py ├── Remove_Nth_Node_From_End_of_List.cpp ├── Remove_Nth_Node_From_End_of_List.java ├── Remove_Nth_Node_From_End_of_List.js ├── Remove_Nth_Node_From_End_of_List.py ├── Reorganize_String.cpp ├── Reorganize_String.java ├── Reorganize_String.js ├── Reorganize_String.py ├── Reverse_Linked_List_II.cpp ├── Reverse_Linked_List_II.java ├── Reverse_Linked_List_II.js ├── Reverse_Linked_List_II.py ├── Reverse_Words_in_a_String_III.cpp ├── Reverse_Words_in_a_String_III.java ├── Reverse_Words_in_a_String_III.js ├── Reverse_Words_in_a_String_III.py ├── Same_Tree.cpp ├── Same_Tree.java ├── Same_Tree.js ├── Same_Tree.py ├── Search_in_Rotated_Sorted_Array_II.cpp ├── Search_in_Rotated_Sorted_Array_II.java ├── Search_in_Rotated_Sorted_Array_II.js ├── Search_in_Rotated_Sorted_Array_II.py ├── Sequential_Digits.cpp ├── Sequential_Digits.java ├── Sequential_Digits.js ├── Sequential_Digits.py ├── Set_Matrix_Zeroes.cpp ├── Set_Matrix_Zeroes.java ├── Set_Matrix_Zeroes.js ├── Set_Matrix_Zeroes.py ├── Set_Mismatch.cpp ├── Set_Mismatch.java ├── Set_Mismatch.js ├── Set_Mismatch.py ├── Shortest_Path_to_Get_All_Keys.cpp ├── Shortest_Path_to_Get_All_Keys.java ├── Shortest_Path_to_Get_All_Keys.js ├── Shortest_Path_to_Get_All_Keys.py ├── Snapshot_Array.cpp ├── Snapshot_Array.java ├── Snapshot_Array.js ├── Snapshot_Array.py ├── Sort_Array_By_Parity.cpp ├── Sort_Array_By_Parity.java ├── Sort_Array_By_Parity.js ├── Sort_Array_By_Parity.py ├── Soup_Servings.cpp ├── Soup_Servings.java ├── Soup_Servings.js ├── Soup_Servings.py ├── Split_Linked_List_in_Parts.cpp ├── Split_Linked_List_in_Parts.java ├── Split_Linked_List_in_Parts.js ├── Split_Linked_List_in_Parts.py ├── Split_the_Array.cpp ├── Split_the_Array.java ├── Split_the_Array.js ├── Split_the_Array.py ├── Squares_of_a_Sorted_Array.cpp ├── Squares_of_a_Sorted_Array.java ├── Squares_of_a_Sorted_Array.js ├── Squares_of_a_Sorted_Array.py ├── Strange_Printer.cpp ├── Strange_Printer.java ├── Strange_Printer.js ├── Strange_Printer.py ├── Sum_of_Subarray_Minimums.cpp ├── Sum_of_Subarray_Minimums.java ├── Sum_of_Subarray_Minimums.js ├── Sum_of_Subarray_Minimums.py ├── Symmetric_Tree.cpp ├── Symmetric_Tree.java ├── Symmetric_Tree.js ├── Symmetric_Tree.py ├── Tallest_Billboard.cpp ├── Tallest_Billboard.java ├── Tallest_Billboard.js ├── Tallest_Billboard.py ├── The_K_Weakest_Rows_in_a_Matrix.cpp ├── The_K_Weakest_Rows_in_a_Matrix.java ├── The_K_Weakest_Rows_in_a_Matrix.js ├── The_K_Weakest_Rows_in_a_Matrix.py ├── Top_K_Frequent_Elements.cpp ├── Top_K_Frequent_Elements.java ├── Top_K_Frequent_Elements.py ├── Total_Cost_to_Hire_K_Workers.cpp ├── Total_Cost_to_Hire_K_Workers.java ├── Total_Cost_to_Hire_K_Workers.js ├── Total_Cost_to_Hire_K_Workers.py ├── Unique_Binary_Search_Trees_II.cpp ├── Unique_Binary_Search_Trees_II.java ├── Unique_Binary_Search_Trees_II.js ├── Unique_Binary_Search_Trees_II.py ├── Unique_Number_of_Occurrences.cpp ├── Unique_Number_of_Occurrences.java ├── Unique_Number_of_Occurrences.js ├── Unique_Number_of_Occurrences.py ├── Unique_Paths_II.cpp ├── Unique_Paths_II.java ├── Unique_Paths_II.js ├── Unique_Paths_II.py ├── Valid_Anagram.cpp ├── Valid_Anagram.java ├── Valid_Anagram.py ├── add_digits_1.cpp ├── add_digits_1.java ├── add_digits_1.js ├── add_digits_1.py ├── add_digits_2.cpp ├── add_digits_2.java ├── add_digits_2.js ├── add_digits_2.py ├── add_two_numbers.py ├── asteroid_collision.cpp ├── asteroid_collision.java ├── asteroid_collision.js ├── asteroid_collision.py ├── average_salary_excluding_the_minimum_and_maximum_salary.cpp ├── average_salary_excluding_the_minimum_and_maximum_salary.java ├── average_salary_excluding_the_minimum_and_maximum_salary.js ├── average_salary_excluding_the_minimum_and_maximum_salary.py ├── binary_search.py ├── binary_tree_level_order_traversal.py ├── binary_tree_maximum_path_sum.cpp ├── binary_tree_maximum_path_sum.java ├── binary_tree_maximum_path_sum.js ├── binary_tree_maximum_path_sum.py ├── binary_tree_right_side_view.py ├── boats_to_save_people.cpp ├── boats_to_save_people.java ├── boats_to_save_people.js ├── boats_to_save_people.py ├── bubble_sort.py ├── c++ ├── 01_Matrix.cpp └── 132_pattern.cpp ├── can_make_arithmetic_progression_from_sequence.cpp ├── can_make_arithmetic_progression_from_sequence.java ├── can_make_arithmetic_progression_from_sequence.js ├── can_make_arithmetic_progression_from_sequence.py ├── can_place_flowers.py ├── candy.cpp ├── candy.java ├── candy.js ├── candy.py ├── car_fleet.py ├── check_if_it_Is_a_straight_line.cpp ├── check_if_it_Is_a_straight_line.java ├── check_if_it_Is_a_straight_line.js ├── check_if_it_Is_a_straight_line.py ├── climbing_stairs_1.py ├── climbing_stairs_2.py ├── coin_change_II.cpp ├── coin_change_II.java ├── coin_change_II.js ├── coin_change_II.py ├── combination_sum.py ├── combination_sum_II.cpp ├── combination_sum_II.java ├── combination_sum_II.js ├── combination_sum_II.py ├── combination_sum_IV.cpp ├── combination_sum_IV.java ├── combination_sum_IV.js ├── combination_sum_IV.py ├── construct_binary_tree_from_preorder_and_inorder_traversal.py ├── construct_binary_tree_from_preorder_and_inorder_traversal_linear.py ├── contains_duplicate.py ├── count_ways_to_build_good_strings.cpp ├── count_ways_to_build_good_strings.java ├── count_ways_to_build_good_strings.js ├── count_ways_to_build_good_strings.py ├── counting_bits.cpp ├── counting_bits.java ├── counting_bits.js ├── counting_bits.py ├── course_schedule.py ├── daily_temperatures.py ├── design_hashSet.cpp ├── design_hashSet.java ├── design_hashSet.js ├── design_hashSet.py ├── design_parking_system.cpp ├── design_parking_system.java ├── design_parking_system.js ├── design_parking_system.py ├── detonate_the_maximum_bombs.cpp ├── detonate_the_maximum_bombs.java ├── detonate_the_maximum_bombs.js ├── detonate_the_maximum_bombs.py ├── evaluate_reverse_polish_notation.py ├── find_all_numbers_disappeared_in_an_array.py ├── find_duplicate_subtrees.cpp ├── find_duplicate_subtrees.java ├── find_duplicate_subtrees.js ├── find_duplicate_subtrees.py ├── find_first_and_last_position_of_element_in_sorted_array.py ├── find_minimum_in_rotated_sorted_array.py ├── find_pivot_index.py ├── find_the_difference_of_two_arrays.cpp ├── find_the_difference_of_two_arrays.java ├── find_the_difference_of_two_arrays.js ├── find_the_difference_of_two_arrays.py ├── find_the_longest_valid_obstacle_course_at_each_position.cpp ├── find_the_longest_valid_obstacle_course_at_each_position.java ├── find_the_longest_valid_obstacle_course_at_each_position.js ├── find_the_longest_valid_obstacle_course_at_each_position.py ├── fireworks ├── fireworks.html ├── fireworks.js ├── fireworks_complete.js └── style.css ├── first_Missing_positive1.js ├── first_missing_positive.cpp ├── first_missing_positive.java ├── first_missing_positive1.py ├── first_missing_positive1_1.py ├── first_missing_positive2.js ├── first_missing_positive2.py ├── frequency_of_the_most_frequent_element.py ├── generate_parentheses.py ├── group_anagrams_1.py ├── group_anagrams_2.py ├── happy_number.py ├── house_robber_II.py ├── increasing_order_search_tree.py ├── is_subsequence.cpp ├── is_subsequence.java ├── is_subsequence.js ├── is_subsequence.py ├── java ├── 01_Matrix.java └── 132_pattern.java ├── js ├── 01_Matrix.js └── 132_pattern.js ├── jump_game.py ├── jump_game_II.py ├── jump_game_III_bfs.py ├── jump_game_III_dfs.py ├── jump_game_IV.py ├── kth_smallest_element_in_a_BST.cpp ├── kth_smallest_element_in_a_BST.java ├── kth_smallest_element_in_a_BST.js ├── kth_smallest_element_in_a_BST.py ├── largest_color_value_in_a_directed_graph.cpp ├── largest_color_value_in_a_directed_graph.java ├── largest_color_value_in_a_directed_graph.js ├── largest_color_value_in_a_directed_graph.py ├── largest_rectangle_in_histogram.cpp ├── largest_rectangle_in_histogram.java ├── largest_rectangle_in_histogram.js ├── largest_rectangle_in_histogram.py ├── last_stone_weight.py ├── length_of_last_word.py ├── linked_list_cycle.py ├── linked_list_cycle_II.py ├── longest_common_prefix.py ├── longest_consecutive_sequence.py ├── longest_increasing_subsequence_binary_search.py ├── longest_increasing_subsequence_dynamic_programming.py ├── longest_palindromic_subsequence.cpp ├── longest_palindromic_subsequence.java ├── longest_palindromic_subsequence.js ├── longest_palindromic_subsequence.py ├── longest_repeating_character_replacement.py ├── longest_substring_without_repeating_characters.py ├── longest_valid_parentheses.cpp ├── longest_valid_parentheses.java ├── longest_valid_parentheses.js ├── longest_valid_parentheses.py ├── longest_zigzag_path_in_a_binary_tree.cpp ├── longest_zigzag_path_in_a_binary_tree.java ├── longest_zigzag_path_in_a_binary_tree.js ├── longest_zigzag_path_in_a_binary_tree.py ├── lowest_common_ancestor_of_a_binary_search_tree.py ├── majority_element_hashmap.py ├── majority_element_solution2.py ├── matrix_diagonal_sum.cpp ├── matrix_diagonal_sum.java ├── matrix_diagonal_sum.js ├── matrix_diagonal_sum.py ├── max_area_of_island.py ├── maximal_rectangle.cpp ├── maximal_rectangle.java ├── maximal_rectangle.js ├── maximal_rectangle.py ├── maximum_depth_of_binary_tree_bfs.py ├── maximum_depth_of_binary_tree_dfs.py ├── maximum_number_of_vowels_in_a_substring_of_given_length.cpp ├── maximum_number_of_vowels_in_a_substring_of_given_length.java ├── maximum_number_of_vowels_in_a_substring_of_given_length.js ├── maximum_number_of_vowels_in_a_substring_of_given_length.py ├── maximum_product_subarray.py ├── maximum_subarray.py ├── maximum_subsequence_score.cpp ├── maximum_subsequence_score.java ├── maximum_subsequence_score.js ├── maximum_subsequence_score.py ├── maximum_twin_sum_of_a_linked_list.cpp ├── maximum_twin_sum_of_a_linked_list.java ├── maximum_twin_sum_of_a_linked_list.js ├── maximum_twin_sum_of_a_linked_list.py ├── maximum_value_of_k_coins_from_piles.cpp ├── maximum_value_of_k_coins_from_piles.java ├── maximum_value_of_k_coins_from_piles.js ├── maximum_value_of_k_coins_from_piles.py ├── maximum_width_of_binary_tree.cpp ├── maximum_width_of_binary_tree.java ├── maximum_width_of_binary_tree.js ├── maximum_width_of_binary_tree.py ├── merge_intervals.cpp ├── merge_intervals.java ├── merge_intervals.js ├── merge_intervals.py ├── merge_k_sorted_lists.py ├── merge_sorted_array.py ├── merge_strings_alternately.cpp ├── merge_strings_alternately.java ├── merge_strings_alternately.js ├── merge_strings_alternately.py ├── merge_two_binary_trees.py ├── min_cost_climbing_stairs.py ├── min_stack.cpp ├── min_stack.java ├── min_stack.js ├── min_stack.py ├── minimum_cost_to_cut_a_stick.cpp ├── minimum_cost_to_cut_a_stick.java ├── minimum_cost_to_cut_a_stick.js ├── minimum_cost_to_cut_a_stick.py ├── minimum_insertion_steps_to_make_a_string_palindrome.cpp ├── minimum_insertion_steps_to_make_a_string_palindrome.java ├── minimum_insertion_steps_to_make_a_string_palindrome.js ├── minimum_insertion_steps_to_make_a_string_palindrome.py ├── minimum_number_of_vertices_to_reach_all_nodes.cpp ├── minimum_number_of_vertices_to_reach_all_nodes.java ├── minimum_number_of_vertices_to_reach_all_nodes.js ├── minimum_number_of_vertices_to_reach_all_nodes.py ├── missing_number.cpp ├── missing_number.java ├── missing_number.js ├── missing_number.py ├── most_frequent_subtree_sum.cpp ├── most_frequent_subtree_sum.java ├── most_frequent_subtree_sum.js ├── most_frequent_subtree_sum.py ├── move_zeroes.py ├── next_permutation.cpp ├── next_permutation.java ├── next_permutation.js ├── next_permutation.py ├── non-overlapping_intervals.cpp ├── non-overlapping_intervals.java ├── non-overlapping_intervals.js ├── non-overlapping_intervals.py ├── non_decreasing_array.py ├── number_of_closed_islands.cpp ├── number_of_closed_islands.java ├── number_of_closed_islands.js ├── number_of_closed_islands.py ├── number_of_enclaves.cpp ├── number_of_enclaves.java ├── number_of_enclaves.js ├── number_of_enclaves.py ├── number_of_islands_bfs.py ├── number_of_islands_dfs.py ├── number_of_provinces.cpp ├── number_of_provinces.java ├── number_of_provinces.js ├── number_of_provinces.py ├── number_of_subsequences_that_satisfy_the_given_sum_condition.cpp ├── number_of_subsequences_that_satisfy_the_given_sum_condition.java ├── number_of_subsequences_that_satisfy_the_given_sum_condition.js ├── number_of_subsequences_that_satisfy_the_given_sum_condition.py ├── number_of_zero-filled_subarrays.cpp ├── number_of_zero-filled_subarrays.java ├── number_of_zero-filled_subarrays.js ├── number_of_zero-filled_subarrays.py ├── pacific_atlantic_water_flow.cpp ├── pacific_atlantic_water_flow.java ├── pacific_atlantic_water_flow.js ├── pacific_atlantic_water_flow.py ├── palindrome_linked_list.py ├── palindrome_number.py ├── partition_equal_subset_sum.py ├── partition_list.py ├── pascals_triangle.cpp ├── pascals_triangle.java ├── pascals_triangle.js ├── pascals_triangle.py ├── path_sum.py ├── permutation_in_string.py ├── plus_one.py ├── product_of_array_except_self.py ├── python ├── 01_Matrix.py └── 132_pattern.py ├── quicksort.py ├── remove_K_digits.py ├── remove_all_adjacent_duplicates_in_string.py ├── remove_all_adjacent_duplicates_in_string_II.cpp ├── remove_all_adjacent_duplicates_in_string_II.java ├── remove_all_adjacent_duplicates_in_string_II.js ├── remove_all_adjacent_duplicates_in_string_II.py ├── remove_linked_list_elements.cpp ├── remove_linked_list_elements.java ├── remove_linked_list_elements.js ├── remove_linked_list_elements.py ├── remove_nth_node_from_end_of_list.py ├── removing_stars_from_a_string.cpp ├── removing_stars_from_a_string.java ├── removing_stars_from_a_string.js ├── removing_stars_from_a_string.py ├── removing_stars_from_a_string_2.cpp ├── removing_stars_from_a_string_2.java ├── removing_stars_from_a_string_2.js ├── removing_stars_from_a_string_2.py ├── reorder_list.py ├── repeated_substring_pattern_1.java ├── repeated_substring_pattern_1.js ├── repeated_substring_pattern_1.py ├── repeated_substring_pattern_2.java ├── repeated_substring_pattern_2.js ├── repeated_substring_pattern_2.py ├── rotate_array_solution1.py ├── rotate_array_solution2.py ├── rotate_image.py ├── rotate_list.py ├── search_a_2d_Matrix.cpp ├── search_a_2d_Matrix.java ├── search_a_2d_Matrix.js ├── search_a_2d_Matrix.py ├── search_a_2d_Matrix_bonus.cpp ├── search_a_2d_Matrix_bonus.java ├── search_a_2d_Matrix_bonus.js ├── search_a_2d_Matrix_bonus.py ├── search_in_a_binary_search_tree.py ├── search_in_rotated_sorted_array.cpp ├── search_in_rotated_sorted_array.java ├── search_in_rotated_sorted_array.js ├── search_in_rotated_sorted_array.py ├── shortest_bridge.cpp ├── shortest_bridge.java ├── shortest_bridge.js ├── shortest_bridge.py ├── shortest_path_in_binary_matrix.cpp ├── shortest_path_in_binary_matrix.java ├── shortest_path_in_binary_matrix.js ├── shortest_path_in_binary_matrix.py ├── sign_of_the_product_of_an_array.cpp ├── sign_of_the_product_of_an_array.java ├── sign_of_the_product_of_an_array.js ├── sign_of_the_product_of_an_array.py ├── simplify_path.cpp ├── simplify_path.java ├── simplify_path.js ├── simplify_path.py ├── sliding_window_maximum.cpp ├── sliding_window_maximum.java ├── sliding_window_maximum.js ├── sliding_window_maximum.py ├── smallest_number_in_infinite_set.cpp ├── smallest_number_in_infinite_set.java ├── smallest_number_in_infinite_set.js ├── smallest_number_in_infinite_set.py ├── sort_colors.py ├── spiral_matrix.cpp ├── spiral_matrix.java ├── spiral_matrix.js ├── spiral_matrix.py ├── spiral_matrix_II.cpp ├── spiral_matrix_II.java ├── spiral_matrix_II.js ├── spiral_matrix_II.py ├── subsets.py ├── subsets_ll.py ├── substring_with_concatenation_of_all_words.java ├── substring_with_concatenation_of_all_words.js ├── substring_with_concatenation_of_all_words.py ├── subtree_of_another_tree.py ├── sum_root_to_leaf_numbers.py ├── swap_nodes_in_pairs.py ├── swapping_nodes_in_a_linked_list.cpp ├── swapping_nodes_in_a_linked_list.java ├── swapping_nodes_in_a_linked_list.js ├── swapping_nodes_in_a_linked_list.py ├── target_sum.py ├── top_k_frequent_elements.py ├── trapping_rain_water.py ├── triangle.cpp ├── triangle.java ├── triangle.js ├── triangle.py ├── two_sum.cpp ├── two_sum.java ├── two_sum.py ├── uncrossed_lines.cpp ├── uncrossed_lines.java ├── uncrossed_lines.js ├── uncrossed_lines.py ├── unique_binary_search_trees.py ├── unique_length-3_palindromic_subsequences.py ├── unique_paths.cpp ├── unique_paths.java ├── unique_paths.js ├── unique_paths.py ├── valid_parentheses.py ├── validate_stack_sequences.cpp ├── validate_stack_sequences.java ├── validate_stack_sequences.js ├── validate_stack_sequences.py ├── word_break.cpp ├── word_break.java ├── word_break.js ├── word_break.py └── word_search.py /Arithmetic_Slices_II_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfArithmeticSlices(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | total = 0 5 | dp = [defaultdict(int) for _ in range(n)] 6 | 7 | for i in range(1, n): 8 | for j in range(i): 9 | diff = nums[i] - nums[j] 10 | dp[i][diff] += 1 11 | if diff in dp[j]: 12 | dp[i][diff] += dp[j][diff] 13 | total += dp[j][diff] 14 | 15 | return total 16 | -------------------------------------------------------------------------------- /Assign_Cookies.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findContentChildren(vector& g, vector& s) { 4 | sort(g.begin(), g.end()); 5 | sort(s.begin(), s.end()); 6 | 7 | int i = 0; 8 | int j = 0; 9 | 10 | while (i < g.size() && j < s.size()) { 11 | if (g[i] <= s[j]) { 12 | i++; 13 | } 14 | j++; 15 | } 16 | 17 | return i; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Assign_Cookies.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findContentChildren(int[] g, int[] s) { 3 | Arrays.sort(g); 4 | Arrays.sort(s); 5 | 6 | int i = 0; 7 | int j = 0; 8 | 9 | while (i < g.length && j < s.length) { 10 | if (g[i] <= s[j]) { 11 | i++; 12 | } 13 | j++; 14 | } 15 | 16 | return i; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assign_Cookies.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} g 3 | * @param {number[]} s 4 | * @return {number} 5 | */ 6 | var findContentChildren = function(g, s) { 7 | g.sort((a, b) => a - b); 8 | s.sort((a, b) => a - b); 9 | 10 | let i = 0; 11 | let j = 0; 12 | 13 | while (i < g.length && j < s.length) { 14 | if (g[i] <= s[j]) { 15 | i++; 16 | } 17 | j++; 18 | } 19 | 20 | return i; 21 | }; 22 | -------------------------------------------------------------------------------- /Assign_Cookies.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findContentChildren(self, g: List[int], s: List[int]) -> int: 3 | g.sort() 4 | s.sort() 5 | 6 | i = 0 7 | j = 0 8 | 9 | while i < len(g) and j < len(s): 10 | if g[i] <= s[j]: 11 | i += 1 12 | j += 1 13 | 14 | return i 15 | -------------------------------------------------------------------------------- /Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices, int fee) { 4 | int n = prices.size(); 5 | if (n < 2) { 6 | return 0; 7 | } 8 | 9 | int buy = -prices[0]; 10 | int sell = 0; 11 | 12 | for (int i = 1; i < n; i++) { 13 | int temp = buy; 14 | buy = std::max(buy, sell - prices[i]); 15 | sell = std::max(sell, temp + prices[i] - fee); 16 | } 17 | 18 | return sell; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices, int fee) { 3 | int n = prices.length; 4 | if (n < 2) { 5 | return 0; 6 | } 7 | 8 | int buy = -prices[0]; 9 | int sell = 0; 10 | 11 | for (int i = 1; i < n; i++) { 12 | int temp = buy; 13 | buy = Math.max(buy, sell - prices[i]); 14 | sell = Math.max(sell, temp + prices[i] - fee); 15 | } 16 | 17 | return sell; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} prices 3 | * @param {number} fee 4 | * @return {number} 5 | */ 6 | var maxProfit = function(prices, fee) { 7 | const n = prices.length; 8 | if (n < 2) { 9 | return 0; 10 | } 11 | 12 | let buy = -prices[0]; 13 | let sell = 0; 14 | 15 | for (let i = 1; i < n; i++) { 16 | const temp = buy; 17 | buy = Math.max(buy, sell - prices[i]); 18 | sell = Math.max(sell, temp + prices[i] - fee); 19 | } 20 | 21 | return sell; 22 | }; 23 | -------------------------------------------------------------------------------- /Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int], fee: int) -> int: 3 | n = len(prices) 4 | if n < 2: 5 | return 0 6 | 7 | buy = -prices[0] 8 | sell = 0 9 | 10 | for i in range(1, n): 11 | temp = buy 12 | buy = max(buy, sell - prices[i]) 13 | sell = max(sell, temp + prices[i] - fee) 14 | 15 | return sell 16 | -------------------------------------------------------------------------------- /Bitwise AND of Numbers Range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeBitwiseAnd(int left, int right) { 4 | while (right > left) { 5 | right &= right - 1; 6 | } 7 | return right; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Bitwise AND of Numbers Range.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rangeBitwiseAnd(int left, int right) { 3 | while (right > left) { 4 | right &= right - 1; 5 | } 6 | return right; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Bitwise AND of Numbers Range.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} left 3 | * @param {number} right 4 | * @return {number} 5 | */ 6 | var rangeBitwiseAnd = function(left, right) { 7 | while (right > left) { 8 | right &= right - 1; 9 | } 10 | return right; 11 | }; 12 | -------------------------------------------------------------------------------- /Bitwise AND of Numbers Range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeBitwiseAnd(self, left: int, right: int) -> int: 3 | while right > left: 4 | right &= right - 1 5 | 6 | return right 7 | -------------------------------------------------------------------------------- /Champagne_Tower_2d.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 3 | pyramid = [[0.0] * k for k in range(1, 101)] 4 | pyramid[0][0] = poured 5 | 6 | for row in range(query_row): 7 | for glass in range(row + 1): 8 | overflow = (pyramid[row][glass] - 1.0) / 2.0 9 | if overflow > 0: 10 | pyramid[row + 1][glass] += overflow 11 | pyramid[row + 1][glass + 1] += overflow 12 | 13 | return min(1.0, pyramid[query_row][query_glass]) 14 | -------------------------------------------------------------------------------- /Combinations.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @param {number} k 4 | * @return {number[][]} 5 | */ 6 | var combine = function(n, k) { 7 | const res = []; 8 | const comb = []; 9 | 10 | function backtrack(start) { 11 | if (comb.length === k) { 12 | res.push([...comb]); 13 | return; 14 | } 15 | 16 | for (let num = start; num <= n; num++) { 17 | comb.push(num); 18 | backtrack(num + 1); 19 | comb.pop(); 20 | } 21 | } 22 | 23 | backtrack(1); 24 | return res; 25 | }; 26 | -------------------------------------------------------------------------------- /Combinations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | res = [] 4 | comb = [] 5 | 6 | def backtrack(start): 7 | if len(comb) == k: 8 | res.append(comb[:]) 9 | return 10 | 11 | for num in range(start, n + 1): 12 | comb.append(num) 13 | backtrack(num + 1) 14 | comb.pop() 15 | 16 | backtrack(1) 17 | return res 18 | -------------------------------------------------------------------------------- /Convert_an_Array_Into_a_2D_Array_With_Conditions.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findMatrix(vector& nums) { 4 | vector> res; 5 | unordered_map freq; 6 | 7 | for (int num : nums) { 8 | freq[num] = 1 + freq[num]; 9 | 10 | if (freq[num] > res.size()) { 11 | res.push_back(vector()); 12 | } 13 | 14 | res[freq[num] - 1].push_back(num); 15 | } 16 | 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Convert_an_Array_Into_a_2D_Array_With_Conditions.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> findMatrix(int[] nums) { 3 | List> res = new ArrayList<>(); 4 | Map freq = new HashMap<>(); 5 | 6 | for (int num : nums) { 7 | freq.put(num, 1 + freq.getOrDefault(num, 0)); 8 | 9 | if (freq.get(num) > res.size()) { 10 | res.add(new ArrayList<>()); 11 | } 12 | 13 | res.get(freq.get(num) - 1).add(num); 14 | } 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Convert_an_Array_Into_a_2D_Array_With_Conditions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var findMatrix = function(nums) { 6 | const res = []; 7 | const freq = {}; 8 | 9 | for (const num of nums) { 10 | freq[num] = 1 + (freq[num] || 0); 11 | 12 | if (freq[num] > res.length) { 13 | res.push([]); 14 | } 15 | 16 | res[freq[num] - 1].push(num); 17 | } 18 | 19 | return res; 20 | }; 21 | -------------------------------------------------------------------------------- /Convert_an_Array_Into_a_2D_Array_With_Conditions.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMatrix(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | freq = {} 5 | 6 | for num in nums: 7 | freq[num] = 1 + freq.get(num, 0) 8 | 9 | if freq[num] > len(res): 10 | res.append([]) 11 | 12 | res[freq[num] - 1].append(num) 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /Copy_List_with_Random_Pointer.js: -------------------------------------------------------------------------------- 1 | var copyRandomList = function(head) { 2 | const hashMap = new Map(); 3 | let cur = head; 4 | 5 | while (cur) { 6 | hashMap.set(cur, new Node(cur.val)); 7 | cur = cur.next; 8 | } 9 | 10 | cur = head; 11 | 12 | while (cur) { 13 | const copy = hashMap.get(cur); 14 | copy.next = hashMap.get(cur.next) || null; 15 | copy.random = hashMap.get(cur.random) || null; 16 | cur = cur.next; 17 | } 18 | 19 | return hashMap.get(head); 20 | }; 21 | -------------------------------------------------------------------------------- /Copy_List_with_Random_Pointer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': 3 | hash = {None: None} 4 | cur = head 5 | 6 | while cur: 7 | hash[cur] = Node(cur.val) 8 | cur = cur.next 9 | 10 | cur = head 11 | 12 | while cur: 13 | copy = hash[cur] 14 | copy.next = hash[cur.next] 15 | copy.random = hash[cur.random] 16 | cur = cur.next 17 | 18 | return hash[head] 19 | -------------------------------------------------------------------------------- /Count_All_Valid_Pickup_and_Delivery_Options.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOrders(int n) { 4 | const int MOD = 1000000007; 5 | long long totalWays = 1; 6 | for (int orderNumber = 2; orderNumber <= n; orderNumber++) { 7 | totalWays = (totalWays * (2LL * orderNumber - 1) * orderNumber) % MOD; 8 | } 9 | return static_cast(totalWays); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Count_All_Valid_Pickup_and_Delivery_Options.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countOrders(int n) { 3 | final int MOD = 1000000007; 4 | int totalWays = 1; 5 | for (int orderNumber = 2; orderNumber <= n; orderNumber++) { 6 | totalWays = (int)((totalWays * (2L * orderNumber - 1) * orderNumber) % MOD); 7 | } 8 | return totalWays; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Count_All_Valid_Pickup_and_Delivery_Options.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number} 4 | */ 5 | var countOrders = function(n) { 6 | const MOD = 1000000007; 7 | let totalWays = 1; 8 | for (let orderNumber = 2; orderNumber <= n; orderNumber++) { 9 | totalWays = (totalWays * (2 * orderNumber - 1) * orderNumber) % MOD; 10 | } 11 | return totalWays; 12 | }; 13 | -------------------------------------------------------------------------------- /Count_All_Valid_Pickup_and_Delivery_Options.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOrders(self, n: int) -> int: 3 | MOD = 10**9 + 7 4 | total_ways = 1 5 | 6 | for order_number in range(2, n + 1): 7 | total_ways = (total_ways * (2 * order_number - 1) * order_number) % MOD 8 | 9 | return total_ways 10 | -------------------------------------------------------------------------------- /Daily_Temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& temperatures) { 4 | stack st; 5 | vector res(temperatures.size(), 0); 6 | 7 | for (int i = 0; i < temperatures.size(); i++) { 8 | while (!st.empty() && temperatures[i] > temperatures[st.top()]) { 9 | int idx = st.top(); st.pop(); 10 | res[idx] = i - idx; 11 | } 12 | st.push(i); 13 | } 14 | 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Daily_Temperatures.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] dailyTemperatures(int[] temperatures) { 3 | Stack stack = new Stack<>(); 4 | int[] result = new int[temperatures.length]; 5 | 6 | for (int i = 0; i < temperatures.length; i++) { 7 | while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { 8 | int idx = stack.pop(); 9 | result[idx] = i - idx; 10 | } 11 | stack.push(i); 12 | } 13 | 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Daily_Temperatures.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} temperatures 3 | * @return {number[]} 4 | */ 5 | var dailyTemperatures = function(temperatures) { 6 | const stack = []; 7 | const result = new Array(temperatures.length).fill(0); 8 | 9 | for (let i = 0; i < temperatures.length; i++) { 10 | while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) { 11 | const idx = stack.pop(); 12 | result[idx] = i - idx; 13 | } 14 | stack.push(i); 15 | } 16 | 17 | return result; 18 | }; 19 | -------------------------------------------------------------------------------- /Daily_Temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | st = [] 4 | res = [0] * len(temperatures) 5 | 6 | for i in range(len(temperatures)): 7 | while st and temperatures[i] > temperatures[st[-1]]: 8 | idx = st.pop() 9 | res[idx] = i - idx 10 | st.append(i) 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /Decoded_String_at_Index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeAtIndex(self, s: str, k: int) -> str: 3 | total_length = 0 4 | 5 | for char in s: 6 | if char.isdigit(): 7 | total_length *= int(char) 8 | else: 9 | total_length += 1 10 | 11 | for char in reversed(s): 12 | k %= total_length 13 | 14 | if k == 0 and char.isalpha(): 15 | return char 16 | 17 | if char.isdigit(): 18 | total_length //= int(char) 19 | else: 20 | total_length -= 1 21 | -------------------------------------------------------------------------------- /Determine_if_String_Halves_Are_Alike.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | left = left_vowels = right_vowels = 0 4 | right = len(s) - 1 5 | vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} 6 | 7 | while left < right: 8 | if s[left] in vowels: 9 | left_vowels += 1 10 | if s[right] in vowels: 11 | right_vowels += 1 12 | 13 | left += 1 14 | right -= 1 15 | 16 | return left_vowels == right_vowels 17 | -------------------------------------------------------------------------------- /Determine_if_Two_Strings_Are_Close.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def closeStrings(self, word1: str, word2: str) -> bool: 3 | if len(word1) != len(word2): 4 | return False 5 | 6 | w1 = {} 7 | for c in word1: 8 | w1[c] = 1 + w1.get(c, 0) 9 | 10 | w2 = {} 11 | for c in word2: 12 | w2[c] = 1 + w2.get(c, 0) 13 | 14 | if w1.keys() != w2.keys(): 15 | return False 16 | 17 | return sorted(w1.values()) == sorted(w2.values()) 18 | -------------------------------------------------------------------------------- /Divide_Array_Into_Arrays_With_Max_Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> divideArray(vector& nums, int k) { 4 | sort(nums.begin(), nums.end()); 5 | vector> res; 6 | 7 | for (int i = 0; i < nums.size(); i += 3) { 8 | if (nums[i] + k < nums[i + 2]) { 9 | return {}; 10 | } 11 | 12 | res.push_back({nums[i], nums[i + 1], nums[i + 2]}); 13 | } 14 | 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Divide_Array_Into_Arrays_With_Max_Difference.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] divideArray(int[] nums, int k) { 3 | Arrays.sort(nums); 4 | int[][] res = new int[nums.length / 3][3]; 5 | 6 | for (int i = 0; i < nums.length; i += 3) { 7 | if (nums[i] + k < nums[i + 2]) { 8 | return new int[0][0]; 9 | } 10 | 11 | res[i/3] = new int[]{nums[i], nums[i + 1], nums[i + 2]}; 12 | } 13 | 14 | return res; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Divide_Array_Into_Arrays_With_Max_Difference.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {number[][]} 5 | */ 6 | var divideArray = function(nums, k) { 7 | nums.sort((a, b) => a - b); 8 | const res = []; 9 | 10 | for (let i = 0; i < nums.length; i += 3) { 11 | if (nums[i] + k < nums[i + 2]) { 12 | return []; 13 | } 14 | 15 | res.push(nums.slice(i, i + 3)); 16 | } 17 | 18 | return res; 19 | }; 20 | -------------------------------------------------------------------------------- /Divide_Array_Into_Arrays_With_Max_Difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divideArray(self, nums: List[int], k: int) -> List[List[int]]: 3 | nums.sort() 4 | res = [] 5 | 6 | for i in range(0, len(nums), 3): 7 | if nums[i] + k < nums[i+2]: 8 | return [] 9 | 10 | res.append(nums[i:i+3]) 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /Equal_Row_and_Column_Pairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def equalPairs(self, grid: List[List[int]]) -> int: 3 | 4 | count = 0 5 | n = len(grid) 6 | 7 | row = {} 8 | 9 | for i in range(n): 10 | row[tuple(grid[i])] = 1 + row.get(tuple(grid[i]), 0) 11 | 12 | for c in range(n): 13 | col = [grid[i][c] for i in range(n)] 14 | if tuple(col) in row: 15 | count += row[tuple(col)] 16 | 17 | return count 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Excel_Sheet_Column_Title.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convertToTitle(int columnNumber) { 4 | string res = ""; 5 | 6 | while (columnNumber > 0) { 7 | columnNumber--; 8 | res = char((columnNumber % 26) + 'A') + res; 9 | columnNumber /= 26; 10 | } 11 | 12 | return res; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Excel_Sheet_Column_Title.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convertToTitle(int columnNumber) { 3 | StringBuilder res = new StringBuilder(); 4 | 5 | while (columnNumber > 0) { 6 | columnNumber--; 7 | res.insert(0, (char) ((columnNumber % 26) + 'A')); 8 | columnNumber /= 26; 9 | } 10 | 11 | return res.toString(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Excel_Sheet_Column_Title.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} columnNumber 3 | * @return {string} 4 | */ 5 | var convertToTitle = function(columnNumber) { 6 | let res = ""; 7 | 8 | while (columnNumber > 0) { 9 | columnNumber--; 10 | res = String.fromCharCode((columnNumber % 26) + "A".charCodeAt(0)) + res; 11 | columnNumber = Math.floor(columnNumber / 26); 12 | } 13 | 14 | return res; 15 | }; 16 | -------------------------------------------------------------------------------- /Excel_Sheet_Column_Title.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convertToTitle(self, columnNumber: int) -> str: 3 | res = "" 4 | 5 | while columnNumber > 0: 6 | columnNumber -= 1 7 | res = chr((columnNumber % 26) + ord("A")) + res 8 | columnNumber //= 26 9 | 10 | return res 11 | -------------------------------------------------------------------------------- /Extra_Characters_in_a_String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minExtraChar(self, s: str, dictionary: List[str]) -> int: 3 | max_len = len(s) + 1 4 | dp = [max_len] * max_len 5 | dp[0] = 0 6 | word_set = set(dictionary) 7 | 8 | for i in range(1, max_len): 9 | dp[i] = dp[i - 1] + 1 10 | 11 | for j in range(1, i + 1): 12 | if s[i-j:i] in word_set: 13 | dp[i] = min(dp[i], dp[i-j]) 14 | 15 | return dp[-1] 16 | -------------------------------------------------------------------------------- /Find the Town Judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | vector trusted(n + 1, 0); 5 | 6 | for (const auto& pair : trust) { 7 | trusted[pair[0]] -= 1; 8 | trusted[pair[1]] += 1; 9 | } 10 | 11 | for (int i = 1; i <= n; i++) { 12 | if (trusted[i] == n - 1) { 13 | return i; 14 | } 15 | } 16 | 17 | return -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Find the Town Judge.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findJudge(int n, int[][] trust) { 3 | int[] trusted = new int[n + 1]; 4 | 5 | for (int[] pair : trust) { 6 | trusted[pair[0]] -= 1; 7 | trusted[pair[1]] += 1; 8 | } 9 | 10 | for (int i = 1; i <= n; i++) { 11 | if (trusted[i] == n - 1) { 12 | return i; 13 | } 14 | } 15 | 16 | return -1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Find the Town Judge.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @param {number[][]} trust 4 | * @return {number} 5 | */ 6 | var findJudge = function(n, trust) { 7 | const trusted = new Array(n + 1).fill(0); 8 | 9 | for (const [a, b] of trust) { 10 | trusted[a] -= 1; 11 | trusted[b] += 1; 12 | } 13 | 14 | for (let i = 1; i <= n; i++) { 15 | if (trusted[i] === n - 1) { 16 | return i; 17 | } 18 | } 19 | 20 | return -1; 21 | }; 22 | -------------------------------------------------------------------------------- /Find the Town Judge.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 3 | trusted = [0] * (n + 1) 4 | 5 | for a, b in trust: 6 | trusted[a] -= 1 7 | trusted[b] += 1 8 | 9 | for i in range(1, n + 1): 10 | if trusted[i] == n - 1: 11 | return i 12 | 13 | return -1 14 | -------------------------------------------------------------------------------- /Find_Players_With_Zero_or_One_Losses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findWinners(self, matches: List[List[int]]) -> List[List[int]]: 3 | res = [[] for _ in range(2)] 4 | lose_times = {} 5 | 6 | for w, l in matches: 7 | if w not in lose_times: 8 | lose_times[w] = 0 9 | lose_times[l] = 1 + lose_times.get(l, 0) 10 | 11 | for player, lose_count in lose_times.items(): 12 | if lose_count < 2: 13 | res[lose_count].append(player) 14 | 15 | return [sorted(res[0]), sorted(res[1])] 16 | -------------------------------------------------------------------------------- /Find_Smallest_Letter_Greater_Than_Target.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreatestLetter(self, letters: List[str], target: str) -> str: 3 | left = 0 4 | right = len(letters) - 1 5 | 6 | while left <= right: 7 | mid = (left + right) // 2 8 | if letters[mid] <= target: 9 | left = mid + 1 10 | else: 11 | right = mid - 1 12 | 13 | if left == len(letters): 14 | return letters[0] 15 | else: 16 | return letters[left] 17 | -------------------------------------------------------------------------------- /Find_the_Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findTheDifference(string s, string t) { 4 | std::unordered_map count; 5 | 6 | for (char c : t) { 7 | count[c]++; 8 | } 9 | 10 | for (char c : s) { 11 | count[c]--; 12 | if (count[c] == 0) { 13 | count.erase(c); 14 | } 15 | } 16 | 17 | return count.begin()->first; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Find_the_Difference.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public char findTheDifference(String s, String t) { 3 | Map count = new HashMap<>(); 4 | 5 | for (char c : t.toCharArray()) { 6 | count.put(c, count.getOrDefault(c, 0) + 1); 7 | } 8 | 9 | for (char c : s.toCharArray()) { 10 | count.put(c, count.get(c) - 1); 11 | if (count.get(c) == 0) { 12 | count.remove(c); 13 | } 14 | } 15 | 16 | return (char) count.keySet().toArray()[0]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Find_the_Difference.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} t 4 | * @return {character} 5 | */ 6 | var findTheDifference = function(s, t) { 7 | const count = new Map(); 8 | 9 | for (const char of t) { 10 | count.set(char, (count.get(char) || 0) + 1); 11 | } 12 | 13 | for (const char of s) { 14 | count.set(char, count.get(char) - 1); 15 | if (count.get(char) === 0) { 16 | count.delete(char); 17 | } 18 | } 19 | 20 | return Array.from(count.keys())[0]; 21 | }; 22 | -------------------------------------------------------------------------------- /Find_the_Difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | # Initialize a dictionary to store character counts 4 | count = {} 5 | 6 | # Count characters in string t 7 | for c in t: 8 | count[c] = count.get(c, 0) + 1 9 | 10 | # Subtract counts for characters in string s 11 | for c in s: 12 | count[c] -= 1 13 | if count[c] == 0: 14 | del count[c] 15 | 16 | # The remaining character in the dictionary is the difference 17 | return list(count.keys())[0] 18 | -------------------------------------------------------------------------------- /Find_the_Duplicate_Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | int slow = nums[0]; 5 | int fast = nums[0]; 6 | 7 | while (true) { 8 | slow = nums[slow]; 9 | fast = nums[nums[fast]]; 10 | 11 | if (slow == fast) { 12 | break; 13 | } 14 | } 15 | 16 | int slow2 = nums[0]; 17 | 18 | while (slow != slow2) { 19 | slow = nums[slow]; 20 | slow2 = nums[slow2]; 21 | } 22 | 23 | return slow; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Find_the_Duplicate_Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findDuplicate(int[] nums) { 3 | int slow = nums[0]; 4 | int fast = nums[0]; 5 | 6 | while (true) { 7 | slow = nums[slow]; 8 | fast = nums[nums[fast]]; 9 | 10 | if (slow == fast) { 11 | break; 12 | } 13 | } 14 | 15 | int slow2 = nums[0]; 16 | 17 | while (slow != slow2) { 18 | slow = nums[slow]; 19 | slow2 = nums[slow2]; 20 | } 21 | 22 | return slow; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Find_the_Duplicate_Number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var findDuplicate = function(nums) { 6 | let slow = nums[0]; 7 | let fast = nums[0]; 8 | 9 | while (true) { 10 | slow = nums[slow]; 11 | fast = nums[nums[fast]]; 12 | 13 | if (slow === fast) { 14 | break; 15 | } 16 | } 17 | 18 | let slow2 = nums[0]; 19 | 20 | while (slow !== slow2) { 21 | slow = nums[slow]; 22 | slow2 = nums[slow2]; 23 | } 24 | 25 | return slow; 26 | }; 27 | -------------------------------------------------------------------------------- /Find_the_Duplicate_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | slow = nums[0] 4 | fast = nums[0] 5 | 6 | while True: 7 | slow = nums[slow] 8 | fast = nums[nums[fast]] 9 | if slow == fast: 10 | break 11 | 12 | slow2 = nums[0] 13 | while slow != slow2: 14 | slow = nums[slow] 15 | slow2 = nums[slow2] 16 | 17 | return slow 18 | -------------------------------------------------------------------------------- /Find_the_Highest_Altitude.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestAltitude(vector& gain) { 4 | int cur = 0; 5 | int highest = cur; 6 | 7 | for (int i = 0; i < gain.size(); i++) { 8 | int a = gain[i]; 9 | cur += a; 10 | highest = max(highest, cur); 11 | } 12 | 13 | return highest; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Find_the_Highest_Altitude.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int largestAltitude(int[] gain) { 3 | int cur = 0; 4 | int highest = cur; 5 | 6 | for (int i = 0; i < gain.length; i++) { 7 | int a = gain[i]; 8 | cur += a; 9 | highest = Math.max(highest, cur); 10 | } 11 | 12 | return highest; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Find_the_Highest_Altitude.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} gain 3 | * @return {number} 4 | */ 5 | var largestAltitude = function(gain) { 6 | let cur = 0; 7 | let highest = cur; 8 | 9 | for (let i = 0; i < gain.length; i++) { 10 | let a = gain[i]; 11 | cur += a; 12 | highest = Math.max(highest, cur); 13 | } 14 | 15 | return highest; 16 | }; 17 | -------------------------------------------------------------------------------- /Find_the_Highest_Altitude.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestAltitude(self, gain: List[int]) -> int: 3 | cur = 0 4 | highest = cur 5 | 6 | for a in gain: 7 | cur += a 8 | highest = max(highest, cur) 9 | 10 | return highest 11 | -------------------------------------------------------------------------------- /Find_the_Middle_Index_in_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMiddleIndex(vector& nums) { 4 | int left = 0; 5 | int right = 0; 6 | for (int num : nums) { 7 | right += num; 8 | } 9 | 10 | for (int i = 0; i < nums.size(); i++) { 11 | right -= nums[i]; 12 | 13 | if (left == right) { 14 | return i; 15 | } 16 | 17 | left += nums[i]; 18 | } 19 | 20 | return -1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Find_the_Middle_Index_in_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMiddleIndex(int[] nums) { 3 | int left = 0; 4 | int right = 0; 5 | for (int num : nums) { 6 | right += num; 7 | } 8 | 9 | for (int i = 0; i < nums.length; i++) { 10 | right -= nums[i]; 11 | 12 | if (left == right) { 13 | return i; 14 | } 15 | 16 | left += nums[i]; 17 | } 18 | 19 | return -1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Find_the_Middle_Index_in_Array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var findMiddleIndex = function(nums) { 6 | let left = 0; 7 | let right = nums.reduce((acc, curr) => acc + curr, 0); 8 | 9 | for (let i = 0; i < nums.length; i++) { 10 | right -= nums[i]; 11 | 12 | if (left === right) { 13 | return i; 14 | } 15 | 16 | left += nums[i]; 17 | } 18 | 19 | return -1; 20 | }; 21 | -------------------------------------------------------------------------------- /Find_the_Middle_Index_in_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMiddleIndex(self, nums: List[int]) -> int: 3 | left = 0 4 | right = sum(nums) 5 | 6 | for i, num in enumerate(nums): 7 | right -= num 8 | 9 | if left == right: 10 | return i 11 | 12 | left += num 13 | 14 | return -1 15 | -------------------------------------------------------------------------------- /Frog_Jump.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCross(self, stones: List[int]) -> bool: 3 | dp = {stone : set() for stone in stones} 4 | dp[0] = {0} 5 | 6 | for stone in stones: 7 | for jump in dp[stone]: 8 | for jump_distance in [jump - 1, jump, jump + 1]: 9 | if jump_distance > 0 and stone + jump_distance in dp: 10 | dp[stone + jump_distance].add(jump_distance) 11 | 12 | return len(dp[stones[-1]]) > 0 13 | -------------------------------------------------------------------------------- /Group_the_People_Given_the_Group_Size They_Belong_To.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: 3 | res = [] 4 | groups = defaultdict(list) 5 | 6 | for i, size in enumerate(groupSizes): 7 | groups[size].append(i) 8 | 9 | if len(groups[size]) == size: 10 | res.append(groups.pop(size)) 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /Implement_Stack_using_Queues_one.cpp: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | private: 3 | std::queue q; 4 | 5 | public: 6 | MyStack() {} 7 | 8 | void push(int x) { 9 | q.push(x); 10 | for (int i = 0; i < q.size() - 1; i++) { 11 | q.push(q.front()); 12 | q.pop(); 13 | } 14 | } 15 | 16 | int pop() { 17 | int top = q.front(); 18 | q.pop(); 19 | return top; 20 | } 21 | 22 | int top() { 23 | return q.front(); 24 | } 25 | 26 | bool empty() { 27 | return q.empty(); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Implement_Stack_using_Queues_one.java: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | 3 | private Queue q; 4 | 5 | public MyStack() { 6 | q = new LinkedList<>(); 7 | } 8 | 9 | public void push(int x) { 10 | q.add(x); 11 | for (int i = 0; i < q.size() - 1; i++) { 12 | q.add(q.poll()); 13 | } 14 | } 15 | 16 | public int pop() { 17 | return q.poll(); 18 | } 19 | 20 | public int top() { 21 | return q.peek(); 22 | } 23 | 24 | public boolean empty() { 25 | return q.isEmpty(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Implement_Stack_using_Queues_one.js: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | constructor() { 3 | this.q = []; 4 | } 5 | 6 | push(x) { 7 | this.q.push(x); 8 | for (let i = 0; i < this.q.length - 1; i++) { 9 | this.q.push(this.q.shift()); 10 | } 11 | } 12 | 13 | pop() { 14 | return this.q.shift(); 15 | } 16 | 17 | top() { 18 | return this.q[0]; 19 | } 20 | 21 | empty() { 22 | return this.q.length === 0; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Implement_Stack_using_Queues_one.py: -------------------------------------------------------------------------------- 1 | class MyStack: 2 | 3 | def __init__(self): 4 | self.q = deque() 5 | 6 | def push(self, x: int) -> None: 7 | self.q.append(x) 8 | for _ in range(len(self.q) - 1): 9 | self.q.append(self.q.popleft()) 10 | 11 | def pop(self) -> int: 12 | return self.q.popleft() 13 | 14 | def top(self) -> int: 15 | return self.q[0] 16 | 17 | def empty(self) -> bool: 18 | return len(self.q) == 0 19 | -------------------------------------------------------------------------------- /Integer_Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def integerBreak(self, n: int) -> int: 3 | if n == 2: 4 | return 1 5 | if n == 3: 6 | return 2 7 | 8 | # Try to divide n into as many threes as possible 9 | threes = n // 3 10 | remainder = n % 3 11 | 12 | if remainder == 1: 13 | threes -= 1 # remove 3 * 1 14 | remainder = 4 # create 2 * 2 15 | elif remainder == 0: 16 | remainder = 1 # when remainder is 0, set 1 which doesn't affect your answer. 17 | 18 | return (3 ** threes) * remainder 19 | -------------------------------------------------------------------------------- /K_Radius_Subarray_Averages.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getAverages(self, nums: List[int], k: int) -> List[int]: 3 | n = len(nums) 4 | avgs = [-1] * n 5 | target_length = k * 2 + 1 6 | total = sum(nums[0:target_length]) 7 | 8 | for c in range(k, n): 9 | if c + k < n: 10 | avgs[c] = total // target_length 11 | if c + k + 1 >= n: 12 | break 13 | total -= nums[c - k] 14 | total += nums[c + k + 1] 15 | 16 | return avgs 17 | -------------------------------------------------------------------------------- /Kth_Largest_Element_in_a_Stream.cpp: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | private: 3 | int k; 4 | priority_queue, greater> minHeap; 5 | 6 | public: 7 | KthLargest(int k, vector& nums) { 8 | this->k = k; 9 | for (int num : nums) { 10 | add(num); 11 | } 12 | } 13 | 14 | int add(int val) { 15 | minHeap.push(val); 16 | if (minHeap.size() > k) { 17 | minHeap.pop(); 18 | } 19 | return minHeap.top(); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Kth_Largest_Element_in_a_Stream.java: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | private int k; 3 | private PriorityQueue minHeap; 4 | 5 | public KthLargest(int k, int[] nums) { 6 | this.k = k; 7 | this.minHeap = new PriorityQueue<>(); 8 | for (int num : nums) { 9 | add(num); 10 | } 11 | } 12 | 13 | public int add(int val) { 14 | minHeap.offer(val); 15 | if (minHeap.size() > k) { 16 | minHeap.poll(); 17 | } 18 | return minHeap.peek(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Kth_Largest_Element_in_a_Stream.py: -------------------------------------------------------------------------------- 1 | class KthLargest: 2 | 3 | def __init__(self, k: int, nums: List[int]): 4 | self.k = k 5 | self.nums = nums 6 | heapq.heapify(self.nums) 7 | while len(self.nums) > self.k: 8 | heapq.heappop(self.nums) 9 | 10 | def add(self, val: int) -> int: 11 | heapq.heappush(self.nums, val) 12 | 13 | if len(self.nums) > self.k: 14 | heapq.heappop(self.nums) 15 | 16 | return self.nums[0] 17 | -------------------------------------------------------------------------------- /Largest_Substring_Between_Two_Equal_Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxLengthBetweenEqualCharacters(string s) { 4 | vector idx(26, 0); 5 | int res = -1; 6 | 7 | for (int i = 0; i < s.size(); ++i) { 8 | if (idx[s[i] - 'a'] == 0) { 9 | idx[s[i] - 'a'] = i + 1; 10 | } 11 | res = max(res, i - idx[s[i] - 'a']); 12 | } 13 | 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Largest_Substring_Between_Two_Equal_Characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxLengthBetweenEqualCharacters(String s) { 3 | int[] idx = new int[26]; 4 | int res = -1; 5 | 6 | for (int i = 0; i < s.length(); ++i) { 7 | if (idx[s.charAt(i) - 'a'] == 0) { 8 | idx[s.charAt(i) - 'a'] = i + 1; 9 | } 10 | res = Math.max(res, i - idx[s.charAt(i) - 'a']); 11 | } 12 | 13 | return res; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Largest_Substring_Between_Two_Equal_Characters.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var maxLengthBetweenEqualCharacters = function(s) { 6 | const idx = Array(26).fill(0); 7 | let res = -1; 8 | 9 | for (let i = 0; i < s.length; ++i) { 10 | if (idx[s.charCodeAt(i) - 'a'.charCodeAt(0)] === 0) { 11 | idx[s.charCodeAt(i) - 'a'.charCodeAt(0)] = i + 1; 12 | } 13 | res = Math.max(res, i - idx[s.charCodeAt(i) - 'a'.charCodeAt(0)]); 14 | } 15 | 16 | return res; 17 | }; 18 | -------------------------------------------------------------------------------- /Largest_Substring_Between_Two_Equal_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLengthBetweenEqualCharacters(self, s: str) -> int: 3 | idx = [0] * 26 4 | res = -1 5 | 6 | for i in range(len(s)): 7 | if idx[ord(s[i]) - ord("a")] == 0: 8 | idx[ord(s[i]) - ord("a")] = i + 1 9 | res = max(res, i - idx[ord(s[i]) - ord("a")]) 10 | 11 | return res 12 | -------------------------------------------------------------------------------- /Longest_Arithmetic_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestArithSeqLength(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | if n <= 2: 5 | return n 6 | 7 | dp = {} 8 | longest = 1 9 | 10 | for i in range(n): 11 | dp[i] = {} 12 | 13 | for j in range(i): 14 | diff = nums[i] - nums[j] 15 | dp[i][diff] = dp[j].get(diff, 1) + 1 16 | longest = max(longest, dp[i][diff]) 17 | 18 | return longest 19 | -------------------------------------------------------------------------------- /Longest_Arithmetic_Subsequence_of_Given_Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubsequence(vector& arr, int difference) { 4 | std::unordered_map dp; 5 | int maxLength = 0; 6 | 7 | for (int n : arr) { 8 | if (dp.count(n - difference)) { 9 | dp[n] = dp[n - difference] + 1; 10 | } else { 11 | dp[n] = 1; 12 | } 13 | 14 | maxLength = std::max(maxLength, dp[n]); 15 | } 16 | 17 | return maxLength; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Longest_Arithmetic_Subsequence_of_Given_Difference.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestSubsequence(int[] arr, int difference) { 3 | Map dp = new HashMap<>(); 4 | int maxLength = 0; 5 | 6 | for (int n : arr) { 7 | if (dp.containsKey(n - difference)) { 8 | dp.put(n, dp.get(n - difference) + 1); 9 | } else { 10 | dp.put(n, 1); 11 | } 12 | 13 | maxLength = Math.max(maxLength, dp.get(n)); 14 | } 15 | 16 | return maxLength; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Longest_Arithmetic_Subsequence_of_Given_Difference.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} difference 4 | * @return {number} 5 | */ 6 | var longestSubsequence = function(arr, difference) { 7 | let dp = {}; 8 | let max_length = 0; 9 | 10 | for (let n of arr) { 11 | if (n - difference in dp) { 12 | dp[n] = dp[n - difference] + 1; 13 | } else { 14 | dp[n] = 1; 15 | } 16 | 17 | max_length = Math.max(max_length, dp[n]); 18 | } 19 | 20 | return max_length; 21 | }; 22 | -------------------------------------------------------------------------------- /Longest_Arithmetic_Subsequence_of_Given_Difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestSubsequence(self, arr: List[int], difference: int) -> int: 3 | dp = {} 4 | max_length = 0 5 | 6 | for n in arr: 7 | if n - difference in dp: 8 | dp[n] = dp[n - difference] + 1 9 | else: 10 | dp[n] = 1 11 | 12 | max_length = max(max_length, dp[n]) 13 | 14 | return max_length 15 | -------------------------------------------------------------------------------- /Longest_Common_Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | dp = [0] * len(text1) 4 | longest = 0 5 | 6 | for c in text2: 7 | cur_length = 0 8 | for i, val in enumerate(dp): 9 | if cur_length < val: 10 | cur_length = val 11 | elif c == text1[i]: 12 | dp[i] = cur_length + 1 13 | longest = max(longest, cur_length + 1) 14 | 15 | return longest 16 | -------------------------------------------------------------------------------- /Longest_Subarray_of_1's_After_Deleting_One_Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(vector& nums) { 4 | int left = 0; 5 | int max_length = 0; 6 | int last_zero = -1; 7 | 8 | for (int right = 0; right < nums.size(); right++) { 9 | if (nums[right] == 0) { 10 | left = last_zero + 1; 11 | last_zero = right; 12 | } 13 | 14 | max_length = max(max_length, right - left); 15 | } 16 | 17 | return max_length; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Longest_Subarray_of_1's_After_Deleting_One_Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestSubarray(int[] nums) { 3 | int left = 0; 4 | int max_length = 0; 5 | int last_zero = -1; 6 | 7 | for (int right = 0; right < nums.length; right++) { 8 | if (nums[right] == 0) { 9 | left = last_zero + 1; 10 | last_zero = right; 11 | } 12 | 13 | max_length = Math.max(max_length, right - left); 14 | } 15 | 16 | return max_length; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Longest_Subarray_of_1's_After_Deleting_One_Element.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var longestSubarray = function(nums) { 6 | let left = 0; 7 | let max_length = 0; 8 | let last_zero = -1; 9 | 10 | for (let right = 0; right < nums.length; right++) { 11 | if (nums[right] === 0) { 12 | left = last_zero + 1; 13 | last_zero = right; 14 | } 15 | 16 | max_length = Math.max(max_length, right - left); 17 | } 18 | 19 | return max_length; 20 | }; 21 | -------------------------------------------------------------------------------- /Longest_Subarray_of_1's_After_Deleting_One_Element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestSubarray(self, nums: List[int]) -> int: 3 | 4 | left = 0 5 | max_length = 0 6 | last_zero = -1 7 | 8 | for right in range(len(nums)): 9 | if nums[right] == 0: 10 | left = last_zero + 1 11 | last_zero = right 12 | 13 | max_length = max(max_length, right - left) 14 | 15 | return max_length 16 | -------------------------------------------------------------------------------- /Maximize_the_Confusion_of_an_Exam.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: 3 | window_size = 0 4 | count = {"T":0, "F":0} 5 | 6 | for right in range(len(answerKey)): 7 | count[answerKey[right]] += 1 8 | minor = min(count["T"], count["F"]) 9 | 10 | if minor <= k: 11 | window_size += 1 12 | else: 13 | count[answerKey[right - window_size]] -= 1 14 | 15 | return window_size 16 | -------------------------------------------------------------------------------- /Maximum_Length_of_Pair_Chain.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findLongestChain(int[][] pairs) { 3 | Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); 4 | 5 | int[] prev = pairs[0]; 6 | int res = 1; 7 | 8 | for (int i = 1; i < pairs.length; i++) { 9 | int[] cur = pairs[i]; 10 | if (cur[0] > prev[1]) { 11 | res++; 12 | prev = cur; 13 | } 14 | } 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Maximum_Length_of_Pair_Chain.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} pairs 3 | * @return {number} 4 | */ 5 | var findLongestChain = function(pairs) { 6 | pairs.sort((a, b) => a[1] - b[1]); 7 | 8 | let prev = pairs[0]; 9 | let res = 1; 10 | 11 | for (let i = 1; i < pairs.length; i++) { 12 | const cur = pairs[i]; 13 | if (cur[0] > prev[1]) { 14 | res++; 15 | prev = cur; 16 | } 17 | } 18 | 19 | return res; 20 | }; 21 | -------------------------------------------------------------------------------- /Maximum_Length_of_Pair_Chain.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLongestChain(self, pairs: List[List[int]]) -> int: 3 | pairs.sort(key=lambda x: x[1]) 4 | 5 | prev = pairs[0] 6 | res = 1 7 | 8 | for cur in pairs[1:]: 9 | if cur[0] > prev[1]: 10 | res += 1 11 | prev = cur 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /Maximum_Length_of_a_Concatenated_String_with_Unique_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLength(self, arr: List[str]) -> int: 3 | uniq_comb = [""] 4 | max_length = 0 5 | 6 | for i in range(len(arr)): 7 | for j in range(len(uniq_comb)): 8 | new_comb = arr[i] + uniq_comb[j] 9 | 10 | if len(set(new_comb)) == len(new_comb): 11 | uniq_comb.append(new_comb) 12 | max_length = max(max_length, len(new_comb)) 13 | 14 | return max_length 15 | -------------------------------------------------------------------------------- /Maximum_Number_of_Events_That_Can_Be_Attended_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxValue(self, events: List[List[int]], k: int) -> int: 3 | events.sort(key=lambda x: x[1]) 4 | cur, temp = [[0, 0]], [[0, 0]] 5 | 6 | for _ in range(k): 7 | for start, end, value in events: 8 | i = bisect.bisect(cur, [start]) - 1 9 | if cur[i][1] + value > temp[-1][1]: 10 | temp.append([end, cur[i][1] + value]) 11 | 12 | cur, temp = temp, [[0, 0]] 13 | 14 | return cur[-1][-1] 15 | -------------------------------------------------------------------------------- /Maximum_Profit_in_Job_Scheduling.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: 3 | max_profit = 0 4 | jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)]) 5 | heap = [] # (endTime, profit) 6 | 7 | for s, e, p in jobs: 8 | while heap and s >= heap[0][0]: 9 | max_profit = max(max_profit, heapq.heappop(heap)[1]) 10 | 11 | heapq.heappush(heap, (e, p + max_profit)) 12 | 13 | return max(p for _, p in heap) 14 | -------------------------------------------------------------------------------- /Maximum_Running_Time_of_N_Computers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxRunTime(self, n: int, batteries: List[int]) -> int: 3 | batteries.sort() 4 | charging = batteries[-n:] 5 | total_extra = sum(batteries[:-n]) 6 | 7 | for i in range(n-1): 8 | if total_extra // (i + 1) < charging[i+1] - charging[i]: 9 | return charging[i] + total_extra // (i + 1) 10 | 11 | total_extra -= (charging[i+1] - charging[i]) * (i + 1) 12 | 13 | return charging[-1] + total_extra // n 14 | -------------------------------------------------------------------------------- /Minimum_Deletions_to_Make_Character_Frequencies_Unique.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var minDeletions = function(s) { 6 | const chars = new Map(); 7 | for (const char of s) { 8 | chars.set(char, (chars.get(char) || 0) + 1); 9 | } 10 | 11 | const uniqSet = new Set(); 12 | let count = 0; 13 | 14 | for (let freq of chars.values()) { 15 | while (freq > 0 && uniqSet.has(freq)) { 16 | freq--; 17 | count++; 18 | } 19 | 20 | uniqSet.add(freq); 21 | } 22 | 23 | return count; 24 | }; 25 | -------------------------------------------------------------------------------- /Minimum_Deletions_to_Make_Character_Frequencies_Unique.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDeletions(self, s: str) -> int: 3 | chars = Counter(s) 4 | 5 | uniq_set = set() 6 | count = 0 7 | 8 | for freq in chars.values(): 9 | while freq > 0 and freq in uniq_set: 10 | freq -= 1 11 | count += 1 12 | 13 | uniq_set.add(freq) 14 | 15 | return count 16 | -------------------------------------------------------------------------------- /Minimum_Falling_Path_Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFallingPathSum(vector>& m) { 4 | for (auto r = 1; r < m.size(); ++r) 5 | for (auto c = 0; c < m.size(); ++c) 6 | m[r][c] += min({ 7 | m[r - 1][max(0,c - 1)], 8 | m[r - 1][c], 9 | m[r - 1][min((int)m.size() - 1, c + 1)] } 10 | ); 11 | 12 | return *min_element(begin(m[m.size() - 1]), end(m[m.size() - 1])); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Minimum_Falling_Path_Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minFallingPathSum(int[][] m) { 3 | for (int r = 1; r < m.length; ++r) 4 | for (int c = 0; c < m.length; ++c) 5 | m[r][c] += Math.min( 6 | m[r - 1][c], 7 | Math.min(m[r - 1][Math.max(0, c - 1)], m[r - 1][Math.min(m.length - 1, c + 1)]) 8 | ); 9 | 10 | return Arrays.stream(m[m.length - 1]).min().getAsInt(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Minimum_Falling_Path_Sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number} 4 | */ 5 | var minFallingPathSum = function(m) { 6 | const n = m.length; 7 | for (let r = 1; r < n; ++r) { 8 | for (let c = 0; c < n; ++c) { 9 | m[r][c] += Math.min( 10 | m[r - 1][Math.max(0, c - 1)], 11 | m[r - 1][c], 12 | m[r - 1][Math.min(n - 1, c + 1)] 13 | ); 14 | } 15 | } 16 | return Math.min(...m[n - 1]); 17 | }; 18 | -------------------------------------------------------------------------------- /Minimum_Falling_Path_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minFallingPathSum(self, m: List[List[int]]) -> int: 3 | n = len(m) 4 | for r in range(1, n): 5 | for c in range(n): 6 | m[r][c] += min( 7 | m[r - 1][max(0, c - 1)], 8 | m[r - 1][c], 9 | m[r - 1][min(n - 1, c + 1)] 10 | ) 11 | 12 | return min(m[-1]) 13 | -------------------------------------------------------------------------------- /Minimum_Number_of_Operations_to_Make_Array_Continuous.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | length = len(nums) 4 | min_operations = length 5 | unique_nums = sorted(set(nums)) 6 | right = 0 7 | 8 | for left in range(len(unique_nums)): 9 | while right < len(unique_nums) and unique_nums[right] < unique_nums[left] + length: 10 | right += 1 11 | 12 | min_operations = min(min_operations, length - (right - left)) 13 | 14 | return min_operations 15 | -------------------------------------------------------------------------------- /Minimum_Number_of_Operations_to_Make_Array_Empty.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | unordered_map freq; 5 | 6 | for (int n : nums) { 7 | freq[n] = 1 + freq[n]; 8 | } 9 | 10 | if (any_of(freq.begin(), freq.end(), [](const auto& kv) { return kv.second == 1; })) { 11 | return -1; 12 | } 13 | 14 | return accumulate(freq.begin(), freq.end(), 0, [](int sum, const auto& kv) { return sum + (kv.second + 2) / 3; }); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Minimum_Number_of_Operations_to_Make_Array_Empty.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(int[] nums) { 3 | HashMap freq = new HashMap<>(); 4 | 5 | for (int n : nums) { 6 | freq.put(n, 1 + freq.getOrDefault(n, 0)); 7 | } 8 | 9 | if (freq.containsValue(1)) { 10 | return -1; 11 | } 12 | 13 | return freq.values().stream().mapToInt(f -> (f + 2) / 3).sum(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Minimum_Number_of_Operations_to_Make_Array_Empty.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var minOperations = function(nums) { 6 | const freq = new Map(); 7 | 8 | for (const n of nums) { 9 | freq.set(n, 1 + (freq.get(n) || 0)); 10 | } 11 | 12 | if ([...freq.values()].includes(1)) { 13 | return -1; 14 | } 15 | 16 | return [...freq.values()].reduce((sum, f) => sum + Math.floor((f + 2) / 3), 0); 17 | }; 18 | -------------------------------------------------------------------------------- /Minimum_Number_of_Operations_to_Make_Array_Empty.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | freq = {} 4 | 5 | for n in nums: 6 | freq[n] = 1 + freq.get(n, 0) 7 | 8 | if 1 in freq.values(): 9 | return -1 10 | 11 | return sum((f + 2) // 3 for f in freq.values()) 12 | -------------------------------------------------------------------------------- /Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSteps(string s, string t) { 4 | unordered_map sCount; 5 | 6 | for (char c : s) { 7 | sCount[c] = 1 + sCount[c]; 8 | } 9 | 10 | int change = 0; 11 | for (char c : t) { 12 | if (sCount.find(c) == sCount.end() || sCount[c] == 0) { 13 | change += 1; 14 | } else { 15 | sCount[c] -= 1; 16 | } 17 | } 18 | 19 | return change; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} t 4 | * @return {number} 5 | */ 6 | var minSteps = function(s, t) { 7 | const sCount = {}; 8 | 9 | for (const c of s) { 10 | sCount[c] = 1 + (sCount[c] || 0); 11 | } 12 | 13 | let change = 0; 14 | for (const c of t) { 15 | if (!sCount[c] || sCount[c] === 0) { 16 | change += 1; 17 | } else { 18 | sCount[c] -= 1; 19 | } 20 | } 21 | 22 | return change; 23 | }; 24 | -------------------------------------------------------------------------------- /Minimum_Number_of_Steps_to_Make_Two_Strings_Anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSteps(self, s: str, t: str) -> int: 3 | s_count = {} 4 | 5 | for c in s: 6 | s_count[c] = 1 + s_count.get(c, 0) 7 | 8 | change = 0 9 | for c in t: 10 | if c not in s_count or s_count[c] == 0: 11 | change += 1 12 | else: 13 | s_count[c] -= 1 14 | 15 | return change 16 | -------------------------------------------------------------------------------- /Minimum_Penalty_for_a_Shop.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bestClosingTime(string customers) { 4 | int res = 0; 5 | int customerLeft = 0; 6 | 7 | for (int i = 0; i < customers.length(); i++) { 8 | if (customers[i] == 'Y') { 9 | customerLeft++; 10 | 11 | if (customerLeft > 0) { 12 | res = i + 1; 13 | customerLeft = 0; 14 | } 15 | } else { 16 | customerLeft--; 17 | } 18 | } 19 | 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Minimum_Penalty_for_a_Shop.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int bestClosingTime(String customers) { 3 | int res = 0; 4 | int customerLeft = 0; 5 | 6 | for (int i = 0; i < customers.length(); i++) { 7 | if (customers.charAt(i) == 'Y') { 8 | customerLeft++; 9 | 10 | if (customerLeft > 0) { 11 | res = i + 1; 12 | customerLeft = 0; 13 | } 14 | } else { 15 | customerLeft--; 16 | } 17 | } 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Minimum_Penalty_for_a_Shop.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} customers 3 | * @return {number} 4 | */ 5 | var bestClosingTime = function(customers) { 6 | let res = 0; 7 | let customerLeft = 0; 8 | 9 | for (let i = 0; i < customers.length; i++) { 10 | if (customers[i] === 'Y') { 11 | customerLeft++; 12 | 13 | if (customerLeft > 0) { 14 | res = i + 1; 15 | customerLeft = 0; 16 | } 17 | } else { 18 | customerLeft--; 19 | } 20 | } 21 | 22 | return res; 23 | }; 24 | -------------------------------------------------------------------------------- /Minimum_Penalty_for_a_Shop.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bestClosingTime(self, customers: str) -> int: 3 | res = 0 4 | customer_left = 0 5 | 6 | for i in range(len(customers)): 7 | if customers[i] == 'Y': 8 | customer_left += 1 9 | 10 | if customer_left > 0: 11 | res = i + 1 12 | customer_left = 0 13 | else: 14 | customer_left -= 1 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /Minimum_Size_Subarray_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, target: int, nums: List[int]) -> int: 3 | min_len = float("inf") 4 | left = 0 5 | cur_sum = 0 6 | 7 | for right in range(len(nums)): 8 | cur_sum += nums[right] 9 | 10 | while cur_sum >= target: 11 | if right - left + 1 < min_len: 12 | min_len = right - left + 1 13 | cur_sum -= nums[left] 14 | left += 1 15 | 16 | return min_len if min_len != float("inf") else 0 17 | -------------------------------------------------------------------------------- /Modify_the_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]: 3 | m = len(matrix) # row 4 | n = len(matrix[0]) # column 5 | answer = matrix.copy() 6 | 7 | for c in range(n): 8 | max_val = max(matrix[r][c] for r in range(m)) 9 | for r in range(m): 10 | if matrix[r][c] == -1: 11 | answer[r][c] = max_val 12 | 13 | return answer 14 | -------------------------------------------------------------------------------- /Monotonic_Array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var isMonotonic = function(nums) { 6 | const n = nums.length; 7 | if (n === 1) return true; 8 | 9 | let isInc = true; 10 | let isDec = true; 11 | 12 | for (let i = 1; i < n; i++) { 13 | if (!isInc && !isDec) { 14 | return false; 15 | } 16 | 17 | if (nums[i] < nums[i - 1]) { 18 | isInc = false; 19 | } 20 | if (nums[i] > nums[i - 1]) { 21 | isDec = false; 22 | } 23 | } 24 | 25 | return isInc || isDec; 26 | }; 27 | -------------------------------------------------------------------------------- /Monotonic_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMonotonic(self, nums: List[int]) -> bool: 3 | n = len(nums) 4 | if n == 1: return True 5 | 6 | is_inc = True 7 | is_dec = True 8 | 9 | for i in range(1, n): 10 | if not is_inc and not is_dec: 11 | return False 12 | 13 | if nums[i] < nums[i-1]: 14 | is_inc = False 15 | 16 | if nums[i] > nums[i-1]: 17 | is_dec = False 18 | 19 | return is_inc or is_dec 20 | -------------------------------------------------------------------------------- /Number_of_Good_Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIdenticalPairs(vector& nums) { 4 | unordered_map pairs; 5 | int count = 0; 6 | 7 | for (int i = 0; i < nums.size(); i++) { 8 | if (pairs.find(nums[i]) != pairs.end()) { 9 | count += pairs[nums[i]]; 10 | } 11 | pairs[nums[i]] = pairs[nums[i]] + 1; 12 | } 13 | 14 | return count; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Number_of_Good_Pairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numIdenticalPairs(int[] nums) { 3 | Map pairs = new HashMap<>(); 4 | int count = 0; 5 | 6 | for (int i = 0; i < nums.length; i++) { 7 | if (pairs.containsKey(nums[i])) { 8 | count += pairs.get(nums[i]); 9 | } 10 | pairs.put(nums[i], pairs.getOrDefault(nums[i], 0) + 1); 11 | } 12 | 13 | return count; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Number_of_Good_Pairs.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var numIdenticalPairs = function(nums) { 6 | const pairs = {}; 7 | let count = 0; 8 | 9 | for (let i = 0; i < nums.length; i++) { 10 | if (nums[i] in pairs) { 11 | count += pairs[nums[i]]; 12 | } 13 | 14 | pairs[nums[i]] = (pairs[nums[i]] || 0) + 1; 15 | } 16 | 17 | return count; 18 | }; 19 | -------------------------------------------------------------------------------- /Number_of_Good_Pairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIdenticalPairs(self, nums: List[int]) -> int: 3 | pairs = {} 4 | count = 0 5 | 6 | for i in range(len(nums)): 7 | if nums[i] in pairs: 8 | count += pairs[nums[i]] 9 | 10 | pairs[nums[i]] = pairs.get(nums[i], 0) + 1 11 | 12 | return count 13 | -------------------------------------------------------------------------------- /Number_of_Laser_Beams_in_a_Bank.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfBeams(String[] bank) { 3 | int res = 0; 4 | int prev = 0; 5 | 6 | for (String r : bank) { 7 | int cur = 0; 8 | for (int c = 0; c < r.length(); c++) { 9 | if (r.charAt(c) == '1') { 10 | cur += 1; 11 | } 12 | } 13 | 14 | res += cur * prev; 15 | 16 | if (cur > 0) { 17 | prev = cur; 18 | } 19 | } 20 | 21 | return res; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Number_of_Laser_Beams_in_a_Bank.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} bank 3 | * @return {number} 4 | */ 5 | var numberOfBeams = function(bank) { 6 | let res = 0; 7 | let prev = 0; 8 | 9 | for (let r = 0; r < bank.length; r++) { 10 | let cur = 0; 11 | for (let c = 0; c < bank[0].length; c++) { 12 | if (bank[r][c] === "1") { 13 | cur += 1; 14 | } 15 | } 16 | 17 | res += cur * prev; 18 | 19 | if (cur > 0) { 20 | prev = cur; 21 | } 22 | } 23 | 24 | return res; 25 | }; 26 | -------------------------------------------------------------------------------- /Number_of_Laser_Beams_in_a_Bank.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfBeams(self, bank: List[str]) -> int: 3 | res = prev = 0 4 | 5 | for r in range(len(bank)): 6 | cur = 0 7 | for c in range(len(bank[0])): 8 | if bank[r][c] == "1": 9 | cur += 1 10 | 11 | res += cur * prev 12 | 13 | if cur > 0: 14 | prev = cur 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /Number_of_Music_Playlists.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: 3 | mod = 10**9 + 7 4 | 5 | dp = [[0 for _ in range(n + 1)] for _ in range(goal + 1)] 6 | dp[0][0] = 1 7 | 8 | for i in range(1, goal + 1): 9 | for j in range(1, min(i, n) + 1): 10 | dp[i][j] = dp[i-1][j-1] * (n - j + 1) % mod 11 | 12 | if j > k: 13 | dp[i][j] = (dp[i][j] + dp[i-1][j] * (j-k)) % mod 14 | 15 | return dp[goal][n] 16 | -------------------------------------------------------------------------------- /Palindromic_Substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | res = 0 4 | 5 | def count_palindrome(s, left, right): 6 | count = 0 7 | while left >= 0 and right < len(s) and s[left] == s[right]: 8 | count += 1 9 | left -= 1 10 | right += 1 11 | 12 | return count 13 | 14 | for i in range(len(s)): 15 | res += count_palindrome(s, i, i) 16 | res += count_palindrome(s, i, i + 1) 17 | 18 | return res 19 | -------------------------------------------------------------------------------- /Partition Array for Maximum Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSumAfterPartitioning(vector& arr, int k) { 4 | int n = arr.size(); 5 | vector maxSum(n + 1); 6 | 7 | for (int i = 1; i <= n; i++) { 8 | int mpn = INT_MIN; 9 | for (int mpnCount = 1; mpnCount <= min(i, k); mpnCount++) { 10 | mpn = max(mpn, arr[i - mpnCount]); 11 | maxSum[i] = max(maxSum[i], maxSum[i - mpnCount] + mpn * mpnCount); 12 | } 13 | } 14 | 15 | return maxSum[n]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Partition Array for Maximum Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSumAfterPartitioning(int[] arr, int k) { 3 | int n = arr.length; 4 | int[] maxSum = new int[n + 1]; 5 | 6 | for (int i = 1; i <= n; i++) { 7 | int mpn = Integer.MIN_VALUE; 8 | for (int mpnCount = 1; mpnCount <= Math.min(i, k); mpnCount++) { 9 | mpn = Math.max(mpn, arr[i - mpnCount]); 10 | maxSum[i] = Math.max(maxSum[i], maxSum[i - mpnCount] + mpn * mpnCount); 11 | } 12 | } 13 | 14 | return maxSum[n]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Partition Array for Maximum Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: 3 | n = len(arr) 4 | max_sum = [0] * (n + 1) 5 | 6 | for i in range(1, n + 1): 7 | mpn = float("-inf") 8 | for mpn_count in range(1, min(i, k) + 1): 9 | mpn = max(mpn, arr[i - mpn_count]) 10 | max_sum[i] = max(max_sum[i], max_sum[i - mpn_count] + mpn * mpn_count) 11 | 12 | return max_sum[n] 13 | -------------------------------------------------------------------------------- /Peak_Index_in_a_Mountain_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& arr) { 4 | int left = 0; 5 | int right = arr.size() - 1; 6 | 7 | while (left < right) { 8 | int mid = (left + right) / 2; 9 | 10 | if (arr[mid] < arr[mid + 1]) { 11 | left = mid + 1; 12 | } else { 13 | right = mid; 14 | } 15 | } 16 | 17 | return left; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Peak_Index_in_a_Mountain_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int peakIndexInMountainArray(int[] arr) { 3 | int left = 0; 4 | int right = arr.length - 1; 5 | 6 | while (left < right) { 7 | int mid = (left + right) / 2; 8 | 9 | if (arr[mid] < arr[mid + 1]) { 10 | left = mid + 1; 11 | } else { 12 | right = mid; 13 | } 14 | } 15 | 16 | return left; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Peak_Index_in_a_Mountain_Array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {number} 4 | */ 5 | var peakIndexInMountainArray = function(arr) { 6 | let left = 0; 7 | let right = arr.length - 1; 8 | 9 | while (left < right) { 10 | let mid = Math.floor((left + right) / 2); 11 | 12 | if (arr[mid] < arr[mid + 1]) { 13 | left = mid + 1; 14 | } else { 15 | right = mid; 16 | } 17 | } 18 | 19 | return left; 20 | }; 21 | -------------------------------------------------------------------------------- /Peak_Index_in_a_Mountain_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def peakIndexInMountainArray(self, arr: List[int]) -> int: 3 | 4 | left = 0 5 | right = len(arr) - 1 6 | 7 | while left < right: 8 | mid = (left + right) // 2 9 | 10 | if arr[mid] < arr[mid + 1]: 11 | left = mid + 1 12 | else: 13 | right = mid 14 | 15 | return left 16 | -------------------------------------------------------------------------------- /Permutations.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[][]} 4 | */ 5 | var permute = function(nums) { 6 | if (nums.length === 1) { 7 | return [nums.slice()]; 8 | } 9 | 10 | var res = []; 11 | 12 | for (var i = 0; i < nums.length; i++) { 13 | var n = nums.shift(); 14 | var perms = permute(nums.slice()); 15 | 16 | for (var p of perms) { 17 | p.push(n); 18 | } 19 | 20 | res.push(...perms); 21 | nums.push(n); 22 | } 23 | 24 | return res; 25 | }; 26 | -------------------------------------------------------------------------------- /Permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | if len(nums) == 1: 4 | return [nums[:]] 5 | 6 | res = [] 7 | 8 | for _ in range(len(nums)): 9 | n = nums.pop(0) 10 | perms = self.permute(nums) 11 | 12 | for p in perms: 13 | p.append(n) 14 | 15 | res.extend(perms) 16 | nums.append(n) 17 | 18 | return res 19 | -------------------------------------------------------------------------------- /Permutations2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | 4 | def backtrack(start): 5 | if start == len(nums): 6 | res.append(nums[:]) 7 | return 8 | 9 | for i in range(start, len(nums)): 10 | nums[start], nums[i] = nums[i], nums[start] 11 | backtrack(start + 1) 12 | nums[start], nums[i] = nums[i], nums[start] 13 | 14 | res = [] 15 | backtrack(0) 16 | return res 17 | -------------------------------------------------------------------------------- /Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | return binaryExp(x, static_cast(n)); 5 | } 6 | 7 | private: 8 | double binaryExp(double x, long n) { 9 | if (n == 0) { 10 | return 1; 11 | } 12 | 13 | if (n < 0) { 14 | return 1.0 / binaryExp(x, -n); 15 | } 16 | 17 | if (n % 2 == 1) { 18 | return x * binaryExp(x * x, (n - 1) / 2); 19 | } else { 20 | return binaryExp(x * x, n / 2); 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Pow(x, n).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | return binaryExp(x, (long) n); 4 | } 5 | 6 | private double binaryExp(double x, long n) { 7 | if (n == 0) { 8 | return 1; 9 | } 10 | 11 | if (n < 0) { 12 | return 1.0 / binaryExp(x, -n); 13 | } 14 | 15 | if (n % 2 == 1) { 16 | return x * binaryExp(x * x, (n - 1) / 2); 17 | } else { 18 | return binaryExp(x * x, n / 2); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Pow(x, n).js: -------------------------------------------------------------------------------- 1 | function myPow(x, n) { 2 | function calc_power(x, n) { 3 | if (x === 0) { 4 | return 0; 5 | } 6 | if (n === 0) { 7 | return 1; 8 | } 9 | 10 | let res = calc_power(x, Math.floor(n / 2)); 11 | res = res * res; 12 | 13 | if (n % 2 === 1) { 14 | return res * x; 15 | } 16 | 17 | return res; 18 | } 19 | 20 | let ans = calc_power(x, Math.abs(n)); 21 | 22 | if (n >= 0) { 23 | return ans; 24 | } 25 | 26 | return 1 / ans; 27 | } 28 | -------------------------------------------------------------------------------- /Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | 4 | def calc_power(x, n): 5 | if x == 0: 6 | return 0 7 | if n == 0: 8 | return 1 9 | 10 | res = calc_power(x, n // 2) 11 | res = res * res 12 | 13 | if n % 2 == 1: 14 | return res * x 15 | 16 | return res 17 | 18 | ans = calc_power(x, abs(n)) 19 | 20 | if n >= 0: 21 | return ans 22 | 23 | return 1 / ans 24 | -------------------------------------------------------------------------------- /Predict_the_Winner.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool PredictTheWinner(vector& nums) { 4 | int n = nums.size(); 5 | vector max_diff(n, 0); 6 | 7 | for (int i = n - 1; i >= 0; i--) { 8 | max_diff[i] = nums[i]; 9 | for (int j = i + 1; j < n; j++) { 10 | max_diff[j] = max(nums[i] - max_diff[j], nums[j] - max_diff[j - 1]); 11 | } 12 | } 13 | 14 | return max_diff[n - 1] >= 0; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Predict_the_Winner.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean PredictTheWinner(int[] nums) { 3 | int n = nums.length; 4 | int[] max_diff = new int[n]; 5 | 6 | for (int i = n - 1; i >= 0; i--) { 7 | max_diff[i] = nums[i]; 8 | for (int j = i + 1; j < n; j++) { 9 | max_diff[j] = Math.max(nums[i] - max_diff[j], nums[j] - max_diff[j - 1]); 10 | } 11 | } 12 | 13 | return max_diff[n - 1] >= 0; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Predict_the_Winner.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var PredictTheWinner = function(nums) { 6 | const n = nums.length; 7 | const max_diff = new Array(n).fill(0); 8 | 9 | for (let i = n - 1; i >= 0; i--) { 10 | max_diff[i] = nums[i]; 11 | for (let j = i + 1; j < n; j++) { 12 | max_diff[j] = Math.max(nums[i] - max_diff[j], nums[j] - max_diff[j - 1]); 13 | } 14 | } 15 | 16 | return max_diff[n - 1] >= 0; 17 | }; 18 | -------------------------------------------------------------------------------- /Predict_the_Winner.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def PredictTheWinner(self, nums: List[int]) -> bool: 3 | n = len(nums) 4 | max_diff = [0] * n 5 | 6 | for i in range(n - 1, -1, -1): 7 | max_diff[i] = nums[i] 8 | for j in range(i + 1, n): 9 | max_diff[j] = max(nums[i] - max_diff[j], nums[j] - max_diff[j - 1]) 10 | 11 | return max_diff[n - 1] >= 0 12 | -------------------------------------------------------------------------------- /Put_Marbles_in_Bags.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long putMarbles(vector& weights, int k) { 4 | int n = weights.size(); 5 | vector scores(n - 1, 0); 6 | 7 | for (int i = 0; i < n - 1; ++i) { 8 | scores[i] += weights[i] + weights[i + 1]; 9 | } 10 | 11 | sort(scores.begin(), scores.end()); 12 | 13 | long long answer = 0; 14 | for (int i = 0; i < k - 1; ++i) { 15 | answer += scores[n - 2 - i] - scores[i]; 16 | } 17 | 18 | return answer; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Put_Marbles_in_Bags.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long putMarbles(int[] weights, int k) { 3 | int n = weights.length; 4 | int[] scores = new int[n - 1]; 5 | 6 | for (int i = 0; i < n - 1; ++i) { 7 | scores[i] = weights[i] + weights[i + 1]; 8 | } 9 | 10 | Arrays.sort(scores, 0, n - 1); 11 | 12 | long answer = 0l; 13 | for (int i = 0; i < k - 1; ++i) { 14 | answer += scores[n - 2 - i] - scores[i]; 15 | } 16 | 17 | return answer; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Put_Marbles_in_Bags.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} weights 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var putMarbles = function(weights, k) { 7 | let scores = []; 8 | for (let i = 0; i < weights.length - 1; i++) { 9 | scores.push(weights[i] + weights[i + 1]); 10 | } 11 | 12 | scores.sort((a, b) => a - b); 13 | 14 | let minScore = scores.slice(0, k - 1).reduce((acc, val) => acc + val, 0); 15 | let maxScore = scores.slice(scores.length - k + 1).reduce((acc, val) => acc + val, 0); 16 | 17 | return maxScore - minScore; 18 | }; 19 | -------------------------------------------------------------------------------- /Put_Marbles_in_Bags.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def putMarbles(self, weights: List[int], k: int) -> int: 3 | scores = [] 4 | for w1, w2 in zip(weights, weights[1:]): 5 | scores.append(w1 + w2) 6 | 7 | scores.sort() 8 | 9 | min_score = sum(scores[:k-1]) 10 | max_score = sum(scores[len(scores) - k + 1:]) 11 | 12 | return max_score - min_score 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodingNinja(Ex-Amazon) 2 | I create a lot of youtube videos to prepare for the next coming technical interview. 3 | I hope my videos help you understand leetcode problem solutions quickly. 4 | 5 | # YouTube channel 6 | https://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww 7 | -------------------------------------------------------------------------------- /Rearrange Array Elements by Sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int pi = 0; 5 | int ni = 1; 6 | vector res(nums.size(), 0); 7 | 8 | for (int n : nums) { 9 | if (n > 0) { 10 | res[pi] = n; 11 | pi += 2; 12 | } else { 13 | res[ni] = n; 14 | ni += 2; 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Rearrange Array Elements by Sign.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] rearrangeArray(int[] nums) { 3 | int pi = 0; 4 | int ni = 1; 5 | int[] res = new int[nums.length]; 6 | Arrays.fill(res, 0); 7 | 8 | for (int n : nums) { 9 | if (n > 0) { 10 | res[pi] = n; 11 | pi += 2; 12 | } else { 13 | res[ni] = n; 14 | ni += 2; 15 | } 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Rearrange Array Elements by Sign.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | var rearrangeArray = function(nums) { 6 | let pi = 0; 7 | let ni = 1; 8 | let res = new Array(nums.length).fill(0); 9 | 10 | for (let n of nums) { 11 | if (n > 0) { 12 | res[pi] = n; 13 | pi += 2; 14 | } else { 15 | res[ni] = n; 16 | ni += 2; 17 | } 18 | } 19 | 20 | return res; 21 | }; 22 | -------------------------------------------------------------------------------- /Redistribute_Characters_to_Make_All_Strings_Equal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool makeEqual(vector& words) { 4 | unordered_map chars; 5 | 6 | for (const string& word : words) { 7 | for (char c : word) { 8 | chars[c] = 1 + chars[c]; 9 | } 10 | } 11 | 12 | int divider = words.size(); 13 | 14 | for (const auto& entry : chars) { 15 | if (entry.second % divider != 0) { 16 | return false; 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | }; -------------------------------------------------------------------------------- /Redistribute_Characters_to_Make_All_Strings_Equal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} words 3 | * @return {boolean} 4 | */ 5 | var makeEqual = function(words) { 6 | const chars = {}; 7 | 8 | for (const word of words) { 9 | for (let i = 0; i < word.length; i++) { 10 | chars[word[i]] = 1 + (chars[word[i]] || 0); 11 | } 12 | } 13 | 14 | const divider = words.length; 15 | 16 | for (const freq of Object.values(chars)) { 17 | if (freq % divider !== 0) { 18 | return false; 19 | } 20 | } 21 | 22 | return true; 23 | }; -------------------------------------------------------------------------------- /Redistribute_Characters_to_Make_All_Strings_Equal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeEqual(self, words: List[str]) -> bool: 3 | chars = {} 4 | 5 | for word in words: 6 | for i in range(len(word)): 7 | chars[word[i]] = 1 + chars.get(word[i], 0) 8 | 9 | divider = len(words) 10 | 11 | for freq in chars.values(): 12 | if freq % divider != 0: 13 | return False 14 | 15 | return True -------------------------------------------------------------------------------- /Remove_Colored_Pieces_if_Both_Neighbors_are_the_Same_Color.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def winnerOfGame(self, colors: str) -> bool: 3 | if len(colors) <= 2: 4 | return False 5 | 6 | alice_turn = 0 7 | bob_turn = 0 8 | 9 | for i in range(1, len(colors) - 1): 10 | if colors[i - 1] == colors[i] == colors[i + 1]: 11 | if colors[i] == "A": 12 | alice_turn += 1 13 | else: 14 | bob_turn += 1 15 | 16 | return alice_turn > bob_turn 17 | -------------------------------------------------------------------------------- /Remove_Nth_Node_From_End_of_List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | ListNode* res = new ListNode(0, head); 5 | ListNode* dummy = res; 6 | 7 | for (int i = 0; i < n; i++) { 8 | head = head->next; 9 | } 10 | 11 | while (head != nullptr) { 12 | head = head->next; 13 | dummy = dummy->next; 14 | } 15 | 16 | dummy->next = dummy->next->next; 17 | 18 | return res->next; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Remove_Nth_Node_From_End_of_List.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode removeNthFromEnd(ListNode head, int n) { 3 | ListNode res = new ListNode(0, head); 4 | ListNode dummy = res; 5 | 6 | for (int i = 0; i < n; i++) { 7 | head = head.next; 8 | } 9 | 10 | while (head != null) { 11 | head = head.next; 12 | dummy = dummy.next; 13 | } 14 | 15 | dummy.next = dummy.next.next; 16 | 17 | return res.next; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Remove_Nth_Node_From_End_of_List.js: -------------------------------------------------------------------------------- 1 | var removeNthFromEnd = function(head, n) { 2 | let res = new ListNode(0, head); 3 | let dummy = res; 4 | 5 | for (let i = 0; i < n; i++) { 6 | head = head.next; 7 | } 8 | 9 | while (head) { 10 | head = head.next; 11 | dummy = dummy.next; 12 | } 13 | 14 | dummy.next = dummy.next.next; 15 | 16 | return res.next; 17 | }; 18 | -------------------------------------------------------------------------------- /Remove_Nth_Node_From_End_of_List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 3 | res = ListNode(0, head) 4 | dummy = res 5 | 6 | for _ in range(n): 7 | head = head.next 8 | 9 | while head: 10 | head = head.next 11 | dummy = dummy.next 12 | 13 | dummy.next = dummy.next.next 14 | 15 | return res.next 16 | -------------------------------------------------------------------------------- /Reverse_Words_in_a_String_III.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var reverseWords = function(s) { 6 | // Split the input string into words and reverse each word 7 | const words = s.split(' '); 8 | const reversedWords = words.map(word => word.split('').reverse().join('')); 9 | 10 | // Join the reversed words to form the final result 11 | return reversedWords.join(' '); 12 | }; 13 | -------------------------------------------------------------------------------- /Reverse_Words_in_a_String_III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | # Split the input string into words and reverse each word 4 | words = s.split() 5 | reversed_words = [word[::-1] for word in words] 6 | 7 | # Join the reversed words to form the final result 8 | return ' '.join(reversed_words) 9 | -------------------------------------------------------------------------------- /Same_Tree.js: -------------------------------------------------------------------------------- 1 | // Solution 1 2 | var isSameTree = function(p, q) { 3 | if (!p && !q) { 4 | return true; 5 | } 6 | 7 | if (p && q && p.val === q.val) { 8 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 9 | } 10 | 11 | return false; 12 | }; 13 | 14 | // Solution 2 15 | var isSameTree = function(p, q) { 16 | if (!p || !q) { 17 | return p === q; 18 | } 19 | 20 | return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 21 | }; 22 | -------------------------------------------------------------------------------- /Sequential_Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sequentialDigits(int low, int high) { 4 | string s = "123456789"; 5 | vector res; 6 | 7 | for (int i = 0; i < s.size(); i++) { 8 | for (int j = i + 1; j < s.size(); j++) { 9 | int num = stoi(s.substr(i, j - i + 1)); 10 | 11 | if (num > high) break; 12 | if (low <= num) res.push_back(num); 13 | } 14 | } 15 | 16 | sort(res.begin(), res.end()); 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Sequential_Digits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List sequentialDigits(int low, int high) { 3 | String s = "123456789"; 4 | List res = new ArrayList<>(); 5 | 6 | for (int i = 0; i < s.length(); i++) { 7 | for (int j = i + 1; j < s.length(); j++) { 8 | int num = Integer.parseInt(s.substring(i, j + 1)); 9 | 10 | if (num > high) break; 11 | if (low <= num) res.add(num); 12 | } 13 | } 14 | 15 | res.sort(null); 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Sequential_Digits.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} low 3 | * @param {number} high 4 | * @return {number[]} 5 | */ 6 | var sequentialDigits = function(low, high) { 7 | let s = "123456789"; 8 | let res = []; 9 | 10 | for (let i = 0; i < s.length; i++) { 11 | for (let j = i + 1; j < s.length; j++) { 12 | let num = parseInt(s.substring(i, j + 1)); 13 | 14 | if (num > high) break; 15 | if (low <= num) res.push(num); 16 | } 17 | } 18 | 19 | return res.sort((a, b) => a - b); 20 | }; 21 | -------------------------------------------------------------------------------- /Sequential_Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sequentialDigits(self, low: int, high: int) -> List[int]: 3 | s = "123456789" 4 | res = [] 5 | 6 | for i in range(len(s)): 7 | for j in range(i + 1, len(s)): 8 | num = int(s[i:j+1]) 9 | 10 | if num > high: break 11 | if low <= num: 12 | res.append(num) 13 | 14 | return sorted(res) 15 | -------------------------------------------------------------------------------- /Set_Mismatch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | var findErrorNums = function(nums) { 6 | const actualSum = nums.reduce((sum, num) => sum + num, 0); 7 | const uniqueSum = [...new Set(nums)].reduce((sum, num) => sum + num, 0); 8 | const duplicate = actualSum - uniqueSum; 9 | 10 | const n = nums.length; 11 | const expectedSum = (n * (1 + n)) / 2; 12 | 13 | const missing = expectedSum + duplicate - actualSum; 14 | 15 | return [duplicate, missing]; 16 | }; 17 | -------------------------------------------------------------------------------- /Set_Mismatch.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findErrorNums(self, nums: List[int]) -> List[int]: 3 | 4 | actual_sum = sum(nums) 5 | duplicate = actual_sum - sum(set(nums)) 6 | 7 | n = len(nums) 8 | expected_sum = n * (1 + n) // 2 9 | 10 | missing = expected_sum + duplicate - actual_sum 11 | 12 | return [duplicate, missing] 13 | -------------------------------------------------------------------------------- /Sort_Array_By_Parity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParity(vector& nums) { 4 | int left = 0; 5 | 6 | for (int i = 0; i < nums.size(); i++) { 7 | if (nums[i] % 2 == 0) { 8 | std::swap(nums[left], nums[i]); 9 | left++; 10 | } 11 | } 12 | 13 | return nums; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Sort_Array_By_Parity.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sortArrayByParity(int[] nums) { 3 | int left = 0; 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | if (nums[i] % 2 == 0) { 7 | int temp = nums[left]; 8 | nums[left] = nums[i]; 9 | nums[i] = temp; 10 | left++; 11 | } 12 | } 13 | 14 | return nums; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Sort_Array_By_Parity.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number[]} 4 | */ 5 | var sortArrayByParity = function(nums) { 6 | let left = 0; 7 | 8 | for (let i = 0; i < nums.length; i++) { 9 | if (nums[i] % 2 === 0) { 10 | [nums[left], nums[i]] = [nums[i], nums[left]]; 11 | left++; 12 | } 13 | } 14 | 15 | return nums; 16 | }; 17 | -------------------------------------------------------------------------------- /Sort_Array_By_Parity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, nums: List[int]) -> List[int]: 3 | left = 0 4 | 5 | for i in range(len(nums)): 6 | if nums[i] % 2 == 0: 7 | nums[left], nums[i] = nums[i], nums[left] 8 | left += 1 9 | 10 | return nums 11 | -------------------------------------------------------------------------------- /Split_the_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossibleToSplit(vector& nums) { 4 | unordered_map count; 5 | 6 | for (int n : nums) { 7 | count[n]++; 8 | } 9 | 10 | for (auto& pair : count) { 11 | if (pair.second > 2) { 12 | return false; 13 | } 14 | } 15 | 16 | return true; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Split_the_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPossibleToSplit(int[] nums) { 3 | HashMap count = new HashMap<>(); 4 | 5 | for (int n : nums) { 6 | count.put(n, count.getOrDefault(n, 0) + 1); 7 | } 8 | 9 | for (int val : count.values()) { 10 | if (val > 2) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Split_the_Array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var isPossibleToSplit = function(nums) { 6 | let count = new Map(); 7 | 8 | for (let n of nums) { 9 | count.set(n, (count.get(n) || 0) + 1); 10 | } 11 | 12 | for (let val of count.values()) { 13 | if (val > 2) { 14 | return false; 15 | } 16 | } 17 | 18 | return true; 19 | }; 20 | -------------------------------------------------------------------------------- /Split_the_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPossibleToSplit(self, nums: List[int]) -> bool: 3 | count = {} 4 | 5 | for n in nums: 6 | count[n] = 1 + count.get(n, 0) 7 | 8 | for val in count.values(): 9 | if val > 2: 10 | return False 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /Squares_of_a_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& nums) { 4 | vector res(nums.size(), 0); 5 | int left = 0; 6 | int right = nums.size() - 1; 7 | 8 | for (int i = nums.size() - 1; i >= 0; i--) { 9 | if (abs(nums[left]) > abs(nums[right])) { 10 | res[i] = nums[left] * nums[left]; 11 | left++; 12 | } else { 13 | res[i] = nums[right] * nums[right]; 14 | right--; 15 | } 16 | } 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Squares_of_a_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sortedSquares(int[] nums) { 3 | int[] res = new int[nums.length]; 4 | int left = 0; 5 | int right = nums.length - 1; 6 | 7 | for (int i = nums.length - 1; i >= 0; i--) { 8 | if (Math.abs(nums[left]) > Math.abs(nums[right])) { 9 | res[i] = nums[left] * nums[left]; 10 | left++; 11 | } else { 12 | res[i] = nums[right] * nums[right]; 13 | right--; 14 | } 15 | } 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Squares_of_a_Sorted_Array.js: -------------------------------------------------------------------------------- 1 | var sortedSquares = function(nums) { 2 | let res = new Array(nums.length).fill(0); 3 | let left = 0; 4 | let right = nums.length - 1; 5 | 6 | for (let i = nums.length - 1; i >= 0; i--) { 7 | if (Math.abs(nums[left]) > Math.abs(nums[right])) { 8 | res[i] = nums[left] ** 2; 9 | left++; 10 | } else { 11 | res[i] = nums[right] ** 2; 12 | right--; 13 | } 14 | } 15 | return res; 16 | }; 17 | -------------------------------------------------------------------------------- /Squares_of_a_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, nums: List[int]) -> List[int]: 3 | res = [0] * len(nums) 4 | left = 0 5 | right = len(nums) - 1 6 | 7 | for i in range(len(nums) - 1, -1, -1): 8 | if abs(nums[left]) > abs(nums[right]): 9 | res[i] = nums[left] ** 2 10 | left += 1 11 | else: 12 | res[i] = nums[right] ** 2 13 | right -= 1 14 | 15 | return res 16 | -------------------------------------------------------------------------------- /Sum_of_Subarray_Minimums.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumSubarrayMins(self, arr: List[int]) -> int: 3 | stack = [] # keep index for the latest smaller values 4 | res = [0] * len(arr) 5 | 6 | for i in range(len(arr)): 7 | while stack and arr[stack[-1]] > arr[i]: 8 | stack.pop() 9 | 10 | j = stack[-1] if stack else -1 11 | res[i] = res[j] + (i - j) * arr[i] 12 | 13 | stack.append(i) 14 | 15 | return sum(res) % (10**9+7) 16 | 17 | -------------------------------------------------------------------------------- /Tallest_Billboard.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def tallestBillboard(self, rods: List[int]) -> int: 3 | dp = {0:0} 4 | 5 | for rod in rods: 6 | for diff, highest in list(dp.items()): 7 | left_diff = diff + rod 8 | dp[left_diff] = max(dp.get(left_diff, 0), highest + rod) 9 | 10 | right_rod = highest - diff + rod 11 | right_diff = abs(highest - right_rod) 12 | dp[right_diff] = max(dp.get(right_diff, 0), max(highest, right_rod)) 13 | 14 | return dp[0] 15 | -------------------------------------------------------------------------------- /The_K_Weakest_Rows_in_a_Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: 3 | min_heap = [] 4 | 5 | for i, row in enumerate(mat): 6 | soldiers_count = 0 7 | 8 | for j in range(len(row)): 9 | if row[j] == 1: 10 | soldiers_count += 1 11 | else: 12 | break 13 | 14 | heapq.heappush(min_heap, (soldiers_count, i)) 15 | 16 | weakest_rows = [heapq.heappop(min_heap)[1] for _ in range(k)] 17 | 18 | return weakest_rows 19 | -------------------------------------------------------------------------------- /Unique_Number_of_Occurrences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool uniqueOccurrences(vector& arr) { 4 | unordered_mapcounts; 5 | 6 | for(auto x: arr){ 7 | counts[x]++; 8 | } 9 | 10 | unordered_sets; 11 | for(auto x: counts){ 12 | s.insert(x.second); 13 | } 14 | 15 | return counts.size()==s.size(); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Unique_Number_of_Occurrences.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean uniqueOccurrences(int[] arr) { 3 | Map counts = new HashMap<>(); 4 | 5 | for (int n : arr) { 6 | counts.put(n, 1 + counts.getOrDefault(n, 0)); 7 | } 8 | 9 | return counts.size() == new HashSet<>(counts.values()).size(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Unique_Number_of_Occurrences.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {boolean} 4 | */ 5 | var uniqueOccurrences = function(arr) { 6 | const counts = new Map(); 7 | 8 | for (const n of arr) { 9 | counts.set(n, 1 + (counts.get(n) || 0)); 10 | } 11 | 12 | return counts.size === new Set(counts.values()).size; 13 | }; 14 | -------------------------------------------------------------------------------- /Unique_Number_of_Occurrences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniqueOccurrences(self, arr: List[int]) -> bool: 3 | counts = {} 4 | 5 | for n in arr: 6 | counts[n] = 1 + counts.get(n, 0) 7 | 8 | return len(counts) == len(set(counts.values())) 9 | -------------------------------------------------------------------------------- /add_digits_1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | if (num < 10) { 5 | return num; 6 | } 7 | 8 | int res = 0; 9 | while (num >= 10) { 10 | res = 0; 11 | while (num != 0) { 12 | res += num % 10; 13 | num /= 10; 14 | } 15 | num = res; 16 | } 17 | 18 | return num; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /add_digits_1.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int addDigits(int num) { 3 | if (num < 10) { 4 | return num; 5 | } 6 | 7 | int res = 0; 8 | while (num >= 10) { 9 | res = 0; 10 | while (num != 0) { 11 | res += num % 10; 12 | num /= 10; 13 | } 14 | num = res; 15 | } 16 | 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /add_digits_1.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @return {number} 4 | */ 5 | var addDigits = function(num) { 6 | if (num < 10) { 7 | return num; 8 | } 9 | 10 | let res = 0; 11 | while (num >= 10) { 12 | res = 0 13 | while (num !== 0) { 14 | res += num % 10; 15 | num = Math.floor(num / 10); 16 | } 17 | num = res; 18 | } 19 | 20 | return res; 21 | }; 22 | -------------------------------------------------------------------------------- /add_digits_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | if num < 10: 4 | return num 5 | 6 | while num >= 10: 7 | res = 0 8 | while num != 0: 9 | res += num % 10 10 | num //= 10 11 | num = res 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /add_digits_2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | if (num == 0) { 5 | return 0; 6 | } 7 | if (num % 9 == 0) { 8 | return 9; 9 | } 10 | return num % 9; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /add_digits_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int addDigits(int num) { 3 | if (num == 0) { 4 | return 0; 5 | } 6 | if (num % 9 == 0) { 7 | return 9; 8 | } 9 | return num % 9; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /add_digits_2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @return {number} 4 | */ 5 | var addDigits = function(num) { 6 | if (num === 0) { 7 | return 0; 8 | } 9 | if (num % 9 === 0) { 10 | return 9; 11 | } 12 | return num % 9; 13 | }; 14 | -------------------------------------------------------------------------------- /add_digits_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | if num == 0: 4 | return 0 5 | if num % 9 == 0: 6 | return 9 7 | return num % 9 8 | -------------------------------------------------------------------------------- /asteroid_collision.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def asteroidCollision(self, asteroids: List[int]) -> List[int]: 3 | 4 | res = [] 5 | 6 | for a in asteroids: 7 | 8 | while res and a < 0 < res[-1]: 9 | if -a > res[-1]: 10 | res.pop() 11 | continue 12 | elif -a == res[-1]: 13 | res.pop() 14 | break 15 | else: 16 | res.append(a) 17 | 18 | return res 19 | -------------------------------------------------------------------------------- /average_salary_excluding_the_minimum_and_maximum_salary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double average(vector& salary) { 4 | int min_s = salary[0], max_s = salary[0]; 5 | double total = 0; 6 | int count = 0; 7 | 8 | for (int s : salary) { 9 | if (s < min_s) { 10 | min_s = s; 11 | } else if (s > max_s) { 12 | max_s = s; 13 | } 14 | total += s; 15 | count++; 16 | } 17 | 18 | return (total - min_s - max_s) / (count - 2.0); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /average_salary_excluding_the_minimum_and_maximum_salary.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double average(int[] salary) { 3 | int min_s = salary[0]; 4 | int max_s = salary[0]; 5 | int total = 0; 6 | int count = 0; 7 | 8 | for (int s : salary) { 9 | if (s < min_s) { 10 | min_s = s; 11 | } else if (s > max_s) { 12 | max_s = s; 13 | } 14 | total += s; 15 | count++; 16 | } 17 | 18 | return (double)(total - min_s - max_s) / (double)(count - 2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /average_salary_excluding_the_minimum_and_maximum_salary.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} salary 3 | * @return {number} 4 | */ 5 | var average = function(salary) { 6 | let min_s = salary[0]; 7 | let max_s = salary[0]; 8 | let total = 0; 9 | let count = 0; 10 | 11 | for (let s of salary) { 12 | if (s < min_s) { 13 | min_s = s; 14 | } else if (s > max_s) { 15 | max_s = s; 16 | } 17 | total += s; 18 | count += 1; 19 | } 20 | 21 | return (total - min_s - max_s) / (count - 2); 22 | }; 23 | -------------------------------------------------------------------------------- /average_salary_excluding_the_minimum_and_maximum_salary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def average(self, salary: List[int]) -> float: 3 | min_s = max_s = salary[0] 4 | total = count = 0 5 | 6 | for s in salary: 7 | if s < min_s: 8 | min_s = s 9 | elif s > max_s: 10 | max_s = s 11 | total += s 12 | count += 1 13 | 14 | return (total - min_s - max_s) / (count - 2) 15 | -------------------------------------------------------------------------------- /binary_search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | left = 0 4 | right = len(nums) - 1 5 | 6 | while left <= right: 7 | mid = (left + right) // 2 8 | 9 | if nums[mid] == target: 10 | return mid 11 | elif nums[mid] > target: 12 | right = mid - 1 13 | else: 14 | left = mid + 1 15 | 16 | return -1 17 | -------------------------------------------------------------------------------- /boats_to_save_people.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRescueBoats(vector& people, int limit) { 4 | int left = 0; 5 | int right = people.size() - 1; 6 | int boat = 0; 7 | std::sort(people.begin(), people.end()); 8 | 9 | while (left <= right) { 10 | boat += 1; 11 | 12 | if (people[left] + people[right] <= limit) { 13 | left += 1; 14 | } 15 | right -= 1; 16 | } 17 | 18 | return boat; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /boats_to_save_people.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numRescueBoats(int[] people, int limit) { 3 | int left = 0; 4 | int right = people.length - 1; 5 | int boat = 0; 6 | Arrays.sort(people); 7 | 8 | while (left <= right) { 9 | boat += 1; 10 | 11 | if (people[left] + people[right] <= limit) { 12 | left += 1; 13 | } 14 | right -= 1; 15 | } 16 | 17 | return boat; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /boats_to_save_people.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} people 3 | * @param {number} limit 4 | * @return {number} 5 | */ 6 | var numRescueBoats = function(people, limit) { 7 | let left = 0; 8 | let right = people.length - 1; 9 | let boat = 0; 10 | people.sort((a, b) => a - b); 11 | 12 | while (left <= right) { 13 | boat += 1; 14 | 15 | if (people[left] + people[right] <= limit) { 16 | left += 1; 17 | } 18 | right -= 1; 19 | } 20 | 21 | return boat; 22 | }; 23 | -------------------------------------------------------------------------------- /boats_to_save_people.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people: List[int], limit: int) -> int: 3 | left = 0 4 | right = len(people) - 1 5 | boat = 0 6 | people.sort() 7 | 8 | while left <= right: 9 | boat += 1 10 | 11 | if people[left] + people[right] <= limit: 12 | left += 1 13 | right -= 1 14 | 15 | return boat 16 | -------------------------------------------------------------------------------- /can_make_arithmetic_progression_from_sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canMakeArithmeticProgression(self, arr: List[int]) -> bool: 3 | minimum = min(arr) 4 | maximum = max(arr) 5 | n = len(arr) 6 | 7 | diff = (maximum - minimum) // (n - 1) 8 | nums = set(arr) 9 | 10 | if diff == 0: 11 | return len(nums) == 1 12 | 13 | for i in range(minimum, maximum + 1, diff): 14 | if i not in nums: 15 | return False 16 | 17 | return True 18 | -------------------------------------------------------------------------------- /can_place_flowers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: 3 | 4 | for i in range(len(flowerbed)): 5 | left = i == 0 or flowerbed[i-1] == 0 6 | right = i == len(flowerbed) - 1 or flowerbed[i+1] == 0 7 | 8 | if left and right and flowerbed[i] == 0: 9 | flowerbed[i] = 1 10 | n -= 1 11 | 12 | return n <= 0 13 | -------------------------------------------------------------------------------- /car_fleet.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: 3 | cars = [[p, s] for p, s in zip(position, speed)] 4 | stack = [] 5 | 6 | for p, s in sorted(cars)[::-1]: 7 | time_taken = (target - p) / s 8 | if not stack or time_taken > stack[-1]: 9 | stack.append(time_taken) 10 | 11 | return len(stack) 12 | -------------------------------------------------------------------------------- /check_if_it_Is_a_straight_line.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkStraightLine(int[][] coordinates) { 3 | int x0 = coordinates[0][0]; 4 | int y0 = coordinates[0][1]; 5 | int x1 = coordinates[1][0]; 6 | int y1 = coordinates[1][1]; 7 | 8 | for (int i = 2; i < coordinates.length; i++) { 9 | int x = coordinates[i][0]; 10 | int y = coordinates[i][1]; 11 | 12 | if ((y1 - y0) * (x - x0) != (y - y0) * (x1 - x0)) { 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /check_if_it_Is_a_straight_line.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} coordinates 3 | * @return {boolean} 4 | */ 5 | var checkStraightLine = function(coordinates) { 6 | const [x0, y0] = coordinates[0]; 7 | const [x1, y1] = coordinates[1]; 8 | 9 | for (let i = 2; i < coordinates.length; i++) { 10 | const [x, y] = coordinates[i]; 11 | 12 | if ((y1 - y0) * (x - x0) !== (y - y0) * (x1 - x0)) { 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | }; 19 | -------------------------------------------------------------------------------- /check_if_it_Is_a_straight_line.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkStraightLine(self, coordinates: List[List[int]]) -> bool: 3 | x0, y0 = coordinates[0] 4 | x1, y1 = coordinates[1] 5 | 6 | for i in range(2, len(coordinates)): 7 | x, y = coordinates[i] 8 | 9 | if (y1 - y0) * (x - x0) != (y - y0) * (x1 - x0): 10 | return False 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /climbing_stairs_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | # space O(n) 4 | dp = [0] * (n + 1) # [0,0,0,0,0] 5 | dp[0] = 1 6 | dp[1] = 1 7 | 8 | for i in range(2, n+1): 9 | dp[i] = dp[i-1] + dp[i-2] 10 | return dp[-1] 11 | -------------------------------------------------------------------------------- /climbing_stairs_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | # space O(1) 4 | if n <= 3: return n 5 | 6 | prev1 = 3 # previous 1 step back 7 | prev2 = 2 # previous 2 steps back 8 | cur = 0 9 | 10 | for i in range(3, n): 11 | cur = prev1 + prev2 12 | # update possible range to reach next stair one by one 13 | prev2 = prev1 14 | prev1 = cur 15 | return cur 16 | -------------------------------------------------------------------------------- /coin_change_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int change(int amount, vector& coins) { 4 | vector dp(amount + 1, 0); 5 | dp[0] = 1; 6 | 7 | for (int c : coins) { 8 | for (int a = c; a <= amount; a++) { 9 | dp[a] += dp[a - c]; 10 | } 11 | } 12 | 13 | return dp[amount]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /coin_change_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int change(int amount, int[] coins) { 3 | int[] dp = new int[amount + 1]; 4 | dp[0] = 1; 5 | 6 | for (int c : coins) { 7 | for (int a = c; a <= amount; a++) { 8 | dp[a] += dp[a - c]; 9 | } 10 | } 11 | 12 | return dp[amount]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /coin_change_II.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} amount 3 | * @param {number[]} coins 4 | * @return {number} 5 | */ 6 | var change = function(amount, coins) { 7 | const dp = new Array(amount + 1).fill(0); 8 | dp[0] = 1; 9 | 10 | for (const c of coins) { 11 | for (let a = c; a <= amount; a++) { 12 | dp[a] += dp[a - c]; 13 | } 14 | } 15 | 16 | return dp[amount]; 17 | }; 18 | -------------------------------------------------------------------------------- /coin_change_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def change(self, amount: int, coins: List[int]) -> int: 3 | 4 | dp = [0] * (amount + 1) # [0,0,0,0,0] 5 | dp[0] = 1 6 | 7 | for c in coins: 8 | for a in range(c, amount + 1): 9 | dp[a] += dp[a-c] 10 | 11 | return dp[amount] 12 | -------------------------------------------------------------------------------- /combination_sum_IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int combinationSum4(vector& nums, int target) { 4 | vectordp(target + 1, 0); 5 | dp[0] = 1; 6 | 7 | for(int i = 1; i <= target; i++){ 8 | for(auto value : nums){ 9 | if(i - value >= 0 && dp[i] <= INT_MAX) 10 | dp[i] += (long long int)dp[i - value]; 11 | } 12 | } 13 | 14 | return dp[target]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /combination_sum_IV.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int combinationSum4(int[] nums, int target) { 3 | int[] dp = new int[target + 1]; 4 | dp[0] = 1; 5 | 6 | for (int i = 1; i <= target; i++) { 7 | for (int n : nums) { 8 | if (n <= i) { 9 | dp[i] += dp[i - n]; 10 | } 11 | } 12 | } 13 | 14 | return dp[target]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /combination_sum_IV.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | var combinationSum4 = function(nums, target) { 7 | const dp = new Array(target + 1).fill(0); 8 | dp[0] = 1; 9 | 10 | for (let i = 1; i <= target; i++) { 11 | for (const n of nums) { 12 | if (n <= i) { 13 | dp[i] += dp[i - n]; 14 | } 15 | } 16 | } 17 | 18 | return dp[target]; 19 | }; 20 | -------------------------------------------------------------------------------- /combination_sum_IV.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum4(self, nums: List[int], target: int) -> int: 3 | dp = [0] * (target + 1) 4 | dp[0] = 1 5 | 6 | for i in range(1, target + 1): 7 | for n in nums: 8 | if n <= i: 9 | dp[i] += dp[i-n] 10 | 11 | return dp[-1] 12 | -------------------------------------------------------------------------------- /contains_duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | num_set = set() 4 | 5 | for n in nums: 6 | if n in num_set: 7 | return True 8 | num_set.add(n) 9 | 10 | return False 11 | -------------------------------------------------------------------------------- /count_ways_to_build_good_strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: 3 | dp = [1] + [0] * high 4 | mod = 10 ** 9 + 7 5 | 6 | for i in range(1, high + 1): 7 | if i - zero >= 0: 8 | dp[i] += dp[i-zero] 9 | 10 | if i - one >= 0: 11 | dp[i] += dp[i-one] 12 | 13 | dp[i] %= mod 14 | 15 | return sum(dp[low:high+1]) % mod 16 | -------------------------------------------------------------------------------- /counting_bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int n) { 4 | std::vector dp(n + 1, 0); 5 | int sub = 1; 6 | 7 | for (int i = 1; i <= n; i++) { 8 | if (sub * 2 == i) { 9 | sub = i; 10 | } 11 | 12 | dp[i] = dp[i - sub] + 1; 13 | } 14 | 15 | return dp; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /counting_bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] countBits(int n) { 3 | int[] dp = new int[n + 1]; 4 | int sub = 1; 5 | 6 | for (int i = 1; i <= n; i++) { 7 | if (sub * 2 == i) { 8 | sub = i; 9 | } 10 | 11 | dp[i] = dp[i - sub] + 1; 12 | } 13 | 14 | return dp; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /counting_bits.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number[]} 4 | */ 5 | var countBits = function(n) { 6 | var dp = new Array(n + 1).fill(0); 7 | var sub = 1; 8 | 9 | for (var i = 1; i <= n; i++) { 10 | if (sub * 2 === i) { 11 | sub = i; 12 | } 13 | 14 | dp[i] = dp[i - sub] + 1; 15 | } 16 | 17 | return dp; 18 | }; 19 | -------------------------------------------------------------------------------- /counting_bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, n: int) -> List[int]: 3 | dp = [0] * (n + 1) 4 | sub = 1 5 | 6 | for i in range(1, n + 1): 7 | if sub * 2 == i: 8 | sub = i 9 | 10 | dp[i] = dp[i - sub] + 1 11 | 12 | return dp 13 | -------------------------------------------------------------------------------- /daily_temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | st = [] 4 | ans = [0] * len(temperatures) 5 | 6 | for i in range(len(temperatures)): 7 | while st and temperatures[i] > temperatures[st[-1]]: 8 | idx = st.pop() 9 | ans[idx] = i - idx 10 | st.append(i) 11 | 12 | return ans 13 | -------------------------------------------------------------------------------- /design_parking_system.py: -------------------------------------------------------------------------------- 1 | class ParkingSystem: 2 | 3 | def __init__(self, big: int, medium: int, small: int): 4 | self.slots = {1: big, 2: medium, 3: small} 5 | 6 | def addCar(self, carType: int) -> bool: 7 | if not self.slots[carType]: 8 | return False 9 | 10 | self.slots[carType] -= 1 11 | return True 12 | 13 | 14 | 15 | # Your ParkingSystem object will be instantiated and called as such: 16 | # obj = ParkingSystem(big, medium, small) 17 | # param_1 = obj.addCar(carType) 18 | -------------------------------------------------------------------------------- /find_all_numbers_disappeared_in_an_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | 4 | for i in range(len(nums)): 5 | idx = abs(nums[i]) - 1 6 | 7 | if nums[idx] > 0: 8 | nums[idx] *= -1 9 | 10 | res = [] 11 | 12 | for i in range(len(nums)): 13 | if nums[i] > 0: 14 | res.append(i+1) 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /find_minimum_in_rotated_sorted_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | 4 | left = 0 5 | right = len(nums) - 1 6 | 7 | while left < right: 8 | mid = (left + right) // 2 9 | 10 | if nums[mid] <= nums[right]: 11 | right = mid 12 | else: 13 | left = mid + 1 14 | 15 | return nums[left] 16 | -------------------------------------------------------------------------------- /find_pivot_index.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotIndex(self, nums: List[int]) -> int: 3 | total = sum(nums) 4 | left = 0 # left sum 5 | 6 | for i in range(len(nums)): 7 | right = total - left - nums[i] # right sum 8 | 9 | if right == left: 10 | return i 11 | 12 | left += nums[i] 13 | 14 | return -1 15 | -------------------------------------------------------------------------------- /find_the_difference_of_two_arrays.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number[]} nums2 4 | * @return {number[][]} 5 | */ 6 | var findDifference = function(nums1, nums2) { 7 | const set1 = new Set(nums1); 8 | const set2 = new Set(nums2); 9 | 10 | const diff1 = new Set([...set1].filter(x => !set2.has(x))); 11 | const diff2 = new Set([...set2].filter(x => !set1.has(x))); 12 | 13 | return [Array.from(diff1), Array.from(diff2)]; 14 | }; 15 | -------------------------------------------------------------------------------- /find_the_difference_of_two_arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: 3 | set1 = set(nums1) 4 | set2 = set(nums2) 5 | 6 | diff1 = set1 - set2 7 | diff2 = set2 - set1 8 | 9 | return [diff1, diff2] 10 | -------------------------------------------------------------------------------- /fireworks/fireworks.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | fireworks 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /fireworks/style.css: -------------------------------------------------------------------------------- 1 | body{ 2 | padding: 0; 3 | margin: 0; 4 | overflow: hidden; 5 | } 6 | 7 | canvas{ 8 | padding: 0; 9 | margin: 0; 10 | } 11 | -------------------------------------------------------------------------------- /first_Missing_positive1.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var firstMissingPositive = function(nums) { 6 | nums.sort((a, b) => a - b); 7 | 8 | let missing = 1; 9 | for (let i = 0; i < nums.length; i++) { 10 | if (nums[i] > 0 && nums[i] === missing) { 11 | missing++; 12 | } else if (nums[i] > missing) { 13 | return missing; 14 | } 15 | } 16 | 17 | return missing; 18 | }; 19 | -------------------------------------------------------------------------------- /first_missing_positive1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | nums = [n for n in nums if n > 0] 4 | nums.sort() 5 | 6 | target = 1 7 | for n in nums: 8 | if n == target: 9 | target += 1 10 | elif n > target: 11 | return target 12 | 13 | return target 14 | -------------------------------------------------------------------------------- /first_missing_positive1_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | 4 | nums.sort() 5 | 6 | target = 1 7 | for n in nums: 8 | if n > 0 and n == target: 9 | target += 1 10 | elif n > target: 11 | return target 12 | 13 | return target 14 | 15 | -------------------------------------------------------------------------------- /first_missing_positive2.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | firstMissingPositive(nums) { 3 | nums = nums.filter(n => n > 0); 4 | 5 | for (let n of nums) { 6 | const idx = Math.abs(n) - 1; 7 | if (idx < nums.length && nums[idx] > 0) { 8 | nums[idx] *= -1; 9 | } 10 | } 11 | 12 | for (let i = 0; i < nums.length; i++) { 13 | if (nums[i] > 0) { 14 | return i + 1; 15 | } 16 | } 17 | 18 | return nums.length + 1; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /first_missing_positive2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | 4 | nums = [n for n in nums if n > 0] 5 | 6 | for n in nums: 7 | idx = abs(n) - 1 8 | if idx < len(nums) and nums[idx] > 0: 9 | nums[idx] *= -1 10 | 11 | for i in range(len(nums)): 12 | if nums[i] > 0: 13 | return i + 1 14 | 15 | return len(nums) + 1 16 | 17 | -------------------------------------------------------------------------------- /frequency_of_the_most_frequent_element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxFrequency(self, nums: List[int], k: int) -> int: 3 | 4 | nums.sort() 5 | left = right = res = total = 0 6 | 7 | while right < len(nums): 8 | total += nums[right] 9 | 10 | while nums[right] * (right - left + 1) > total + k: 11 | total -= nums[left] 12 | left += 1 13 | 14 | res = max(res, right - left + 1) 15 | right += 1 16 | 17 | return res 18 | -------------------------------------------------------------------------------- /generate_parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n: int) -> List[str]: 3 | res = [] 4 | 5 | def dfs(openP, closeP, s): 6 | if openP == closeP and openP + closeP == n * 2: 7 | res.append(s) 8 | return 9 | 10 | if openP < n: 11 | dfs(openP + 1, closeP, s + "(") 12 | 13 | if closeP < openP: 14 | dfs(openP, closeP + 1, s + ")") 15 | 16 | dfs(0, 0, "") 17 | return res 18 | -------------------------------------------------------------------------------- /group_anagrams_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | ans = collections.defaultdict(list) 4 | 5 | for s in strs: 6 | key = "".join(sorted(s)) 7 | ans[key].append(s) 8 | 9 | return ans.values() 10 | -------------------------------------------------------------------------------- /group_anagrams_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | ans = collections.defaultdict(list) 4 | 5 | for s in strs: 6 | count = [0] * 26 7 | 8 | # a = 100 9 | # b = 101 -> 101 - 100 = 1 10 | # c = 102 -> 102 - 100 = 2 11 | for c in s: 12 | count[ord(c) - ord("a")] += 1 13 | ans[tuple(count)].append(s) 14 | 15 | return ans.values() 16 | -------------------------------------------------------------------------------- /happy_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | visit = set() 4 | 5 | while n not in visit: 6 | visit.add(n) 7 | n = self.get_next_number(n) 8 | 9 | if n == 1: 10 | return True 11 | 12 | return False 13 | 14 | def get_next_number(self, n): 15 | output = 0 16 | 17 | while n: 18 | digit = n % 10 19 | output += digit ** 2 20 | n = n // 10 21 | 22 | return output 23 | -------------------------------------------------------------------------------- /house_robber_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | 4 | def get_max(nums): 5 | nei_max = rob_max = 0 6 | 7 | for n in nums: 8 | temp = max(rob_max, n + nei_max) 9 | nei_max = rob_max 10 | rob_max = temp 11 | 12 | return rob_max 13 | 14 | return max(get_max(nums[1:]), get_max(nums[:-1]), nums[0]) 15 | -------------------------------------------------------------------------------- /is_subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | int sIdx = 0; 5 | int tIdx = 0; 6 | 7 | while (sIdx < s.length() && tIdx < t.length()) { 8 | if (s[sIdx] == t[tIdx]) { 9 | sIdx++; 10 | } 11 | tIdx++; 12 | } 13 | 14 | return sIdx == s.length(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /is_subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSubsequence(String s, String t) { 3 | int sIdx = 0; 4 | int tIdx = 0; 5 | 6 | while (sIdx < s.length() && tIdx < t.length()) { 7 | if (s.charAt(sIdx) == t.charAt(tIdx)) { 8 | sIdx++; 9 | } 10 | tIdx++; 11 | } 12 | 13 | return sIdx == s.length(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /is_subsequence.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} t 4 | * @return {boolean} 5 | */ 6 | var isSubsequence = function(s, t) { 7 | let sIdx = 0; 8 | let tIdx = 0; 9 | 10 | while (sIdx < s.length && tIdx < t.length) { 11 | if (s[sIdx] === t[tIdx]) { 12 | sIdx++; 13 | } 14 | tIdx++; 15 | } 16 | 17 | return sIdx === s.length; 18 | }; 19 | -------------------------------------------------------------------------------- /is_subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | s_idx = t_idx = 0 4 | 5 | while s_idx < len(s) and t_idx < len(t): 6 | if s[s_idx] == t[t_idx]: 7 | s_idx += 1 8 | t_idx += 1 9 | 10 | return s_idx == len(s) 11 | -------------------------------------------------------------------------------- /js/132_pattern.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {boolean} 4 | */ 5 | var find132pattern = function(nums) { 6 | const st = []; 7 | let cur_min = nums[0]; 8 | 9 | for (let i = 1; i < nums.length; i++) { 10 | const n = nums[i]; 11 | while (st.length && n >= st[st.length - 1][0]) { 12 | st.pop(); 13 | } 14 | 15 | if (st.length && n > st[st.length - 1][1]) { 16 | return true; 17 | } 18 | 19 | st.push([n, cur_min]); 20 | cur_min = Math.min(cur_min, n); 21 | } 22 | 23 | return false; 24 | }; 25 | -------------------------------------------------------------------------------- /jump_game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | goal = len(nums) - 1 4 | 5 | for i in range(len(nums) - 2, -1, -1): 6 | if i + nums[i] >= goal: 7 | goal = i 8 | 9 | return True if goal == 0 else False 10 | -------------------------------------------------------------------------------- /jump_game_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | jumps = 0 4 | near = far = 0 5 | 6 | while far < len(nums) - 1: 7 | farthest = 0 8 | # check farthest position from current range 9 | for i in range(near, far + 1): 10 | farthest = max(farthest, i + nums[i]) 11 | 12 | near = far + 1 13 | far = farthest 14 | jumps += 1 15 | 16 | return jumps 17 | -------------------------------------------------------------------------------- /jump_game_III_bfs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canReach(self, arr: List[int], start: int) -> bool: 3 | 4 | queue = [start] 5 | visited = set() 6 | 7 | while queue: 8 | i = queue.pop() 9 | jump = arr[i] 10 | 11 | if jump == 0: return True 12 | 13 | if i not in visited: 14 | visited.add(i) 15 | if i + jump < len(arr): 16 | queue.append(i + jump) 17 | if i - jump >= 0: 18 | queue.append(i - jump) 19 | 20 | return False 21 | -------------------------------------------------------------------------------- /jump_game_III_dfs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canReach(self, arr: List[int], start: int) -> bool: 3 | 4 | visited = set() 5 | 6 | def dfs(i): 7 | if i >= len(arr) or i < 0 or i in visited: 8 | return False 9 | if arr[i] == 0: 10 | return True 11 | 12 | visited.add(i) 13 | 14 | left = i - arr[i] 15 | right = i + arr[i] 16 | 17 | if dfs(left) or dfs(right): 18 | return True 19 | 20 | return False 21 | 22 | return dfs(start) 23 | -------------------------------------------------------------------------------- /last_stone_weight.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lastStoneWeight(self, stones: List[int]) -> int: 3 | if len(stones) == 1: 4 | return stones[0] 5 | 6 | stones = [-s for s in stones] 7 | heapq.heapify(stones) 8 | 9 | while len(stones) > 1: 10 | s1 = -(heapq.heappop(stones)) 11 | s2 = -(heapq.heappop(stones)) 12 | 13 | if s1 != s2: 14 | heapq.heappush(stones, -(s1-s2)) 15 | 16 | return -(stones[0]) if stones else 0 17 | -------------------------------------------------------------------------------- /length_of_last_word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | # return len(s.split()[-1]) 4 | 5 | 6 | idx, length = len(s) - 1, 0 7 | 8 | while s[idx] == " ": 9 | idx -= 1 10 | 11 | while idx >= 0 and s[idx] != " ": 12 | length += 1 13 | idx -= 1 14 | 15 | return length 16 | -------------------------------------------------------------------------------- /linked_list_cycle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasCycle(self, head: Optional[ListNode]) -> bool: 3 | fast = head 4 | slow = head 5 | 6 | while fast and fast.next: 7 | fast = fast.next.next 8 | slow = slow.next 9 | 10 | if fast == slow: 11 | return True 12 | 13 | return False 14 | -------------------------------------------------------------------------------- /longest_common_prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | pref = strs[0] 4 | plen = len(pref) 5 | 6 | for s in strs[1:]: 7 | while pref != s[0:plen]: 8 | plen -= 1 9 | if plen == 0: 10 | return "" 11 | 12 | pref = pref[0:plen] 13 | 14 | return pref 15 | -------------------------------------------------------------------------------- /longest_consecutive_sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | num_set = set(nums) 4 | longest_length = 0 5 | 6 | for n in nums: 7 | if n - 1 not in num_set: 8 | length = 1 9 | while n + length in num_set: 10 | length += 1 11 | 12 | longest_length = max(longest_length, length) 13 | 14 | return longest_length -------------------------------------------------------------------------------- /longest_increasing_subsequence_dynamic_programming.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | dp = [1] * len(nums) 4 | 5 | for i in range(len(nums)): 6 | for j in range(i): 7 | if nums[i] > nums[j] and dp[i] < dp[j] + 1: 8 | dp[i] = dp[j] + 1 9 | 10 | return max(dp) 11 | -------------------------------------------------------------------------------- /longest_palindromic_subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindromeSubseq(self, s: str) -> int: 3 | n = len(s) 4 | dp = [1 for _ in range(n)] 5 | 6 | for i in range(n - 2, -1, -1): 7 | prev = 0 8 | for j in range(i + 1, n): 9 | temp = dp[j] 10 | 11 | if s[i] == s[j]: 12 | dp[j] = prev + 2 13 | else: 14 | dp[j] = max(dp[j], dp[j-1]) 15 | 16 | prev = temp 17 | 18 | return dp[n-1] 19 | -------------------------------------------------------------------------------- /longest_repeating_character_replacement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def characterReplacement(self, s: str, k: int) -> int: 3 | left = res = 0 4 | freq = 0 5 | chars = {} 6 | 7 | for right in range(len(s)): 8 | chars[s[right]] = 1 + chars.get(s[right], 0) 9 | freq = max(freq, chars[s[right]]) 10 | 11 | while right - left + 1 - freq > k: 12 | chars[s[left]] -= 1 13 | left += 1 14 | 15 | res = max(res, right - left + 1) 16 | 17 | return res 18 | -------------------------------------------------------------------------------- /longest_substring_without_repeating_characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | left = max_length = 0 4 | char_set = set() 5 | 6 | for right in range(len(s)): 7 | while s[right] in char_set: 8 | char_set.remove(s[left]) 9 | left += 1 10 | 11 | char_set.add(s[right]) 12 | max_length = max(max_length, right - left + 1) 13 | 14 | return max_length 15 | -------------------------------------------------------------------------------- /longest_valid_parentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var longestValidParentheses = function(s) { 6 | const stack = [-1]; 7 | let max_len = 0; 8 | 9 | for (let i = 0; i < s.length; i++) { 10 | if (s[i] === "(") { 11 | stack.push(i); 12 | } else { 13 | stack.pop(); 14 | if (stack.length === 0) { 15 | stack.push(i); 16 | } else { 17 | max_len = Math.max(max_len, i - stack[stack.length - 1]); 18 | } 19 | } 20 | } 21 | 22 | return max_len; 23 | }; 24 | -------------------------------------------------------------------------------- /longest_valid_parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestValidParentheses(self, s: str) -> int: 3 | stack = [-1] 4 | max_len = 0 5 | 6 | for i in range(len(s)): 7 | if s[i] == "(": 8 | stack.append(i) 9 | else: 10 | stack.pop() 11 | if len(stack) == 0: 12 | stack.append(i) 13 | else: 14 | max_len = max(max_len, i - stack[-1]) 15 | 16 | return max_len 17 | -------------------------------------------------------------------------------- /lowest_common_ancestor_of_a_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 3 | 4 | while root: 5 | if p.val > root.val and q.val > root.val: 6 | root = root.right 7 | elif p.val < root.val and q.val < root.val: 8 | root = root.left 9 | else: 10 | return root 11 | -------------------------------------------------------------------------------- /majority_element_hashmap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | hash = {} 4 | res = majority = 0 5 | 6 | for n in nums: 7 | hash[n] = 1 + hash.get(n, 0) 8 | if hash[n] > majority: 9 | res = n 10 | majority = hash[n] 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /majority_element_solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | res = majority = 0 4 | 5 | for n in nums: 6 | if majority == 0: 7 | res = n 8 | 9 | majority += 1 if n == res else -1 10 | 11 | return res 12 | -------------------------------------------------------------------------------- /matrix_diagonal_sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int diagonalSum(vector>& mat) { 4 | int last_row = mat.size() - 1; 5 | int total = 0; 6 | 7 | for (int i = 0; i < mat.size(); i++) { 8 | total += mat[i][i]; 9 | total += mat[last_row - i][i]; 10 | 11 | if (i == last_row - i) { 12 | total -= mat[i][i]; 13 | } 14 | } 15 | 16 | return total; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /matrix_diagonal_sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int diagonalSum(int[][] mat) { 3 | int last_row = mat.length - 1; 4 | int total = 0; 5 | 6 | for (int i = 0; i < mat.length; i++) { 7 | total += mat[i][i]; 8 | total += mat[last_row - i][i]; 9 | 10 | if (i == last_row - i) { 11 | total -= mat[i][i]; 12 | } 13 | } 14 | 15 | return total; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /matrix_diagonal_sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} mat 3 | * @return {number} 4 | */ 5 | var diagonalSum = function(mat) { 6 | let last_row = mat.length - 1; 7 | let total = 0; 8 | 9 | for (let i = 0; i < mat.length; i++) { 10 | total += mat[i][i]; 11 | total += mat[last_row - i][i]; 12 | 13 | if (i == last_row - i) { 14 | total -= mat[i][i]; 15 | } 16 | } 17 | 18 | return total; 19 | }; 20 | -------------------------------------------------------------------------------- /matrix_diagonal_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diagonalSum(self, mat: List[List[int]]) -> int: 3 | last_row = len(mat) - 1 4 | total = 0 5 | 6 | for i in range(len(mat)): 7 | total += mat[i][i] 8 | total += mat[last_row - i][i] 9 | 10 | if i == last_row - i: 11 | total -= mat[i][i] 12 | 13 | return total 14 | -------------------------------------------------------------------------------- /maximum_depth_of_binary_tree_dfs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, root: Optional[TreeNode]) -> int: 3 | if not root: 4 | return 0 5 | 6 | return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 7 | -------------------------------------------------------------------------------- /maximum_number_of_vowels_in_a_substring_of_given_length.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxVowels(self, s: str, k: int) -> int: 3 | vowels = set("aeiou") 4 | max_vowels = cur_vowels = 0 5 | 6 | for right in range(len(s)): 7 | if s[right] in vowels: 8 | cur_vowels += 1 9 | 10 | if right >= k and s[right - k] in vowels: 11 | cur_vowels -= 1 12 | 13 | max_vowels = max(max_vowels, cur_vowels) 14 | 15 | if max_vowels == k: 16 | return k 17 | 18 | return max_vowels 19 | -------------------------------------------------------------------------------- /maximum_product_subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | res = max(nums) 4 | cur_max = cur_min = 1 5 | 6 | for n in nums: 7 | temp = cur_max * n 8 | cur_max = max(temp, cur_min * n, n) 9 | cur_min = min(temp, cur_min * n, n) 10 | 11 | res = max(res, cur_max) 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /maximum_subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | res = nums[0] 4 | total = 0 5 | 6 | for n in nums: 7 | if total < 0: 8 | total = 0 9 | 10 | total += n 11 | res = max(res, total) 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /maximum_subsequence_score.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int: 3 | pairs = sorted(zip(nums1, nums2), key=lambda p: -p[1]) 4 | 5 | total = res = 0 6 | heap = [] 7 | 8 | for pair in pairs: 9 | nums1, nums2 = pair 10 | heapq.heappush(heap, nums1) 11 | total += nums1 12 | 13 | if len(heap) > k: 14 | total -= heapq.heappop(heap) 15 | 16 | if len(heap) == k: 17 | res = max(res, total * nums2) 18 | 19 | return res 20 | -------------------------------------------------------------------------------- /merge_intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | if not intervals: 4 | return [] 5 | 6 | merged = [] 7 | intervals.sort(key=lambda x: x[0]) 8 | 9 | prev = intervals[0] 10 | 11 | for interval in intervals[1:]: 12 | if interval[0] <= prev[1]: 13 | prev[1] = max(prev[1], interval[1]) 14 | else: 15 | merged.append(prev) 16 | prev = interval 17 | 18 | merged.append(prev) 19 | 20 | return merged 21 | -------------------------------------------------------------------------------- /merge_strings_alternately.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string mergeAlternately(string word1, string word2) { 4 | std::string merged; 5 | int maxLength = std::max(word1.length(), word2.length()); 6 | 7 | for (int i = 0; i < maxLength; i++) { 8 | if (i < word1.length()) { 9 | merged += word1[i]; 10 | } 11 | 12 | if (i < word2.length()) { 13 | merged += word2[i]; 14 | } 15 | } 16 | 17 | return merged; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /merge_strings_alternately.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String mergeAlternately(String word1, String word2) { 3 | StringBuilder merged = new StringBuilder(); 4 | int maxLength = Math.max(word1.length(), word2.length()); 5 | 6 | for (int i = 0; i < maxLength; i++) { 7 | if (i < word1.length()) { 8 | merged.append(word1.charAt(i)); 9 | } 10 | 11 | if (i < word2.length()) { 12 | merged.append(word2.charAt(i)); 13 | } 14 | } 15 | 16 | return merged.toString(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /merge_strings_alternately.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} word1 3 | * @param {string} word2 4 | * @return {string} 5 | */ 6 | var mergeAlternately = function(word1, word2) { 7 | let merged = []; 8 | 9 | for (let i = 0; i < Math.max(word1.length, word2.length); i++) { 10 | if (i < word1.length) { 11 | merged.push(word1[i]); 12 | } 13 | 14 | if (i < word2.length) { 15 | merged.push(word2[i]); 16 | } 17 | } 18 | 19 | return merged.join(""); 20 | }; 21 | -------------------------------------------------------------------------------- /merge_strings_alternately.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeAlternately(self, word1: str, word2: str) -> str: 3 | merged = [] 4 | 5 | for a, b in zip(word1, word2): 6 | merged.append(a + b) 7 | 8 | merged.append(word1[len(word2):]) 9 | merged.append(word2[len(word1):]) 10 | 11 | return "".join(merged) 12 | -------------------------------------------------------------------------------- /min_cost_climbing_stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostClimbingStairs(self, cost: List[int]) -> int: 3 | cost.append(0) # top [10,15,20,0] 4 | 5 | for i in range(len(cost) - 4, -1, -1): 6 | cost[i] += min(cost[i+1], cost[i+2]) 7 | 8 | return min(cost[0], cost[1]) 9 | -------------------------------------------------------------------------------- /minimum_insertion_steps_to_make_a_string_palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minInsertions(self, s: str) -> int: 3 | n = len(s) 4 | dp = [0] * n 5 | 6 | for i in range(n - 2, -1, -1): 7 | prev = 0 8 | 9 | for j in range(i + 1, n): 10 | temp = dp[j] 11 | 12 | if s[i] == s[j]: 13 | dp[j] = prev 14 | else: 15 | dp[j] = min(dp[j], dp[j-1]) + 1 16 | 17 | prev = temp 18 | 19 | return dp[n-1] 20 | -------------------------------------------------------------------------------- /minimum_number_of_vertices_to_reach_all_nodes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSmallestSetOfVertices(int n, vector>& edges) { 4 | std::vector indegree(n, 0); 5 | std::vector res; 6 | 7 | for (const std::vector& edge : edges) { 8 | indegree[edge[1]]++; 9 | } 10 | 11 | for (int i = 0; i < n; i++) { 12 | if (indegree[i] == 0) { 13 | res.push_back(i); 14 | } 15 | } 16 | 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /minimum_number_of_vertices_to_reach_all_nodes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findSmallestSetOfVertices(int n, List> edges) { 3 | int[] indegree = new int[n]; 4 | List res = new ArrayList<>(); 5 | 6 | for (List edge : edges) { 7 | indegree[edge.get(1)]++; 8 | } 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (indegree[i] == 0) { 12 | res.add(i); 13 | } 14 | } 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /minimum_number_of_vertices_to_reach_all_nodes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @param {number[][]} edges 4 | * @return {number[]} 5 | */ 6 | var findSmallestSetOfVertices = function(n, edges) { 7 | let indegree = new Array(n).fill(0); 8 | let res = []; 9 | 10 | for (let edge of edges) { 11 | indegree[edge[1]]++; 12 | } 13 | 14 | for (let i = 0; i < n; i++) { 15 | if (indegree[i] === 0) { 16 | res.push(i); 17 | } 18 | } 19 | 20 | return res; 21 | }; 22 | -------------------------------------------------------------------------------- /minimum_number_of_vertices_to_reach_all_nodes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: 3 | indegree = [0] * n 4 | res = [] 5 | 6 | for edge in edges: 7 | indegree[edge[1]] += 1 8 | 9 | for i in range(n): 10 | if indegree[i] == 0: 11 | res.append(i) 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /missing_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int res = nums.size(); 5 | 6 | for (int i = 0; i < nums.size(); i++) { 7 | res += i - nums[i]; 8 | } 9 | 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /missing_number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { 3 | int res = nums.length; 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | res += i - nums[i]; 7 | } 8 | 9 | return res; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /missing_number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var missingNumber = function(nums) { 6 | let res = nums.length; 7 | 8 | for (let i = 0; i < nums.length; i++) { 9 | res += i - nums[i]; 10 | } 11 | 12 | return res; 13 | }; 14 | -------------------------------------------------------------------------------- /missing_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | res = len(nums) 4 | 5 | for i in range(len(nums)): 6 | res += i - nums[i] 7 | 8 | return res 9 | -------------------------------------------------------------------------------- /move_zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | left = 0 7 | 8 | for i in range(len(nums)): 9 | if nums[i] != 0: 10 | nums[i], nums[left] = nums[left], nums[i] 11 | left += 1 12 | 13 | return nums 14 | -------------------------------------------------------------------------------- /next_permutation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextPermutation(self, nums: List[int]) -> None: 3 | i = len(nums) - 1 4 | while i > 0 and nums[i-1] >= nums[i]: 5 | i -= 1 6 | 7 | if i == 0: 8 | nums.reverse() 9 | return 10 | 11 | j = len(nums) - 1 12 | while j >= i and nums[j] <= nums[i-1]: 13 | j -= 1 14 | 15 | nums[i-1], nums[j] = nums[j], nums[i-1] 16 | 17 | nums[i:] = reversed(nums[i:]) 18 | -------------------------------------------------------------------------------- /non-overlapping_intervals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int eraseOverlapIntervals(int[][] intervals) { 3 | int res = 0; 4 | 5 | Arrays.sort(intervals, (a, b) -> a[1] - b[1]); 6 | int prev_end = intervals[0][1]; 7 | 8 | for (int i = 1; i < intervals.length; i++) { 9 | if (prev_end > intervals[i][0]) { 10 | res++; 11 | } else { 12 | prev_end = intervals[i][1]; 13 | } 14 | } 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /non-overlapping_intervals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} intervals 3 | * @return {number} 4 | */ 5 | var eraseOverlapIntervals = function(intervals) { 6 | let res = 0; 7 | intervals.sort((a, b) => a[1] - b[1]); 8 | let prev_end = intervals[0][1]; 9 | 10 | for (let i = 1; i < intervals.length; i++) { 11 | if (prev_end > intervals[i][0]) { 12 | res++; 13 | } else { 14 | prev_end = intervals[i][1]; 15 | } 16 | } 17 | 18 | return res; 19 | }; 20 | -------------------------------------------------------------------------------- /non-overlapping_intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | res = 0 4 | 5 | intervals.sort(key=lambda x: x[1]) 6 | prev_end = intervals[0][1] 7 | 8 | for i in range(1, len(intervals)): 9 | if prev_end > intervals[i][0]: 10 | res += 1 11 | else: 12 | prev_end = intervals[i][1] 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /non_decreasing_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkPossibility(self, nums: List[int]) -> bool: 3 | changed = False 4 | 5 | for i in range(1, len(nums)): 6 | if nums[i] < nums[i-1]: 7 | if changed: 8 | return False 9 | 10 | changed = True 11 | 12 | if i >= 2 and nums[i] < nums[i-2]: 13 | nums[i] = nums[i-1] 14 | 15 | return True 16 | -------------------------------------------------------------------------------- /number_of_provinces.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCircleNum(self, isConnected: List[List[int]]) -> int: 3 | visited = set() 4 | provinces = 0 5 | 6 | def dfs(city): 7 | visited.add(city) 8 | for cur, connected in enumerate(isConnected[city]): 9 | if connected and cur not in visited: 10 | dfs(cur) 11 | 12 | for i in range(len(isConnected)): 13 | if i not in visited: 14 | dfs(i) 15 | provinces += 1 16 | 17 | return provinces 18 | -------------------------------------------------------------------------------- /number_of_subsequences_that_satisfy_the_given_sum_condition.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSubseq(self, nums: List[int], target: int) -> int: 3 | nums.sort() 4 | left, right = 0, len(nums) - 1 5 | ans = 0 6 | mod = 10 ** 9 + 7 7 | 8 | while left <= right: 9 | if nums[left] + nums[right] > target: 10 | right -= 1 11 | else: 12 | # pow(x, y, z) = x^y % z 13 | ans += pow(2, right - left, mod) 14 | left += 1 15 | 16 | return ans % mod 17 | -------------------------------------------------------------------------------- /number_of_zero-filled_subarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long zeroFilledSubarray(vector& nums) { 4 | long res = 0; 5 | int count = 0; 6 | 7 | for (int i = 0; i < nums.size(); i++) { 8 | if (nums[i] == 0) { 9 | count += 1; 10 | } else { 11 | count = 0; 12 | } 13 | res += count; 14 | } 15 | 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /number_of_zero-filled_subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long zeroFilledSubarray(int[] nums) { 3 | long res = 0; 4 | int count = 0; 5 | 6 | for (int i = 0; i < nums.length; i++) { 7 | if (nums[i] == 0) { 8 | count += 1; 9 | } else { 10 | count = 0; 11 | } 12 | 13 | res += count; 14 | } 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /number_of_zero-filled_subarrays.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var zeroFilledSubarray = function(nums) { 6 | let res = 0; 7 | let count = 0; 8 | 9 | for (let i = 0; i < nums.length; i++) { 10 | if (nums[i] == 0) { 11 | count += 1; 12 | } else { 13 | count = 0; 14 | } 15 | res += count; 16 | } 17 | 18 | return res; 19 | }; 20 | -------------------------------------------------------------------------------- /number_of_zero-filled_subarrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def zeroFilledSubarray(self, nums: List[int]) -> int: 3 | res = 0 4 | count = 0 5 | 6 | for i in range(len(nums)): 7 | if nums[i] == 0: 8 | count += 1 9 | else: 10 | count = 0 11 | 12 | res += count 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /palindrome_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | 4 | if x < 0: 5 | return False 6 | 7 | reverse = 0 8 | xcopy = x 9 | 10 | while x > 0: 11 | reverse = (reverse * 10) + (x % 10) 12 | x //= 10 13 | 14 | return reverse == xcopy 15 | -------------------------------------------------------------------------------- /pascals_triangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} numRows 3 | * @return {number[][]} 4 | */ 5 | var generate = function(numRows) { 6 | const res = [[1]]; 7 | 8 | for (let i = 0; i < numRows - 1; i++) { 9 | const dummyRow = [0, ...res[res.length - 1], 0]; 10 | const row = []; 11 | 12 | for (let j = 0; j < dummyRow.length - 1; j++) { 13 | row.push(dummyRow[j] + dummyRow[j + 1]); 14 | } 15 | 16 | res.push(row); 17 | } 18 | 19 | return res; 20 | }; 21 | -------------------------------------------------------------------------------- /pascals_triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | res = [[1]] 4 | 5 | for _ in range(numRows - 1): 6 | dummy_row = [0] + res[-1] + [0] 7 | row = [] 8 | 9 | for i in range(len(res[-1]) + 1): 10 | row.append(dummy_row[i] + dummy_row[i+1]) 11 | res.append(row) 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /path_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: 3 | if not root: 4 | return False 5 | 6 | if not root.left and not root.right: 7 | return targetSum - root.val == 0 8 | 9 | targetSum -= root.val 10 | 11 | return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum) 12 | -------------------------------------------------------------------------------- /plus_one.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | 4 | for i in range(len(digits) - 1, -1, -1): 5 | 6 | if digits[i] + 1 != 10: 7 | digits[i] += 1 8 | return digits 9 | 10 | digits[i] = 0 11 | 12 | if i == 0: 13 | return [1] + digits 14 | -------------------------------------------------------------------------------- /product_of_array_except_self.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | 4 | # [1,1,1,1] 5 | output = [1] * len(nums) 6 | 7 | left = 1 8 | for i in range(len(nums)): 9 | output[i] *= left 10 | left *= nums[i] 11 | 12 | right = 1 13 | for i in range(len(nums) - 1, -1, -1): 14 | output[i] *= right 15 | right *= nums[i] 16 | 17 | return output 18 | -------------------------------------------------------------------------------- /python/132_pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def find132pattern(self, nums: List[int]) -> bool: 3 | 4 | st = [] 5 | cur_min = nums[0] 6 | 7 | for n in nums[1:]: 8 | while st and n >= st[-1][0]: 9 | st.pop() 10 | 11 | if st and n > st[-1][1]: 12 | return True 13 | 14 | st.append([n, cur_min]) 15 | cur_min = min(cur_min, n) 16 | 17 | return False 18 | -------------------------------------------------------------------------------- /quicksort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(seq): 2 | length = len(seq) 3 | 4 | if length <= 1: 5 | return seq 6 | else: 7 | pivot = seq.pop() 8 | 9 | more = [] 10 | less = [] 11 | 12 | for val in seq: 13 | if val > pivot: 14 | more.append(val) 15 | else: 16 | less.append(val) 17 | 18 | return quick_sort(less) + [pivot] + quick_sort(more) 19 | 20 | print(quick_sort([1,3,4,23,7,4,6,8,9,5,4,3])) 21 | print(quick_sort([1,3,4,23,2,3,6,4,2,5,4,6,3,9])) 22 | -------------------------------------------------------------------------------- /remove_K_digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeKdigits(self, num: str, k: int) -> str: 3 | st = [] 4 | 5 | for c in num: 6 | while k > 0 and st and st[-1] > c: 7 | st.pop() 8 | k -= 1 9 | st.append(c) 10 | 11 | # 12 345 k=3 12 | st = st[:len(st) - k] 13 | res = "".join(st) 14 | 15 | return str(int(res)) if res else "0" 16 | -------------------------------------------------------------------------------- /remove_all_adjacent_duplicates_in_string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, s: str) -> str: 3 | 4 | st = [] 5 | 6 | for c in s: 7 | if st and st[-1] == c: 8 | st.pop() 9 | else: 10 | st.append(c) 11 | 12 | return "".join(st) 13 | -------------------------------------------------------------------------------- /remove_all_adjacent_duplicates_in_string_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, s: str, k: int) -> str: 3 | if len(s) < k: 4 | return s 5 | 6 | st = [] 7 | 8 | for c in s: 9 | if st and c == st[-1][0]: 10 | st[-1][-1] += 1 11 | 12 | if st[-1][-1] == k: 13 | st.pop() 14 | else: 15 | st.append([c, 1]) 16 | 17 | res = "" 18 | for char, count in st: 19 | res += char * count 20 | 21 | return res 22 | -------------------------------------------------------------------------------- /remove_linked_list_elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 8 | ans = ListNode(0, head) 9 | dummy = ans 10 | 11 | while dummy: 12 | while dummy.next and dummy.next.val == val: 13 | dummy.next = dummy.next.next 14 | dummy = dummy.next 15 | 16 | return ans.next 17 | -------------------------------------------------------------------------------- /removing_stars_from_a_string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var removeStars = function(s) { 6 | let st = []; 7 | 8 | for (let c of s) { 9 | if (c === '*') { 10 | st.pop(); 11 | } else { 12 | st.push(c); 13 | } 14 | } 15 | 16 | return st.join(''); 17 | }; 18 | -------------------------------------------------------------------------------- /removing_stars_from_a_string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeStars(self, s: str) -> str: 3 | res = [] 4 | for i in s: 5 | if i == '*': 6 | res.pop() 7 | else: 8 | res.append(i) 9 | 10 | return "".join(res) 11 | -------------------------------------------------------------------------------- /removing_stars_from_a_string_2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeStars(string s) { 4 | int count = 0; 5 | string res = ""; 6 | 7 | for (int i = s.length() - 1; i >= 0; i--) { 8 | if (s[i] == '*') { 9 | count++; 10 | } else if (count > 0) { 11 | count--; 12 | } else { 13 | res += s[i]; 14 | } 15 | } 16 | 17 | reverse(res.begin(), res.end()); 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /removing_stars_from_a_string_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String removeStars(String s) { 3 | int count = 0; 4 | StringBuilder res = new StringBuilder(); 5 | 6 | for (int i = s.length() - 1; i >= 0; i--) { 7 | if (s.charAt(i) == '*') { 8 | count++; 9 | } else if (count > 0) { 10 | count--; 11 | } else { 12 | res.append(s.charAt(i)); 13 | } 14 | } 15 | 16 | return res.reverse().toString(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /removing_stars_from_a_string_2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var removeStars = function(s) { 6 | let count = 0; 7 | let res = ""; 8 | 9 | for (let i = s.length - 1; i >= 0; i--) { 10 | if (s[i] === "*") { 11 | count++; 12 | } else if (count > 0) { 13 | count--; 14 | } else { 15 | res += s[i]; 16 | } 17 | } 18 | 19 | return res.split("").reverse().join(""); 20 | }; 21 | -------------------------------------------------------------------------------- /removing_stars_from_a_string_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeStars(self, s: str) -> str: 3 | count = 0 4 | res = "" 5 | 6 | for i in range(len(s) -1, -1, -1): 7 | if s[i] == "*": 8 | count += 1 9 | elif count > 0: 10 | count -= 1 11 | else: 12 | res += s[i] 13 | 14 | return res[::-1] 15 | -------------------------------------------------------------------------------- /repeated_substring_pattern_1.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean repeatedSubstringPattern(String s) { 3 | int n = s.length(); 4 | for (int i = 1; i <= n / 2; i++) { 5 | if (n % i == 0 && s.substring(0, i).repeat(n / i).equals(s)) { 6 | return true; 7 | } 8 | } 9 | return false; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /repeated_substring_pattern_1.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | var repeatedSubstringPattern = function(s) { 6 | const n = s.length; 7 | 8 | for (let i = 1; i <= Math.floor(n / 2); i++) { 9 | if (n % i === 0 && s.slice(0, i).repeat(n / i) === s) { 10 | return true; 11 | } 12 | } 13 | 14 | return false; 15 | }; 16 | -------------------------------------------------------------------------------- /repeated_substring_pattern_1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | n = len(s) 4 | for i in range(1, n // 2 + 1): 5 | if n % i == 0 and s[:i] * (n // i) == s: 6 | return True 7 | 8 | return False 9 | -------------------------------------------------------------------------------- /repeated_substring_pattern_2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean repeatedSubstringPattern(String s) { 3 | String concatenated = s + s; 4 | return concatenated.substring(1, concatenated.length() - 1).contains(s); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /repeated_substring_pattern_2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | var repeatedSubstringPattern = function(s) { 6 | return (s + s).substring(1, s.length * 2 - 1).includes(s); 7 | }; 8 | -------------------------------------------------------------------------------- /repeated_substring_pattern_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | return s in (s+s)[1:-1] 4 | -------------------------------------------------------------------------------- /rotate_array_solution1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | k = k % len(nums) 4 | if k != 0: 5 | nums[:k], nums[k:] = nums[-k:], nums[:-k] 6 | -------------------------------------------------------------------------------- /rotate_array_solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | k %= len(nums) 4 | 5 | def reverse(left, right): 6 | while left < right: 7 | nums[left], nums[right] = nums[right], nums[left] 8 | left += 1 9 | right -= 1 10 | 11 | reverse(0, len(nums) - 1) 12 | reverse(0, k-1) 13 | reverse(k, len(nums) - 1) 14 | -------------------------------------------------------------------------------- /sign_of_the_product_of_an_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arraySign(vector& nums) { 4 | int sign = 1; 5 | for (int n : nums) { 6 | if (n == 0) { 7 | return 0; 8 | } 9 | if (n < 0) { 10 | sign *= -1; 11 | } 12 | } 13 | return sign; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /sign_of_the_product_of_an_array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int arraySign(int[] nums) { 3 | int sign = 1; 4 | for (int n : nums) { 5 | if (n == 0) { 6 | return 0; 7 | } 8 | if (n < 0) { 9 | sign *= -1; 10 | } 11 | } 12 | return sign; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /sign_of_the_product_of_an_array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var arraySign = function(nums) { 6 | let sign = 1; 7 | for (let n of nums) { 8 | if (n == 0) { 9 | return 0; 10 | } 11 | if (n < 0) { 12 | sign *= -1; 13 | } 14 | } 15 | return sign; 16 | }; 17 | -------------------------------------------------------------------------------- /sign_of_the_product_of_an_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arraySign(self, nums: List[int]) -> int: 3 | sign = 1 4 | for n in nums: 5 | if n == 0: 6 | return 0 7 | if n < 0: 8 | sign *= -1 9 | 10 | return sign 11 | -------------------------------------------------------------------------------- /simplify_path.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} path 3 | * @return {string} 4 | */ 5 | var simplifyPath = function(path) { 6 | const components = path.split("/"); 7 | const st = []; 8 | 9 | for (const comp of components) { 10 | if (comp === "" || comp === ".") { 11 | continue; 12 | } 13 | 14 | if (comp === "..") { 15 | if (st.length) { 16 | st.pop(); 17 | } 18 | } else { 19 | st.push(comp); 20 | } 21 | } 22 | 23 | return "/" + st.join("/"); 24 | }; 25 | -------------------------------------------------------------------------------- /simplify_path.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | components = path.split("/") 4 | st = [] 5 | 6 | for comp in components: 7 | if comp == "" or comp == ".": 8 | continue 9 | 10 | if comp == "..": 11 | if st: 12 | st.pop() 13 | else: 14 | st.append(comp) 15 | 16 | return "/" + "/".join(st) 17 | -------------------------------------------------------------------------------- /sliding_window_maximum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: 3 | 4 | res = [] 5 | left = right = 0 6 | q = deque() 7 | 8 | while right < len(nums): 9 | while q and nums[right] > nums[q[-1]]: 10 | q.pop() 11 | q.append(right) 12 | 13 | if left > q[0]: 14 | q.popleft() 15 | 16 | if right + 1 >= k: 17 | res.append(nums[q[0]]) 18 | left += 1 19 | right += 1 20 | 21 | return res 22 | -------------------------------------------------------------------------------- /spiral_matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | rows, cols = len(matrix), len(matrix[0]) 4 | x, y, dx, dy = 0, 0, 1, 0 5 | res = [] 6 | 7 | for _ in range(rows * cols): 8 | res.append(matrix[y][x]) 9 | matrix[y][x] = "." 10 | 11 | if not 0 <= x + dx < cols or not 0 <= y + dy < rows or matrix[y+dy][x+dx] == ".": 12 | dx, dy = -dy, dx 13 | 14 | x += dx 15 | y += dy 16 | 17 | return res 18 | -------------------------------------------------------------------------------- /spiral_matrix_II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] generateMatrix(int n) { 3 | int x = 0, y = 0, dx = 1, dy = 0; 4 | int[][] res = new int[n][n]; 5 | 6 | for (int i = 0; i < n * n; i++) { 7 | res[y][x] = i + 1; 8 | 9 | if (!(0 <= x + dx && x + dx < n && 0 <= y + dy && y + dy < n && res[y+dy][x+dx] == 0)) { 10 | int temp = dx; 11 | dx = -dy; 12 | dy = temp; 13 | } 14 | 15 | x += dx; 16 | y += dy; 17 | } 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spiral_matrix_II.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {number[][]} 4 | */ 5 | var generateMatrix = function(n) { 6 | let x = 0, y = 0, dx = 1, dy = 0; 7 | let res = Array.from({length: n}, () => Array.from({length: n}, () => 0)); 8 | 9 | for (let i = 0; i < n * n; i++) { 10 | res[y][x] = i + 1; 11 | 12 | if (!(0 <= x + dx && x + dx < n && 0 <= y + dy && y + dy < n && res[y+dy][x+dx] === 0)) { 13 | [dx, dy] = [-dy, dx]; 14 | } 15 | 16 | x += dx; 17 | y += dy; 18 | } 19 | 20 | return res; 21 | }; 22 | -------------------------------------------------------------------------------- /spiral_matrix_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n: int) -> List[List[int]]: 3 | x, y, dx, dy = 0, 0, 1, 0 4 | res = [[0 for _ in range(n)] for _ in range(n)] 5 | 6 | for i in range(n * n): 7 | res[y][x] = i + 1 8 | 9 | if not 0 <= x + dx < n or not 0 <= y + dy < n or res[y+dy][x+dx] != 0: 10 | dx, dy = -dy, dx 11 | 12 | x += dx 13 | y += dy 14 | 15 | return res 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /subsets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | subset = [] 5 | 6 | def create_subset(i): 7 | if i == len(nums): 8 | res.append(subset[:]) 9 | return 10 | 11 | subset.append(nums[i]) 12 | create_subset(i+1) 13 | subset.pop() 14 | create_subset(i+1) 15 | 16 | create_subset(0) 17 | 18 | return res 19 | -------------------------------------------------------------------------------- /target_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTargetSumWays(self, nums: List[int], target: int) -> int: 3 | counter = {0:1} 4 | 5 | for n in nums: 6 | temp = {} 7 | 8 | for total, count in counter.items(): 9 | temp[total + n] = temp.get(total + n, 0) + count 10 | temp[total - n] = temp.get(total - n, 0) + count 11 | counter = temp 12 | 13 | return counter.get(target, 0) 14 | -------------------------------------------------------------------------------- /triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector>& triangle) { 4 | int row = triangle.size(); 5 | vector memo = triangle[row-1]; 6 | 7 | for (int r = row-2; r >= 0; r--) { 8 | for (int c = 0; c <= r; c++) { 9 | memo[c] = min(memo[c], memo[c+1]) + triangle[r][c]; 10 | } 11 | } 12 | 13 | return memo[0]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /triangle.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumTotal(List> triangle) { 3 | int row = triangle.size(); 4 | int[] memo = new int[row]; 5 | 6 | for (int i = 0; i < row; i++) { 7 | memo[i] = triangle.get(row - 1).get(i); 8 | } 9 | 10 | for (int r = row-2; r >= 0; r--) { 11 | for (int c = 0; c <= r; c++) { 12 | memo[c] = Math.min(memo[c], memo[c+1]) + triangle.get(r).get(c); 13 | } 14 | } 15 | 16 | return memo[0]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /triangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} triangle 3 | * @return {number} 4 | */ 5 | var minimumTotal = function(triangle) { 6 | let row = triangle.length; 7 | let memo = [...triangle[row-1]]; 8 | 9 | for (let r = row-2; r >= 0; r--) { 10 | for (let c = 0; c <= r; c++) { 11 | memo[c] = Math.min(memo[c], memo[c+1]) + triangle[r][c]; 12 | } 13 | } 14 | 15 | return memo[0]; 16 | }; 17 | -------------------------------------------------------------------------------- /triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumTotal(self, triangle: List[List[int]]) -> int: 3 | row = len(triangle) 4 | memo = triangle[row-1].copy() 5 | 6 | for r in range(row-2, -1, -1): 7 | for c in range(r+1): 8 | memo[c] = min(memo[c], memo[c+1]) + triangle[r][c] 9 | 10 | return memo[0] 11 | 12 | -------------------------------------------------------------------------------- /two_sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | unordered_map pairIdx; 5 | 6 | for (int i = 0; i < nums.size(); ++i) { 7 | int num = nums[i]; 8 | if (pairIdx.find(target - num) != pairIdx.end()) { 9 | return {i, pairIdx[target - num]}; 10 | } 11 | pairIdx[num] = i; 12 | } 13 | 14 | return {}; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /two_sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | Map pairIdx = new HashMap<>(); 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | int num = nums[i]; 7 | if (pairIdx.containsKey(target - num)) { 8 | return new int[] { i, pairIdx.get(target - num) }; 9 | } 10 | pairIdx.put(num, i); 11 | } 12 | 13 | return new int[] {}; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /two_sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | pair_idx = {} 4 | 5 | for i, num in enumerate(nums): 6 | if target - num in pair_idx: 7 | return [i, pair_idx[target - num]] 8 | pair_idx[num] = i 9 | -------------------------------------------------------------------------------- /uncrossed_lines.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: 3 | m, n = len(nums1), len(nums2) 4 | dp = [0] * (n + 1) 5 | 6 | for i in range(1, m + 1): 7 | prev = 0 8 | 9 | for j in range(1, n + 1): 10 | temp = dp[j] 11 | 12 | if nums1[i-1] == nums2[j-1]: 13 | dp[j] = prev + 1 14 | else: 15 | dp[j] = max(dp[j], dp[j-1]) 16 | 17 | prev = temp 18 | 19 | return dp[n] 20 | -------------------------------------------------------------------------------- /unique_binary_search_trees.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTrees(self, n: int) -> int: 3 | 4 | dp = [1] * (n + 1) # [1,1,1,1,1] 5 | 6 | for nodes in range(2, n+1): # number of nodes 7 | total = 0 8 | # count each case like root is 1, root is 2... 9 | for root in range(1, nodes + 1): 10 | left = root - 1 11 | right = nodes - root 12 | total += dp[left] * dp[right] 13 | 14 | dp[nodes] = total 15 | 16 | return dp[n] 17 | -------------------------------------------------------------------------------- /unique_length-3_palindromic_subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPalindromicSubsequence(self, s: str) -> int: 3 | 4 | res = 0 5 | uniq = set(s) 6 | 7 | for c in uniq: 8 | start = s.find(c) # search a character from the beginning 9 | end = s.rfind(c) # search a character from the last index 10 | 11 | if start < end: 12 | res += len(set(s[start+1:end])) 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /unique_paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | std::vector aboveRow(n, 1); 5 | 6 | for (int row = 1; row < m; row++) { 7 | std::vector currentRow(n, 1); 8 | for (int col = 1; col < n; col++) { 9 | currentRow[col] = currentRow[col - 1] + aboveRow[col]; 10 | } 11 | aboveRow = currentRow; 12 | } 13 | 14 | return aboveRow[n - 1]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /unique_paths.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int uniquePaths(int m, int n) { 3 | int[] aboveRow = new int[n]; 4 | Arrays.fill(aboveRow, 1); 5 | 6 | for (int row = 1; row < m; row++) { 7 | int[] currentRow = new int[n]; 8 | Arrays.fill(currentRow, 1); 9 | for (int col = 1; col < n; col++) { 10 | currentRow[col] = currentRow[col - 1] + aboveRow[col]; 11 | } 12 | aboveRow = currentRow; 13 | } 14 | 15 | return aboveRow[n - 1]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /unique_paths.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} m 3 | * @param {number} n 4 | * @return {number} 5 | */ 6 | var uniquePaths = function(m, n) { 7 | let aboveRow = Array(n).fill(1); 8 | 9 | for (let row = 1; row < m; row++) { 10 | let currentRow = Array(n).fill(1); 11 | for (let col = 1; col < n; col++) { 12 | currentRow[col] = currentRow[col - 1] + aboveRow[col]; 13 | } 14 | aboveRow = currentRow; 15 | } 16 | 17 | return aboveRow[n - 1]; 18 | }; 19 | -------------------------------------------------------------------------------- /unique_paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | 4 | aboveRow = [1] * n 5 | 6 | for _ in range(m - 1): 7 | currentRow = [1] * n 8 | for i in range(1, n): 9 | currentRow[i] = currentRow[i-1] + aboveRow[i] 10 | aboveRow = currentRow 11 | 12 | return aboveRow[-1] 13 | -------------------------------------------------------------------------------- /validate_stack_sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validateStackSequences(vector& pushed, vector& popped) { 4 | std::stack st; 5 | int i = 0; 6 | 7 | for (int n : pushed) { 8 | st.push(n); 9 | 10 | while (!st.empty() && st.top() == popped[i]) { 11 | st.pop(); 12 | i++; 13 | } 14 | } 15 | 16 | return i == popped.size(); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /validate_stack_sequences.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean validateStackSequences(int[] pushed, int[] popped) { 3 | Stack st = new Stack<>(); 4 | int i = 0; 5 | 6 | for (int n : pushed) { 7 | st.push(n); 8 | 9 | while (!st.isEmpty() && st.peek() == popped[i]) { 10 | st.pop(); 11 | i++; 12 | } 13 | } 14 | 15 | return i == popped.length; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /validate_stack_sequences.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} pushed 3 | * @param {number[]} popped 4 | * @return {boolean} 5 | */ 6 | var validateStackSequences = function(pushed, popped) { 7 | const st = []; 8 | let i = 0; 9 | 10 | for (const n of pushed) { 11 | st.push(n); 12 | 13 | while (st.length > 0 && st[st.length - 1] === popped[i]) { 14 | st.pop(); 15 | i++; 16 | } 17 | } 18 | 19 | return i === popped.length; 20 | }; 21 | -------------------------------------------------------------------------------- /validate_stack_sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: 3 | 4 | st = [] 5 | i = 0 6 | 7 | for n in pushed: 8 | st.append(n) 9 | 10 | while st and st[-1] == popped[i]: 11 | st.pop() 12 | i += 1 13 | 14 | return i == len(popped) 15 | -------------------------------------------------------------------------------- /word_break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordBreak(string s, vector& wordDict) { 4 | vector dp(s.size()+1, false); 5 | dp[0] = true; 6 | 7 | for (int i = 1; i <= s.size(); i++) 8 | for (int j = 0; j < i; j++) 9 | if ((dp[j]) && (find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end())) { 10 | dp[i] = true; 11 | break; 12 | } 13 | 14 | return dp.back(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /word_break.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean wordBreak(String s, List wordDict) { 3 | int n = s.length(); 4 | boolean[] dp = new boolean[n + 1]; 5 | dp[0] = true; 6 | 7 | for (int i = 1; i <= n; i++) { 8 | for (String word : wordDict) { 9 | if (i - word.length() >= 0 && dp[i - word.length()] && s.substring(i - word.length(), i).equals(word)) { 10 | dp[i] = true; 11 | break; 12 | } 13 | } 14 | } 15 | 16 | return dp[n]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /word_break.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string[]} wordDict 4 | * @return {boolean} 5 | */ 6 | var wordBreak = function(s, wordDict) { 7 | const n = s.length; 8 | const dp = new Array(n + 1).fill(false); 9 | dp[0] = true; 10 | 11 | for (let i = 1; i <= n; i++) { 12 | for (const word of wordDict) { 13 | if (i - word.length >= 0 && dp[i - word.length] && s.substring(i - word.length, i) === word) { 14 | dp[i] = true; 15 | break; 16 | } 17 | } 18 | } 19 | 20 | return dp[n]; 21 | }; 22 | -------------------------------------------------------------------------------- /word_break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | 4 | dp = [True] + [False] * len(s) 5 | 6 | for i in range(1, len(s) + 1): 7 | for w in wordDict: 8 | if i - len(w) >= 0 and dp[i - len(w)] and s[:i].endswith(w): 9 | dp[i] = True 10 | break 11 | return dp[-1] 12 | --------------------------------------------------------------------------------