├── .gitignore ├── LICENSE ├── Python ├── ant_on_the_boundary.py ├── apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k.py ├── array_partition.py ├── bag_of_tokens.py ├── baseball_game.py ├── best_time_to_buy_and_sell_stock.py ├── binary_subarrays_with_sum.py ├── binary_subarrays_with_sumvv.py ├── binary_tree_inorder_traversal.py ├── build_array_from_permutation.py ├── buy_two_chocolates.py ├── cells_in_a_range_on_an_excel_sheet.py ├── cells_with_odd_values_in_a_matrix.py ├── cheapest_flights_within_k_stops.py ├── check_if_a_string_is_an_acronym_of_words.py ├── check_if_all_characters_have_equal_number_of_occurrences.py ├── check_if_number_has_equal_digit_count_and_digit_value.py ├── check_if_the_sentence_is_pangram.py ├── check_if_two_string_arrays_are_equivalent.py ├── climbing_stairs.py ├── combination_sum.py ├── concatenation_of_array.py ├── contains_duplicate_ii.py ├── contiguous_array.py ├── convert_binary_number_in_a_linked_list_to_integer.py ├── convert_sorted_array_to_binary_search_tree.py ├── count_elements_with_maximum_frequency.py ├── count_equal_and_divisible_pairs_in_an_array.py ├── count_good_triplets.py ├── count_items_matching_a_rule.py ├── count_negative_numbers_in_a_sorted_matrix.py ├── count_number_of_pairs_with_absolute_difference_k.py ├── count_pairs_whose_sum_is_less_than_target.py ├── count_prefixes_of_a_given_string.py ├── count_subarrays_with_fixed_bounds.py ├── count_substrings_starting_and_ending_with_given_character.py ├── count_tested_devices_after_test_operations.py ├── count_the_number_of_consistent_strings.py ├── counting_words_with_a_given_prefix.py ├── create_target_array_in_the_given_order.py ├── decode_the_message.py ├── decode_xored_array.py ├── decompress_run-length_encoded_list.py ├── defanging_an_ip_address.py ├── delete_greatest_value_in_each_row.py ├── design_an_ordered_stream.py ├── destination_city.py ├── di_string_match.py ├── diameter_of_binary_tree.py ├── difference_between_element_sum_and_digit_sum_of_an_array.py ├── distribute_candies.py ├── divide_array_into_equal_pairs.py ├── even_odd_tree.py ├── existence_of_a_substring_in_a_string_and_its_reverse.py ├── final_prices_with_a_special_discount_in_a_shop.py ├── final_value_of_variable_after_performing_operations.py ├── find_all_people_with_secret.py ├── find_bottom_left_tree_value.py ├── find_champion_i.py ├── find_common_elements_between_two_arrays.py ├── find_first_palindromic_string_in_the_array.py ├── find_greatest_common_divisor_of_array.py ├── find_maximum_number_of_string_pairs.py ├── find_missing_and_repeated_values.py ├── find_n_unique_integers_sum_up_to_zero.py ├── find_numbers_with_even_number_of_digits.py ├── find_pivot_index.py ├── find_target_indices_after_sorting_array.py ├── find_the_difference_of_two_arrays.py ├── find_the_distinct_difference_array.py ├── find_the_duplicate_number.py ├── find_the_highest_altitude.py ├── find_the_index_of_the_first_occurrence_in_a_string.py ├── find_the_k-or_of_an_array.py ├── find_the_peaks.py ├── find_the_pivot_integer.py ├── find_the_town_judge.py ├── find_words_containing_character.py ├── first_letter_to_appear_twice.py ├── first_missing_positive.py ├── flipping_an_image.py ├── generate_parentheses.py ├── goal_parser_interpretation.py ├── greatest_common_divisor_traversal.py ├── height_checker.py ├── how_many_numbers_are_smaller_than_the_current_number.py ├── insert_interval.py ├── intersection_of_two_arrays.py ├── is_subsequence.py ├── isomorphic_strings.py ├── jewels_and_stones.py ├── kids_with_the_greatest_number_of_candies.py ├── kth_distinct_string_in_an_array.py ├── largest_local_values_in_a_matrix.py ├── left_and_right_sum_differences.py ├── length_of_last_word.py ├── letter_combinations_of_a_phone_number.py ├── lexicographically_smallest_palindrome.py ├── longest_common_prefix.py ├── longest_common_suffix_queries.py ├── longest_palindromic_substring.py ├── majority_element.py ├── make_array_zero_by_subtracting_equal_amounts.py ├── matrix_diagonal_sum.py ├── maximum_69_number.py ├── maximum_depth_of_binary_tree.py ├── maximum_length_substring_with_two_occurrences.py ├── maximum_number_of_balls_in_a_box.py ├── maximum_number_of_pairs_in_array.py ├── maximum_number_of_words_found_in_sentences.py ├── maximum_number_of_words_you_can_type.py ├── maximum_odd_binary_number.py ├── maximum_product_difference_between_two_pairs.py ├── maximum_product_of_two_elements_in_an_array.py ├── maximum_strong_pair_xor_i.py ├── maximum_sum_with_exactly_k_elements_.py ├── maximum_units_on_a_truck.py ├── merge_in_between_linked_lists.py ├── merge_similar_items.py ├── merge_sorted_array.py ├── merge_two_2d_arrays_by_summing_values.py ├── merge_two_sorted_lists.py ├── middle_of_the_linked_list.py ├── minimize_string_length.py ├── minimum_common_value.py ├── minimum_deletions_to_make_string_k-special.py ├── minimum_length_of_string_after_deleting_similar_ends.py ├── minimum_number_game.py ├── minimum_number_of_moves_to_seat_everyone.py ├── minimum_operations_to_exceed_threshold_value_i.py ├── minimum_operations_to_make_the_array_increasing.py ├── minimum_sum_of_four_digit_number_after_splitting_digits.py ├── minimum_time_visiting_all_points.py ├── modify_the_matrix.py ├── most_common_word.py ├── most_frequent_ids.py ├── move_zeroes.py ├── n-queens.py ├── n-repeated_element_in_size_2n_array.py ├── neither_minimum_nor_maximum.py ├── next_greater_element_i.py ├── number_of_arithmetic_triplets.py ├── number_of_employees_who_met_the_target.py ├── number_of_good_pairs.py ├── number_of_rectangles_that_can_form_the_largest_square.py ├── number_of_senior_citizens.py ├── number_of_students_doing_homework_at_a_given_time.py ├── number_of_students_unable_to_eat_lunch.py ├── number_of_unequal_triplets_in_array.py ├── palindrome_number.py ├── pascals_triangle.py ├── permutations.py ├── plus_one.py ├── points_that_intersect_with_cars.py ├── product_of_array_except_self.py ├── ransom_note.py ├── remove_duplicates_from_sorted_array.py ├── remove_element.py ├── remove_linked_list_elements.py ├── remove_nth_node_from_end_of_list.py ├── remove_palindromic_subsequences.py ├── remove_zero_sum_consecutive_nodes_from_linked_list.py ├── replace_all_digits_with_characters.py ├── reverse_linked_list.py ├── reverse_words_in_a_string_iii.py ├── richest_customer_wealth.py ├── rings_and_rods.py ├── roman_to_integer.py ├── row_with_maximum_ones.py ├── running_sum_of_1d_array.py ├── same_tree.py ├── separate_the_digits_in_an_array.py ├── shuffle_string.py ├── shuffle_the_array.py ├── single_number.py ├── smallest_index_with_equal_value.py ├── sort_array_by_parity.py ├── sort_integers_by_the_number_of_1_bits.py ├── sort_the_people.py ├── sorting_the_sentence.py ├── split_a_string_in_balanced_strings.py ├── split_strings_by_separator.py ├── split_the_array.py ├── squares_of_a_sorted_array.py ├── subarray_product_less_than_k.py ├── subarrays_distinct_element_sum_of_squares_i.py ├── subarrays_with_k_different_integers.py ├── subsets.py ├── sum_of_all_odd_length_subarrays.py ├── sum_of_all_subset_xor_totals.py ├── sum_of_squares_of_special_elements_.py ├── sum_of_unique_elements.py ├── sum_of_values_at_indices_with_k_set_bits.py ├── symmetric_tree.py ├── to_lower_case.py ├── top_k_frequent_elements.py ├── transpose_matrix.py ├── trapping_rain_water.py ├── truncate_sentence.py ├── two_out_of_three.py ├── two_sum.py ├── unique_number_of_occurrences.py ├── valid_anagram.py ├── valid_palindrome.py ├── valid_parentheses.py ├── widest_vertical_area_between_two_points_containing_no_points.py ├── winner_of_the_linked_list_game.py └── word_search.py ├── README.md ├── generate_file.py ├── generate_lists.py ├── img └── repo_icon.png └── search_problem.py /.gitignore: -------------------------------------------------------------------------------- 1 | # General 2 | .DS_Store 3 | .AppleDouble 4 | .LSOverride 5 | 6 | # Icon must end with two \r 7 | Icon 8 | 9 | # Thumbnails 10 | ._* 11 | 12 | # Files that might appear in the root of a volume 13 | .DocumentRevisions-V100 14 | .fseventsd 15 | .Spotlight-V100 16 | .TemporaryItems 17 | .Trashes 18 | .VolumeIcon.icns 19 | .com.apple.timemachine.donotpresent 20 | 21 | # Directories potentially created on remote AFP share 22 | .AppleDB 23 | .AppleDesktop 24 | Network Trash Folder 25 | Temporary Items 26 | .apdisk 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Og'abek 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Python/ant_on_the_boundary.py: -------------------------------------------------------------------------------- 1 | # Ant on the Boundary 2 | 3 | class Solution(object): 4 | def returnToBoundaryCount(self, nums): 5 | position = 0 6 | boundary_count = 0 7 | 8 | for step in nums: 9 | position += step 10 | 11 | if position == 0: 12 | boundary_count += 1 13 | 14 | return boundary_count 15 | 16 | solution = Solution() 17 | print(solution.returnToBoundaryCount([2,3,-5])) -------------------------------------------------------------------------------- /Python/apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k.py: -------------------------------------------------------------------------------- 1 | # Apply Operations to Make Sum of Array Greater Than or Equal to k 2 | 3 | import math 4 | 5 | class Solution: 6 | def minOperations(self, k: int) -> int: 7 | if k == 1: 8 | return 0 9 | 10 | ans = float('inf') 11 | for i in range(1, (k // 2) + 1): 12 | temp = math.ceil(k / i) 13 | m = (i - 1) + (temp - 1) 14 | ans = min(m, ans) 15 | 16 | return ans 17 | 18 | solution = Solution() 19 | print(solution.minOperations(11)) -------------------------------------------------------------------------------- /Python/array_partition.py: -------------------------------------------------------------------------------- 1 | # Array Partition 2 | 3 | class Solution(object): 4 | def arrayPairSum(self, nums): 5 | nums.sort() 6 | count = 0 7 | for i in range(0, len(nums), 2): 8 | count += min(nums[i], nums[i+1]) 9 | return count 10 | 11 | solution = Solution() 12 | print(solution.arrayPairSum([1,4,3,2])) -------------------------------------------------------------------------------- /Python/bag_of_tokens.py: -------------------------------------------------------------------------------- 1 | # Bag of Tokens 2 | 3 | class Solution(object): 4 | def bagOfTokensScore(self, tokens, power): 5 | tokens.sort() 6 | n = len(tokens) 7 | score = 0 8 | max_score = 0 9 | left = 0 10 | right = n - 1 11 | 12 | while left <= right: 13 | if power >= tokens[left]: 14 | power -= tokens[left] 15 | score += 1 16 | left += 1 17 | max_score = max(max_score, score) 18 | elif score > 0: 19 | power += tokens[right] 20 | score -= 1 21 | right -= 1 22 | else: 23 | break 24 | 25 | return max_score 26 | 27 | solution = Solution() 28 | print(solution.bagOfTokensScore([100], 50)) -------------------------------------------------------------------------------- /Python/baseball_game.py: -------------------------------------------------------------------------------- 1 | # Baseball Game 2 | 3 | class Solution(object): 4 | def calPoints(self, operations): 5 | record = [] 6 | for i in range(len(operations)): 7 | if operations[i] == '+': 8 | record.append(record[-1] + record[-2]) 9 | elif operations[i] == 'D': 10 | record.append(record[-1] * 2) 11 | elif operations[i] == 'C': 12 | record.pop() 13 | else: 14 | record.append(int(operations[i])) 15 | return sum(record) 16 | 17 | solution = Solution() 18 | print(solution.calPoints(["5","2","C","D","+"])) -------------------------------------------------------------------------------- /Python/best_time_to_buy_and_sell_stock.py: -------------------------------------------------------------------------------- 1 | # Best Time to Buy and Sell Stock 2 | 3 | class Solution(object): 4 | def maxProfit(self, prices): 5 | min_price = prices[0] 6 | max_profit = 0 7 | 8 | for price in prices: 9 | min_price = min(min_price, price) 10 | max_profit = max(max_profit, price - min_price) 11 | 12 | return max_profit 13 | 14 | solution = Solution() 15 | print(solution.maxProfit([7,1,5,3,6,4])) -------------------------------------------------------------------------------- /Python/binary_subarrays_with_sum.py: -------------------------------------------------------------------------------- 1 | # Binary Subarrays With Sum 2 | 3 | class Solution(object): 4 | def numSubarraysWithSum(self, nums, goal): 5 | count = {0: 1} 6 | curr_sum = 0 7 | total_subarrays = 0 8 | 9 | for num in nums: 10 | curr_sum += num 11 | if curr_sum - goal in count: 12 | total_subarrays += count[curr_sum - goal] 13 | count[curr_sum] = count.get(curr_sum, 0) + 1 14 | 15 | return total_subarrays 16 | 17 | solution = Solution() 18 | print(solution.numSubarraysWithSum([1,0,1,0,1], 2)) -------------------------------------------------------------------------------- /Python/binary_subarrays_with_sumvv.py: -------------------------------------------------------------------------------- 1 | # Binary Subarrays With Sumvv 2 | 3 | class Solution(object): 4 | def numSubarraysWithSum(self, nums, goal): 5 | count = {0: 1} 6 | curr_sum = 0 7 | total_subarrays = 0 8 | 9 | for num in nums: 10 | curr_sum += num 11 | if curr_sum - goal in count: 12 | total_subarrays += count[curr_sum - goal] 13 | count[curr_sum] = count.get(curr_sum, 0) + 1 14 | 15 | return total_subarrays 16 | 17 | solution = Solution() 18 | print(solution.numSubarraysWithSum([1,0,1,0,1], 2)) -------------------------------------------------------------------------------- /Python/binary_tree_inorder_traversal.py: -------------------------------------------------------------------------------- 1 | # Binary Tree Inorder Traversal 2 | 3 | class TreeNode(object): 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution(object): 10 | def inorderTraversal(self, root): 11 | def traverse(node, result): 12 | if node is None: 13 | return 14 | traverse(node.left, result) 15 | result.append(node.val) 16 | traverse(node.right, result) 17 | 18 | result = [] 19 | traverse(root, result) 20 | return result 21 | 22 | root = TreeNode(1) 23 | root.right = TreeNode(2) 24 | root.right.left = TreeNode(3) 25 | 26 | solution = Solution() 27 | 28 | print(solution.inorderTraversal(root)) -------------------------------------------------------------------------------- /Python/build_array_from_permutation.py: -------------------------------------------------------------------------------- 1 | # Build Array from Permutation 2 | 3 | class Solution(object): 4 | def buildArray(self, nums): 5 | return [nums[nums[i]] for i in range(len(nums))] 6 | 7 | test = Solution() 8 | print(test.buildArray([0,2,1,5,3,4])) -------------------------------------------------------------------------------- /Python/buy_two_chocolates.py: -------------------------------------------------------------------------------- 1 | # Buy Two Chocolates 2 | 3 | class Solution(object): 4 | def buyChoco(self, prices, money): 5 | prices.sort() 6 | cheapest_chocolates = sum(prices[:2]) 7 | difference = abs(cheapest_chocolates - money) if cheapest_chocolates <= money else money 8 | return difference 9 | 10 | solution = Solution() 11 | print(solution.buyChoco([1,2,2], 3)) -------------------------------------------------------------------------------- /Python/cells_in_a_range_on_an_excel_sheet.py: -------------------------------------------------------------------------------- 1 | # Cells in a Range on an Excel Sheet 2 | 3 | class Solution(object): 4 | def cellsInRange(self, s): 5 | start, start_char = int(s[1]), ord(s[0]) 6 | end, end_char = int(s[-1]) + 1, ord(s[3]) + 1 7 | arr = [] 8 | 9 | for i in range(start_char, end_char): 10 | for j in range(start, end): 11 | arr.append(chr(i) + str(j)) 12 | 13 | return arr 14 | 15 | solution = Solution() 16 | print(solution.cellsInRange("K1:L2")) -------------------------------------------------------------------------------- /Python/cells_with_odd_values_in_a_matrix.py: -------------------------------------------------------------------------------- 1 | # Cells with Odd Values in a Matrix 2 | 3 | class Solution(object): 4 | def oddCells(self, m, n, indices): 5 | matrix = [[0] * n for _ in range(m)] 6 | 7 | for ri, ci in indices: 8 | for j in range(n): 9 | matrix[ri][j] += 1 10 | for i in range(m): 11 | matrix[i][ci] += 1 12 | 13 | odd_count = sum(cell % 2 != 0 for row in matrix for cell in row) 14 | return odd_count 15 | 16 | solution = Solution() 17 | print(solution.oddCells(2, 3, [[0,1],[1,1]])) -------------------------------------------------------------------------------- /Python/cheapest_flights_within_k_stops.py: -------------------------------------------------------------------------------- 1 | # Cheapest Flights Within K Stops 2 | 3 | from collections import defaultdict 4 | from queue import Queue 5 | 6 | class Solution(object): 7 | def findCheapestPrice(self, n, flights, src, dst, k): 8 | adj = defaultdict(list) 9 | for flight in flights: 10 | adj[flight[0]].append((flight[1], flight[2])) 11 | 12 | dist = [float('inf')] * n 13 | dist[src] = 0 14 | 15 | q = Queue() 16 | q.put((src, 0)) 17 | stops = 0 18 | 19 | while not q.empty() and stops <= k: 20 | sz = q.qsize() 21 | for _ in range(sz): 22 | node, distance = q.get() 23 | 24 | if node not in adj: continue 25 | 26 | for neighbour, price in adj[node]: 27 | if price + distance >= dist[neighbour]: continue 28 | dist[neighbour] = price + distance 29 | q.put((neighbour, dist[neighbour])) 30 | 31 | stops += 1 32 | 33 | return dist[dst] if dist[dst] != float('inf') else -1 34 | 35 | test = Solution() 36 | print(test.findCheapestPrice(4, [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], 0, 3, 1)) -------------------------------------------------------------------------------- /Python/check_if_a_string_is_an_acronym_of_words.py: -------------------------------------------------------------------------------- 1 | # Check if a String Is an Acronym of Words 2 | 3 | class Solution(object): 4 | def isAcronym(self, words, s): 5 | if len(s) != len(words): 6 | return False 7 | 8 | for i in range(len(words)): 9 | if s[i] != words[i][0]: 10 | return False 11 | 12 | return True 13 | 14 | test = Solution() 15 | print(test.isAcronym(["alice","bob","charlie"], "abc")) -------------------------------------------------------------------------------- /Python/check_if_all_characters_have_equal_number_of_occurrences.py: -------------------------------------------------------------------------------- 1 | # Check if All Characters Have Equal Number of Occurrences 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def areOccurrencesEqual(self, s): 7 | counted_chars = Counter(s) 8 | main_count = counted_chars.most_common(1)[0][1] 9 | 10 | for count in counted_chars.values(): 11 | if main_count != count: 12 | return False 13 | 14 | return True 15 | 16 | solution = Solution() 17 | print(solution.areOccurrencesEqual("abacbc")) -------------------------------------------------------------------------------- /Python/check_if_number_has_equal_digit_count_and_digit_value.py: -------------------------------------------------------------------------------- 1 | # Check if Number Has Equal Digit Count and Digit Value 2 | 3 | class Solution(object): 4 | def digitCount(self, num): 5 | n = len(num) 6 | 7 | for i in range(n): 8 | digit = int(num[i]) 9 | count = num.count(str(i)) 10 | 11 | if count != digit: 12 | return False 13 | 14 | return True 15 | 16 | solution = Solution() 17 | print(solution.digitCount("1210")) -------------------------------------------------------------------------------- /Python/check_if_the_sentence_is_pangram.py: -------------------------------------------------------------------------------- 1 | # Check if the Sentence Is Pangram 2 | 3 | class Solution(object): 4 | def checkIfPangram(self, sentence): 5 | return len(set(sentence)) == 26 6 | 7 | solution = Solution() 8 | print(solution.checkIfPangram("thequickbrownfoxjumpsoverthelazydog")) -------------------------------------------------------------------------------- /Python/check_if_two_string_arrays_are_equivalent.py: -------------------------------------------------------------------------------- 1 | # Check If Two String Arrays are Equivalent 2 | 3 | class Solution(object): 4 | def arrayStringsAreEqual(self, word1, word2): 5 | return ''.join(word1) == ''.join(word2) 6 | 7 | test = Solution() 8 | print(test.arrayStringsAreEqual(["a", "cb"], ["ab", "c"])) -------------------------------------------------------------------------------- /Python/climbing_stairs.py: -------------------------------------------------------------------------------- 1 | # Climbing Stairs 2 | 3 | class Solution(object): 4 | def climbStairs(self, n): 5 | if n == 0 or n == 1: 6 | return 1 7 | 8 | dp = [0] * (n+1) 9 | dp[0] = dp[1] = 1 10 | 11 | for i in range(2, n+1): 12 | dp[i] = dp[i-1] + dp[i-2] 13 | return dp[n] 14 | 15 | solution = Solution() 16 | print(solution.climbStairs(2)) -------------------------------------------------------------------------------- /Python/combination_sum.py: -------------------------------------------------------------------------------- 1 | # Combination Sum 2 | 3 | class Solution(object): 4 | def combinationSum(self, candidates, target): 5 | def backtrack(start, target, path): 6 | if target == 0: 7 | result.append(path) 8 | return 9 | if target < 0: 10 | return 11 | for i in range(start, len(candidates)): 12 | backtrack(i, target - candidates[i], path + [candidates[i]]) 13 | 14 | result = [] 15 | candidates.sort() 16 | backtrack(0, target, []) 17 | return result 18 | 19 | solution = Solution() 20 | print(solution.combinationSum([2,3,6,7], 7)) -------------------------------------------------------------------------------- /Python/concatenation_of_array.py: -------------------------------------------------------------------------------- 1 | # Concatenation of Array 2 | 3 | class Solution(object): 4 | def getConcatenation(self, nums): 5 | return nums + nums 6 | 7 | test = Solution() 8 | print(test.getConcatenation([1,2,1])) -------------------------------------------------------------------------------- /Python/contains_duplicate_ii.py: -------------------------------------------------------------------------------- 1 | # Contains Duplicate II 2 | 3 | class Solution(object): 4 | def containsNearbyDuplicate(self, nums, k): 5 | hashmap = {} 6 | for i in range(len(nums)): 7 | if nums[i] in hashmap: 8 | if abs(hashmap[nums[i]] - i) <= k: 9 | return True 10 | hashmap[nums[i]] = i 11 | return False 12 | 13 | solution = Solution() 14 | print(solution.containsNearbyDuplicate([1,2,3,1], 3)) -------------------------------------------------------------------------------- /Python/contiguous_array.py: -------------------------------------------------------------------------------- 1 | # Contiguous Array 2 | 3 | class Solution(object): 4 | def findMaxLength(self, nums): 5 | max_length = 0 6 | sum_map = {0: -1} 7 | count = 0 8 | 9 | for i, num in enumerate(nums): 10 | if num == 0: 11 | count -= 1 12 | else: 13 | count += 1 14 | 15 | if count in sum_map: 16 | max_length = max(max_length, i - sum_map[count]) 17 | else: 18 | sum_map[count] = i 19 | 20 | return max_length 21 | 22 | solution = Solution() 23 | print(solution.findMaxLength()) -------------------------------------------------------------------------------- /Python/convert_binary_number_in_a_linked_list_to_integer.py: -------------------------------------------------------------------------------- 1 | # Convert Binary Number in a Linked List to Integer 2 | 3 | class ListNode(object): 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | class Solution(object): 9 | def getDecimalValue(self, head): 10 | decimal_value = 0 11 | 12 | while head: 13 | decimal_value = decimal_value * 2 + head.val 14 | head = head.next 15 | 16 | return decimal_value 17 | 18 | head = ListNode(1) 19 | head.next = ListNode(0) 20 | head.next.next = ListNode(1) 21 | 22 | solution = Solution() 23 | print(solution.getDecimalValue(head)) -------------------------------------------------------------------------------- /Python/convert_sorted_array_to_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | # Convert Sorted Array to Binary Search Tree 2 | 3 | class TreeNode(object): 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution(object): 10 | def sortedArrayToBST(self, nums): 11 | def helper(start, end): 12 | if start > end: 13 | return None 14 | mid = (start + end) // 2 15 | root = TreeNode(nums[mid]) 16 | root.left = helper(start, mid - 1) 17 | root.right = helper(mid + 1, end) 18 | return root 19 | 20 | return helper(0, len(nums) - 1) 21 | 22 | solution = Solution() 23 | print(solution.sortedArrayToBST([1,2,3,4])) -------------------------------------------------------------------------------- /Python/count_elements_with_maximum_frequency.py: -------------------------------------------------------------------------------- 1 | # Count Elements With Maximum Frequency 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def maxFrequencyElements(self, nums): 7 | freq_counter = Counter(nums) 8 | print(freq_counter) 9 | 10 | max_frequency = max(freq_counter.values()) 11 | 12 | max_freq_elements = [num for num, freq in freq_counter.items() if freq == max_frequency] 13 | 14 | total_frequency = max_frequency * len(max_freq_elements) 15 | 16 | return total_frequency 17 | 18 | solution = Solution() 19 | print(solution.maxFrequencyElements([1,2,2,3,1,4])) -------------------------------------------------------------------------------- /Python/count_equal_and_divisible_pairs_in_an_array.py: -------------------------------------------------------------------------------- 1 | # Count Equal and Divisible Pairs in an Array 2 | 3 | class Solution(object): 4 | def countPairs(self, nums, k): 5 | count = 0 6 | n = len(nums) 7 | for i in range(n): 8 | for j in range(i+1, n): 9 | if nums[i] == nums[j] and (i * j) % k == 0: 10 | count += 1 11 | return count 12 | 13 | solution = Solution() 14 | print(solution.countPairs([3,1,2,2,2,1,3], 2)) -------------------------------------------------------------------------------- /Python/count_good_triplets.py: -------------------------------------------------------------------------------- 1 | # Count Good Triplets 2 | 3 | class Solution(object): 4 | def countGoodTriplets(self, arr, a, b, c): 5 | n = len(arr) 6 | count = 0 7 | for i in range(n): 8 | for j in range(i+1, n): 9 | for k in range(j+1, n): 10 | if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: 11 | count += 1 12 | return count 13 | 14 | solution = Solution() 15 | print(solution.countGoodTriplets([3,0,1,1,9,7], 7, 2, 3)) -------------------------------------------------------------------------------- /Python/count_items_matching_a_rule.py: -------------------------------------------------------------------------------- 1 | # Count Items Matching a Rule 2 | 3 | class Solution(object): 4 | def countMatches(self, items, ruleKey, ruleValue): 5 | count = 0 6 | for item in items: 7 | if ruleKey == "type" and item[0] == ruleValue: 8 | count += 1 9 | elif ruleKey == "color" and item[1] == ruleValue: 10 | count += 1 11 | elif ruleKey == "name" and item[2] == ruleValue: 12 | count += 1 13 | return count 14 | 15 | test = Solution() 16 | print(test.countMatches([["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], "color", "silver")) -------------------------------------------------------------------------------- /Python/count_negative_numbers_in_a_sorted_matrix.py: -------------------------------------------------------------------------------- 1 | # Count Negative Numbers in a Sorted Matrix 2 | 3 | class Solution(object): 4 | def countNegatives(self, grid): 5 | m, n = len(grid), len(grid[0]) 6 | count = 0 7 | row, col = m - 1, 0 8 | 9 | while row >= 0 and col < n: 10 | if grid[row][col] < 0: 11 | count += n - col 12 | row -= 1 13 | else: 14 | col += 1 15 | 16 | return count 17 | 18 | solution = Solution() 19 | print(solution.countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]])) -------------------------------------------------------------------------------- /Python/count_number_of_pairs_with_absolute_difference_k.py: -------------------------------------------------------------------------------- 1 | # Count Number of Pairs With Absolute Difference K 2 | 3 | class Solution(object): 4 | def countKDifference(self, nums, k): 5 | n = len(nums) 6 | return len([None for i in range(n) for j in range(i+1, n) if abs(nums[i] - nums[j]) == k]) 7 | 8 | test = Solution() 9 | print(test.countKDifference([1,2,2,1], 1)) -------------------------------------------------------------------------------- /Python/count_pairs_whose_sum_is_less_than_target.py: -------------------------------------------------------------------------------- 1 | # Count Pairs Whose Sum is Less than Target 2 | 3 | class Solution(object): 4 | def countPairs(self, nums, target): 5 | return len([None for i in range(len(nums)) for j in range(i+1, len(nums)) if nums[i] + nums[j] < target]) 6 | 7 | test = Solution() 8 | print(test.countPairs([-1,1,2,3,1], 2)) -------------------------------------------------------------------------------- /Python/count_prefixes_of_a_given_string.py: -------------------------------------------------------------------------------- 1 | # Count Prefixes of a Given String 2 | 3 | class Solution(object): 4 | def countPrefixes(self, words, s): 5 | count = 0 6 | 7 | for word in words: 8 | if word == s[:len(word)]: 9 | count += 1 10 | 11 | return count 12 | 13 | solution = Solution() 14 | print(solution.countPrefixes(["a","b","c","ab","bc","abc"], "abc")) -------------------------------------------------------------------------------- /Python/count_subarrays_with_fixed_bounds.py: -------------------------------------------------------------------------------- 1 | # Count Subarrays With Fixed Bounds 2 | 3 | class Solution(object): 4 | def countSubarrays(self, nums, minK, maxK): 5 | res = 0 6 | bad_idx = left_idx = right_idx = -1 7 | 8 | for i, num in enumerate(nums) : 9 | if not minK <= num <= maxK: 10 | bad_idx = i 11 | 12 | if num == minK: 13 | left_idx = i 14 | 15 | if num == maxK: 16 | right_idx = i 17 | 18 | res += max(0, min(left_idx, right_idx) - bad_idx) 19 | 20 | return res 21 | 22 | solution = Solution() 23 | print(solution.countSubarrays([1,3,5,2,7,5], 1, 5)) -------------------------------------------------------------------------------- /Python/count_substrings_starting_and_ending_with_given_character.py: -------------------------------------------------------------------------------- 1 | # Count Substrings Starting and Ending with Given Character 2 | 3 | class Solution(object): 4 | def countSubstrings(self, s, c): 5 | count = s.count(c) 6 | return count * (count + 1) // 2 7 | 8 | solution = Solution() 9 | print(solution.countSubstrings("abada", "a")) -------------------------------------------------------------------------------- /Python/count_tested_devices_after_test_operations.py: -------------------------------------------------------------------------------- 1 | # Count Tested Devices After Test Operations 2 | 3 | class Solution(object): 4 | def countTestedDevices(self, batteryPercentages): 5 | count = 0 6 | n = len(batteryPercentages) 7 | for i in range(n): 8 | if batteryPercentages[i] > 0: 9 | count += 1 10 | for j in range(i+1, n): 11 | batteryPercentages[j] -= 1 12 | return count 13 | 14 | solution = Solution() 15 | print(solution.countTestedDevices([1,1,2,1,3])) -------------------------------------------------------------------------------- /Python/count_the_number_of_consistent_strings.py: -------------------------------------------------------------------------------- 1 | # Count the Number of Consistent Strings 2 | 3 | class Solution(object): 4 | def countConsistentStrings(self, allowed, words): 5 | count = 0 6 | 7 | for word in words: 8 | if all(char in allowed for char in word): 9 | count += 1 10 | 11 | return count 12 | 13 | test = Solution() 14 | print(test.countConsistentStrings("ab", ["ad","bd","aaab","baa","badab"])) -------------------------------------------------------------------------------- /Python/counting_words_with_a_given_prefix.py: -------------------------------------------------------------------------------- 1 | # Counting Words With a Given Prefix 2 | 3 | class Solution(object): 4 | def prefixCount(self, words, pref): 5 | n = len(pref) 6 | count = 0 7 | for i in range(len(words)): 8 | if words[i][:n] == pref: 9 | count += 1 10 | return count 11 | 12 | solution = Solution() 13 | print(solution.prefixCount(["pay","attention","practice","attend"], "at")) -------------------------------------------------------------------------------- /Python/create_target_array_in_the_given_order.py: -------------------------------------------------------------------------------- 1 | # Create Target Array in the Given Order 2 | 3 | class Solution(object): 4 | def createTargetArray(self, nums, index): 5 | arr = [] 6 | for i, num in zip(index, nums): 7 | arr.insert(i, num) 8 | return arr 9 | 10 | test = Solution() 11 | print(test.createTargetArray([0,1,2,3,4], [0,1,2,2,1])) -------------------------------------------------------------------------------- /Python/decode_the_message.py: -------------------------------------------------------------------------------- 1 | # Decode the Message 2 | 3 | class Solution(object): 4 | def decodeMessage(self, key, message): 5 | mapping = {' ': ' '} 6 | i = 0 7 | res = '' 8 | letters = 'abcdefghijklmnopqrstuvwxyz' 9 | 10 | for char in key: 11 | if char not in mapping: 12 | mapping[char] = letters[i] 13 | i += 1 14 | 15 | for char in message: 16 | res += mapping[char] 17 | 18 | return res 19 | 20 | solution = Solution() 21 | print(solution.decodeMessage("the quick brown fox jumps over the lazy dog", "the quick brown fox jumps over the lazy dog")) -------------------------------------------------------------------------------- /Python/decode_xored_array.py: -------------------------------------------------------------------------------- 1 | # Decode XORed Array 2 | 3 | class Solution(object): 4 | def decode(self, encoded, first): 5 | decoded_array = [first] 6 | for num in encoded: 7 | decoded_array.append(decoded_array[-1] ^ num) 8 | return decoded_array 9 | 10 | test = Solution() 11 | print(test.decode([1, 2, 3, 4, 5])) -------------------------------------------------------------------------------- /Python/decompress_run-length_encoded_list.py: -------------------------------------------------------------------------------- 1 | # Decompress Run-Length Encoded List 2 | 3 | class Solution(object): 4 | def decompressRLElist(self, nums): 5 | arr = [] 6 | for i in range(0, len(nums), 2): 7 | arr += [nums[i+1]] * nums[i] 8 | return arr 9 | 10 | test = Solution() 11 | print(test.decompressRLElist([1,2,3,4])) -------------------------------------------------------------------------------- /Python/defanging_an_ip_address.py: -------------------------------------------------------------------------------- 1 | # Defanging an IP Address 2 | 3 | class Solution(object): 4 | def defangIPaddr(self, address): 5 | return address.replace('.', '[.]') 6 | 7 | test = Solution() 8 | print(test.defangIPaddr("1.1.1.1")) -------------------------------------------------------------------------------- /Python/delete_greatest_value_in_each_row.py: -------------------------------------------------------------------------------- 1 | # Delete Greatest Value in Each Row 2 | 3 | class Solution(object): 4 | def deleteGreatestValue(self, grid): 5 | cound = 0 6 | n = len(grid) 7 | if n > 1: 8 | for i in range(len(grid[0])): 9 | new_list = [] 10 | for j in range(n): 11 | a = sorted(grid[j]) 12 | new_list.append(a[i]) 13 | cound+=max(new_list) 14 | return cound 15 | else: 16 | return sum(grid[0]) 17 | 18 | solution = Solution() 19 | print(solution.deleteGreatestValue([[1,2,4],[3,3,1]])) -------------------------------------------------------------------------------- /Python/design_an_ordered_stream.py: -------------------------------------------------------------------------------- 1 | # Design an Ordered Stream 2 | 3 | class OrderedStream(object): 4 | def __init__(self, n): 5 | self.stream = [None] * (n + 1) 6 | self.ptr = 1 7 | 8 | def insert(self, idKey, value): 9 | self.stream[idKey] = value 10 | result = [] 11 | 12 | while self.ptr < len(self.stream) and self.stream[self.ptr] is not None: 13 | result.append(self.stream[self.ptr]) 14 | self.ptr += 1 15 | return result 16 | 17 | ordered_stream = OrderedStream(5) 18 | print(ordered_stream.insert(3, "c")) 19 | print(ordered_stream.insert(1, "a")) 20 | print(ordered_stream.insert(2, "b")) 21 | print(ordered_stream.insert(5, "e")) 22 | print(ordered_stream.insert(4, "d")) -------------------------------------------------------------------------------- /Python/destination_city.py: -------------------------------------------------------------------------------- 1 | # Destination City 2 | 3 | class Solution(object): 4 | def destCity(self, paths): 5 | outgoing_cities = set() 6 | for path in paths: 7 | outgoing_cities.add(path[0]) 8 | 9 | for path in paths: 10 | city = path[1] 11 | if city not in outgoing_cities: 12 | return city 13 | 14 | solution = Solution() 15 | print(solution.destCity([["pYyNGfBYbm","wxAscRuzOl"],["kzwEQHfwce","pYyNGfBYbm"]])) 16 | -------------------------------------------------------------------------------- /Python/di_string_match.py: -------------------------------------------------------------------------------- 1 | # DI String Match 2 | 3 | class Solution(object): 4 | def diStringMatch(self, s): 5 | n = len(s) 6 | perm = list(range(n + 1)) 7 | result = [] 8 | 9 | for char in s: 10 | if char == 'I': 11 | result.append(perm.pop(0)) 12 | elif char == 'D': 13 | result.append(perm.pop()) 14 | 15 | result.append(perm[0]) 16 | return result 17 | 18 | solution = Solution() 19 | print(solution.diStringMatch("IDID")) -------------------------------------------------------------------------------- /Python/diameter_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | # Diameter of Binary Tree 2 | 3 | class TreeNode(object): 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution(object): 10 | def diameterOfBinaryTree(self, root): 11 | def diameter(node, res): 12 | if not node: 13 | return 0 14 | 15 | left = diameter(node.left, res) 16 | right = diameter(node.right, res) 17 | 18 | res[0] = max(res[0], left + right) 19 | 20 | return max(left, right) + 1 21 | 22 | res = [0] 23 | diameter(root, res) 24 | return res[0] 25 | 26 | root = TreeNode(1) 27 | root.left = TreeNode(2) 28 | root.right = TreeNode(3) 29 | root.left.left = TreeNode(4) 30 | root.left.right = TreeNode(5) 31 | 32 | test = Solution() 33 | print(test.diameterOfBinaryTree(root)) -------------------------------------------------------------------------------- /Python/difference_between_element_sum_and_digit_sum_of_an_array.py: -------------------------------------------------------------------------------- 1 | # Difference Between Element Sum and Digit Sum of an Array 2 | 3 | class Solution(object): 4 | def differenceOfSum(self, nums): 5 | return sum(nums) - sum([int(s) for num in nums for s in str(num)]) 6 | 7 | test = Solution() 8 | print(test.differenceOfSum()) -------------------------------------------------------------------------------- /Python/distribute_candies.py: -------------------------------------------------------------------------------- 1 | # Distribute Candies 2 | 3 | class Solution(object): 4 | def distributeCandies(self, candyType): 5 | unique_candies = len(set(candyType)) 6 | max_candies = min(unique_candies, len(candyType) // 2) 7 | 8 | return max_candies 9 | 10 | solution = Solution() 11 | print(solution.distributeCandies([1,1,2,2,3,3])) -------------------------------------------------------------------------------- /Python/divide_array_into_equal_pairs.py: -------------------------------------------------------------------------------- 1 | # Divide Array Into Equal Pairs 2 | 3 | class Solution(object): 4 | def divideArray(self, nums): 5 | counts = {} 6 | 7 | for num in nums: 8 | counts[num] = counts.get(num, 0) + 1 9 | 10 | for count in counts.values(): 11 | if count % 2 != 0: 12 | return False 13 | 14 | return True 15 | 16 | solution = Solution() 17 | print(solution.divideArray([3,2,3,2,2,2])) -------------------------------------------------------------------------------- /Python/even_odd_tree.py: -------------------------------------------------------------------------------- 1 | # Even Odd Tree 2 | 3 | from collections import deque 4 | 5 | class TreeNode: 6 | def __init__(self, val=0, left=None, right=None): 7 | self.val = val 8 | self.left = left 9 | self.right = right 10 | 11 | class Solution: 12 | def isEvenOddTree(self, root): 13 | if not root: 14 | return True 15 | 16 | queue = deque([root]) 17 | level = 0 18 | 19 | while queue: 20 | prev_val = None 21 | 22 | for _ in range(len(queue)): 23 | node = queue.popleft() 24 | 25 | if (level % 2 == 0 and (node.val % 2 == 0 or (prev_val is not None and node.val <= prev_val))) or \ 26 | (level % 2 == 1 and (node.val % 2 == 1 or (prev_val is not None and node.val >= prev_val))): 27 | return False 28 | 29 | prev_val = node.val 30 | 31 | if node.left: 32 | queue.append(node.left) 33 | if node.right: 34 | queue.append(node.right) 35 | 36 | level += 1 37 | 38 | return True 39 | 40 | root = TreeNode(1) 41 | root.left = TreeNode(10) 42 | root.right = TreeNode(4) 43 | root.left.left = TreeNode(3) 44 | root.left.right = TreeNode(7) 45 | root.right.right = TreeNode(9) 46 | 47 | solution = Solution() 48 | print(solution.isEvenOddTree(root)) 49 | -------------------------------------------------------------------------------- /Python/existence_of_a_substring_in_a_string_and_its_reverse.py: -------------------------------------------------------------------------------- 1 | # Existence of a Substring in a String and Its Reverse 2 | 3 | class Solution(object): 4 | def isSubstringPresent(self, s): 5 | for i in range(len(s) - 1): 6 | if s[i:i+2] in s[::-1]: 7 | return True 8 | 9 | return False 10 | 11 | solution = Solution() 12 | print(solution.isSubstringPresent("leetcode")) -------------------------------------------------------------------------------- /Python/final_prices_with_a_special_discount_in_a_shop.py: -------------------------------------------------------------------------------- 1 | # Final Prices With a Special Discount in a Shop 2 | 3 | class Solution(object): 4 | def finalPrices(self, prices): 5 | stack = [] 6 | for i, price in enumerate(prices): 7 | while stack and prices[stack[-1]] >= price: 8 | prices[stack.pop()] -= price 9 | stack.append(i) 10 | return prices 11 | 12 | solution = Solution() 13 | print(solution.finalPrices([8,4,6,2,3])) -------------------------------------------------------------------------------- /Python/final_value_of_variable_after_performing_operations.py: -------------------------------------------------------------------------------- 1 | # Final Value of Variable After Performing Operations 2 | 3 | class Solution(object): 4 | def finalValueAfterOperations(self, operations): 5 | count = 0 6 | for operation in operations: 7 | if operation[1] == "+": 8 | count += 1 9 | else: 10 | count -= 1 11 | return count 12 | 13 | test = Solution() 14 | print(test.finalValueAfterOperations(["--X","X++","X++"])) -------------------------------------------------------------------------------- /Python/find_all_people_with_secret.py: -------------------------------------------------------------------------------- 1 | # Find All People With Secret 2 | 3 | from collections import defaultdict, deque 4 | 5 | class Solution(object): 6 | def findAllPeople(self, n, meetings, firstPerson): 7 | known_set = set([0, firstPerson]) 8 | 9 | sorted_meetings = [] 10 | meetings.sort(key=lambda x:x[2]) 11 | 12 | seen_time = set() 13 | 14 | for meeting in meetings: 15 | if meeting[2] not in seen_time: 16 | seen_time.add(meeting[2]) 17 | sorted_meetings.append([]) 18 | sorted_meetings[-1].append((meeting[0], meeting[1])) 19 | 20 | for meeting_group in sorted_meetings: 21 | people_know_secret = set() 22 | graph = defaultdict(list) 23 | 24 | for p1, p2 in meeting_group: 25 | graph[p1].append(p2) 26 | graph[p2].append(p1) 27 | if p1 in known_set: 28 | people_know_secret.add(p1) 29 | if p2 in known_set: 30 | people_know_secret.add(p2) 31 | 32 | queue = deque((people_know_secret)) 33 | 34 | while queue: 35 | curr = queue.popleft() 36 | known_set.add(curr) 37 | for neighbor in graph[curr]: 38 | if neighbor not in known_set: 39 | known_set.add(neighbor) 40 | queue.append(neighbor) 41 | 42 | return list(known_set) 43 | 44 | test = Solution() 45 | print(test.findAllPeople(6, [[1,2,5],[2,3,8],[1,5,10]], 1)) -------------------------------------------------------------------------------- /Python/find_bottom_left_tree_value.py: -------------------------------------------------------------------------------- 1 | # Find Bottom Left Tree Value 2 | 3 | from collections import deque 4 | 5 | class TreeNode: 6 | def __init__(self, value=0, left=None, right=None): 7 | self.val = value 8 | self.left = left 9 | self.right = right 10 | 11 | class Solution(object): 12 | def findBottomLeftValue(self, root): 13 | queue = deque([root]) 14 | leftmost_value = None 15 | 16 | while queue: 17 | node = queue.popleft() 18 | 19 | leftmost_value = node.val 20 | 21 | if node.right: 22 | queue.append(node.right) 23 | if node.left: 24 | queue.append(node.left) 25 | 26 | return leftmost_value 27 | 28 | root = TreeNode(2, TreeNode(1), TreeNode(3)) 29 | 30 | test = Solution() 31 | print(test.findBottomLeftValue(root)) -------------------------------------------------------------------------------- /Python/find_champion_i.py: -------------------------------------------------------------------------------- 1 | # Find Champion I 2 | 3 | class Solution(object): 4 | def findChampion(self, grid): 5 | n = len(grid) 6 | for i in range(n): 7 | if sum(grid[i]) == n - 1: 8 | return i 9 | 10 | solution = Solution() 11 | print(solution.findChampion([[0,1],[0,0]])) -------------------------------------------------------------------------------- /Python/find_common_elements_between_two_arrays.py: -------------------------------------------------------------------------------- 1 | # Find Common Elements Between Two Arrays 2 | 3 | class Solution(object): 4 | def findIntersectionValues(self, nums1, nums2): 5 | set1 = set(nums1) 6 | set2 = set(nums2) 7 | 8 | count1 = sum(1 for num in nums1 if num in set2) 9 | 10 | count2 = sum(1 for num in nums2 if num in set1) 11 | 12 | return [count1, count2] 13 | 14 | solution = Solution() 15 | print(solution.findIntersectionValues([4,3,2,3,1], [2,2,5,2,3,6])) -------------------------------------------------------------------------------- /Python/find_first_palindromic_string_in_the_array.py: -------------------------------------------------------------------------------- 1 | # Find First Palindromic String in the Array 2 | 3 | class Solution(object): 4 | def firstPalindrome(self, words): 5 | for word in words: 6 | if word[::-1] == word: 7 | return word 8 | return '' 9 | 10 | test = Solution() 11 | print(test.firstPalindrome(["abc","car","ada","racecar","cool"])) -------------------------------------------------------------------------------- /Python/find_greatest_common_divisor_of_array.py: -------------------------------------------------------------------------------- 1 | # Find Greatest Common Divisor of Array 2 | 3 | class Solution(object): 4 | def findGCD(self, nums): 5 | def gcd(a, b): 6 | while b: 7 | a, b = b, a % b 8 | return a 9 | 10 | if not nums: 11 | return None 12 | 13 | smallest = min(nums) 14 | largest = max(nums) 15 | 16 | result = gcd(smallest, largest) 17 | 18 | return result 19 | 20 | solution = Solution() 21 | print(solution.findGCD([2,5,6,9,10])) -------------------------------------------------------------------------------- /Python/find_maximum_number_of_string_pairs.py: -------------------------------------------------------------------------------- 1 | # Find Maximum Number of String Pairs 2 | 3 | class Solution(object): 4 | def maximumNumberOfStringPairs(self, words): 5 | count = 0 6 | n = len(words) 7 | for i in range(n): 8 | for j in range(i+1, n): 9 | if words[i] == words[j][::-1]: 10 | count += 1 11 | return count 12 | 13 | solution = Solution() 14 | print(solution.maximumNumberOfStringPairs()) -------------------------------------------------------------------------------- /Python/find_missing_and_repeated_values.py: -------------------------------------------------------------------------------- 1 | # Find Missing and Repeated Values 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def findMissingAndRepeatedValues(self, grid): 7 | n = len(grid) 8 | nums = [] 9 | 10 | for row in grid: 11 | nums.extend(row) 12 | 13 | counted_nums = Counter(nums) 14 | repeating = None 15 | 16 | for num in counted_nums: 17 | if counted_nums[num] == 2: 18 | repeating = num 19 | break 20 | 21 | missing = None 22 | for num in range(1, n*n + 1): 23 | if num not in counted_nums: 24 | missing = num 25 | break 26 | 27 | return [repeating, missing] 28 | 29 | solution = Solution() 30 | print(solution.findMissingAndRepeatedValues([[1,3],[2,2]])) -------------------------------------------------------------------------------- /Python/find_n_unique_integers_sum_up_to_zero.py: -------------------------------------------------------------------------------- 1 | # Find N Unique Integers Sum up to Zero 2 | 3 | class Solution(object): 4 | def sumZero(self, n): 5 | result = list(range(1, n)) 6 | result.append(-sum(result)) 7 | 8 | return result 9 | 10 | solution = Solution() 11 | print(solution.sumZero(5)) -------------------------------------------------------------------------------- /Python/find_numbers_with_even_number_of_digits.py: -------------------------------------------------------------------------------- 1 | # Find Numbers with Even Number of Digits 2 | 3 | class Solution(object): 4 | def findNumbers(self, nums): 5 | count = 0 6 | for num in nums: 7 | if len(str(num)) % 2 == 0: 8 | count += 1 9 | return count 10 | 11 | solution = Solution() 12 | print(solution.findNumbers([12,345,2,6,7896])) -------------------------------------------------------------------------------- /Python/find_pivot_index.py: -------------------------------------------------------------------------------- 1 | # Find Pivot Index 2 | 3 | class Solution(object): 4 | def pivotIndex(self, nums): 5 | left_sum = 0 6 | right_sum = sum(nums) 7 | 8 | for i in range(len(nums)): 9 | right_sum -= nums[i] 10 | if left_sum == right_sum: 11 | return i 12 | left_sum += nums[i] 13 | 14 | return -1 15 | 16 | solution = Solution() 17 | print(solution.pivotIndex([1,7,3,6,5,6])) -------------------------------------------------------------------------------- /Python/find_target_indices_after_sorting_array.py: -------------------------------------------------------------------------------- 1 | # Find Target Indices After Sorting Array 2 | 3 | class Solution(object): 4 | def targetIndices(self, nums, target): 5 | lessThanCount = 0 6 | equalCount = 0 7 | 8 | for x in nums: 9 | if x == target: 10 | equalCount += 1 11 | elif x < target: 12 | lessThanCount += 1 13 | 14 | results = [] 15 | 16 | l = lessThanCount 17 | r = l + equalCount 18 | for i in range(l, r): 19 | results.append(i) 20 | 21 | return results 22 | 23 | solution = Solution() 24 | print(solution.targetIndices([1,2,5,2,3], 2)) -------------------------------------------------------------------------------- /Python/find_the_difference_of_two_arrays.py: -------------------------------------------------------------------------------- 1 | # Find the Difference of Two Arrays 2 | 3 | class Solution(object): 4 | def findDifference(self, nums1, nums2): 5 | nums1, nums2 = set(nums1), set(nums2) 6 | return [[num for num in nums1 if num not in nums2], [num for num in nums2 if num not in nums1]] 7 | 8 | solution = Solution() 9 | print(solution.findDifference([1,2,3], [2,4,6])) -------------------------------------------------------------------------------- /Python/find_the_distinct_difference_array.py: -------------------------------------------------------------------------------- 1 | # Find the Distinct Difference Array 2 | 3 | class Solution(object): 4 | def distinctDifferenceArray(self, nums): 5 | diff = [] 6 | 7 | for i in range(len(nums)): 8 | prefix = len(set(nums[:i+1])) 9 | surfix = len(set(nums[i+1:])) 10 | diff.append(prefix-surfix) 11 | 12 | return diff 13 | 14 | solution = Solution() 15 | print(solution.distinctDifferenceArray([1,2,3,4,5])) -------------------------------------------------------------------------------- /Python/find_the_duplicate_number.py: -------------------------------------------------------------------------------- 1 | # Find the Duplicate Number 2 | 3 | class Solution(object): 4 | def findDuplicates(self, nums): 5 | p = 10 ** 5 + 3 6 | ans = [] 7 | 8 | for x in nums: 9 | next = (x % p) - 1 10 | if nums[next] > p: 11 | ans.append(next + 1) 12 | nums[next] += p 13 | 14 | return ans 15 | 16 | solution = Solution() 17 | print(solution.findDuplicates([4,3,2,7,8,2,3,1])) -------------------------------------------------------------------------------- /Python/find_the_highest_altitude.py: -------------------------------------------------------------------------------- 1 | # Find the Highest Altitude 2 | 3 | class Solution(object): 4 | def largestAltitude(self, gain): 5 | _sum = 0 6 | highest_altitude = 0 7 | for num in gain: 8 | _sum += num 9 | highest_altitude = max(_sum, highest_altitude) 10 | return highest_altitude 11 | 12 | test = Solution() 13 | print(test.largestAltitude([-5,1,5,0,-7])) -------------------------------------------------------------------------------- /Python/find_the_index_of_the_first_occurrence_in_a_string.py: -------------------------------------------------------------------------------- 1 | # Find the Index of the First Occurrence in a String 2 | 3 | class Solution(object): 4 | def strStr(self, haystack, needle): 5 | n = len(needle) 6 | for i in range(len(haystack)-n+1): 7 | if haystack[i : i+n] == needle: 8 | return i 9 | return -1 10 | 11 | solution = Solution() 12 | print(solution.strStr("sadbutsad", "sad")) -------------------------------------------------------------------------------- /Python/find_the_k-or_of_an_array.py: -------------------------------------------------------------------------------- 1 | # Find the K-or of an Array 2 | 3 | class Solution(object): 4 | def findKOr(self, nums, k): 5 | result = 0 6 | 7 | for i in range(31, -1, -1): 8 | count = 0 9 | for num in nums: 10 | if num & (1 << i): 11 | count += 1 12 | if count >= k: 13 | result |= (1 << i) 14 | 15 | return result 16 | 17 | solution = Solution() 18 | print(solution.findKOr([7,12,9,8,9,15], 4 )) -------------------------------------------------------------------------------- /Python/find_the_peaks.py: -------------------------------------------------------------------------------- 1 | # Find the Peaks 2 | 3 | class Solution(object): 4 | def findPeaks(self, mountain): 5 | peaks = [] 6 | n = len(mountain) 7 | for i in range(1, n - 1): 8 | if mountain[i] > mountain[i - 1] and mountain[i] > mountain[i + 1]: 9 | peaks.append(i) 10 | return peaks 11 | 12 | solution = Solution() 13 | print(solution.findPeaks([2,4,4])) -------------------------------------------------------------------------------- /Python/find_the_pivot_integer.py: -------------------------------------------------------------------------------- 1 | # Find the Pivot Integer 2 | 3 | from math import sqrt 4 | 5 | class Solution(object): 6 | def pivotInteger(self, n): 7 | x = sqrt(n * (n + 1) / 2) 8 | 9 | if x % 1 != 0: 10 | return -1 11 | else: 12 | return int(x) 13 | 14 | solution = Solution() 15 | print(solution.pivotInteger(8)) -------------------------------------------------------------------------------- /Python/find_the_town_judge.py: -------------------------------------------------------------------------------- 1 | # Find the Town Judge 2 | 3 | class Solution(object): 4 | def findJudge(self, n, trust): 5 | 6 | in_degree = [0] * (n + 1) 7 | out_degree = [0] * (n + 1) 8 | 9 | for a in trust: 10 | out_degree[a[0]] += 1 11 | in_degree[a[1]] += 1 12 | for i in range(1, n + 1): 13 | if in_degree[i] == n - 1 and out_degree[i] == 0: 14 | return i 15 | return -1 16 | 17 | test = Solution() 18 | print(test.findJudge(2, [[1,2]])) -------------------------------------------------------------------------------- /Python/find_words_containing_character.py: -------------------------------------------------------------------------------- 1 | # Find Words Containing Character 2 | 3 | class Solution(object): 4 | def findWordsContaining(self, words, x): 5 | arr = [] 6 | for i in range(len(words)): 7 | if x in words[i]: 8 | arr.append(i) 9 | return arr 10 | 11 | test = Solution() 12 | print(test.findWordsContaining(["leet","code"], "e")) -------------------------------------------------------------------------------- /Python/first_letter_to_appear_twice.py: -------------------------------------------------------------------------------- 1 | # First Letter to Appear Twice 2 | 3 | class Solution(object): 4 | def repeatedCharacter(self, s): 5 | hash_set = set() 6 | 7 | for char in s: 8 | if char in hash_set: 9 | return char 10 | hash_set.add(char) 11 | 12 | return char 13 | 14 | solution = Solution() 15 | print(solution.repeatedCharacter("abccbaacz")) -------------------------------------------------------------------------------- /Python/first_missing_positive.py: -------------------------------------------------------------------------------- 1 | # First Missing Positive 2 | 3 | class Solution(object): 4 | def firstMissingPositive(self, nums): 5 | n = len(nums) 6 | for i in range(n): 7 | while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: 8 | nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] 9 | 10 | for i in range(n): 11 | if nums[i] != i + 1: 12 | return i + 1 13 | 14 | return n + 1 15 | 16 | solution = Solution() 17 | print(solution.firstMissingPositive([1,2,0])) -------------------------------------------------------------------------------- /Python/flipping_an_image.py: -------------------------------------------------------------------------------- 1 | # Flipping an Image 2 | 3 | class Solution(object): 4 | def flipAndInvertImage(self, image): 5 | return [[1 ^ pixel for pixel in row[::-1]] for row in image] 6 | 7 | solution = Solution() 8 | print(solution.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]])) -------------------------------------------------------------------------------- /Python/generate_parentheses.py: -------------------------------------------------------------------------------- 1 | # Generate Parentheses 2 | 3 | class Solution(object): 4 | def generateParenthesis(self, n): 5 | def backtrack(S='', left=0, right=0): 6 | if len(S) == 2 * n: 7 | result.append(S) 8 | return 9 | if left < n: 10 | backtrack(S + '(', left + 1, right) 11 | if right < left: 12 | backtrack(S + ')', left, right + 1) 13 | 14 | result = [] 15 | backtrack() 16 | return result 17 | 18 | solution = Solution() 19 | print(solution.generateParenthesis(3)) -------------------------------------------------------------------------------- /Python/goal_parser_interpretation.py: -------------------------------------------------------------------------------- 1 | # Goal Parser Interpretation 2 | 3 | class Solution(object): 4 | def interpret(self, command): 5 | return command.replace('()', 'o').replace('(', '').replace(')', '') 6 | 7 | solution = Solution() 8 | print(solution.interpret("G()(al)")) -------------------------------------------------------------------------------- /Python/greatest_common_divisor_traversal.py: -------------------------------------------------------------------------------- 1 | # Greatest Common Divisor Traversal 2 | 3 | class Solution(object): 4 | def canTraverseAllPairs(self, nums): 5 | num_elements = len(nums) 6 | 7 | if num_elements == 1: 8 | return True 9 | 10 | disjoint_set = [_ for _ in range(num_elements)] 11 | 12 | 13 | set_size = [1] * num_elements 14 | 15 | factor_first_occurrence = {} 16 | 17 | def find_set_leader(x): 18 | if disjoint_set[x] == x: 19 | return x 20 | disjoint_set[x] = find_set_leader(disjoint_set[x]) 21 | return disjoint_set[x] 22 | 23 | def union_sets(x, y): 24 | x_leader, y_leader = find_set_leader(x), find_set_leader(y) 25 | if x_leader == y_leader: 26 | return 27 | if set_size[x_leader] < set_size[y_leader]: 28 | x_leader, y_leader = y_leader, x_leader 29 | disjoint_set[y_leader] = x_leader 30 | set_size[x_leader] += set_size[y_leader] 31 | 32 | for i in range(num_elements): 33 | num = nums[i] 34 | divisor = 2 35 | while divisor * divisor <= num: 36 | if num % divisor == 0: 37 | if divisor in factor_first_occurrence: 38 | union_sets(i, factor_first_occurrence[divisor]) 39 | else: 40 | factor_first_occurrence[divisor] = i 41 | while num % divisor == 0: 42 | num //= divisor 43 | divisor += 1 44 | if num > 1: 45 | if num in factor_first_occurrence: 46 | union_sets(i, factor_first_occurrence[num]) 47 | else: 48 | factor_first_occurrence[num] = i 49 | 50 | return set_size[find_set_leader(0)] == num_elements 51 | 52 | test = Solution() 53 | print(test.canTraverseAllPairs([2,3,6])) -------------------------------------------------------------------------------- /Python/height_checker.py: -------------------------------------------------------------------------------- 1 | # Height Checker 2 | 3 | class Solution(object): 4 | def heightChecker(self, heights): 5 | expected = sorted(heights) 6 | 7 | count = sum(1 for i in range(len(heights)) if heights[i] != expected[i]) 8 | 9 | return count 10 | 11 | solution = Solution() 12 | print(solution.heightChecker([1,1,4,2,1,3])) -------------------------------------------------------------------------------- /Python/how_many_numbers_are_smaller_than_the_current_number.py: -------------------------------------------------------------------------------- 1 | # How Many Numbers Are Smaller Than the Current Number 2 | 3 | class Solution(object): 4 | def smallerNumbersThanCurrent(self, nums): 5 | counts = [0] * 101 6 | for num in nums: 7 | counts[num] += 1 8 | 9 | smaller_counts = [0] * len(nums) 10 | for i in range(len(nums)): 11 | smaller_counts[i] = sum(counts[:nums[i]]) 12 | 13 | return smaller_counts 14 | 15 | test = Solution() 16 | print(test.smallerNumbersThanCurrent([8,1,2,2,3])) -------------------------------------------------------------------------------- /Python/insert_interval.py: -------------------------------------------------------------------------------- 1 | # Insert Interval 2 | 3 | class Solution(object): 4 | def insert(self, intervals, newInterval): 5 | merged = [] 6 | i = 0 7 | 8 | while i < len(intervals) and intervals[i][1] < newInterval[0]: 9 | merged.append(intervals[i]) 10 | i += 1 11 | 12 | while i < len(intervals) and intervals[i][0] <= newInterval[1]: 13 | newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])] 14 | i += 1 15 | merged.append(newInterval) 16 | 17 | while i < len(intervals): 18 | merged.append(intervals[i]) 19 | i += 1 20 | 21 | return merged 22 | 23 | solution = Solution() 24 | print(solution.insert([[1,3],[6,9]], [2,5])) -------------------------------------------------------------------------------- /Python/intersection_of_two_arrays.py: -------------------------------------------------------------------------------- 1 | # Intersection of Two Arrays 2 | 3 | class Solution(object): 4 | def intersection(self, nums1, nums2): 5 | set1 = set(nums1) 6 | set2 = set(nums2) 7 | return list(set1.intersection(set2)) 8 | 9 | solution = Solution() 10 | print(solution.intersection([1,2,2,1], [2,2])) -------------------------------------------------------------------------------- /Python/is_subsequence.py: -------------------------------------------------------------------------------- 1 | # Is Subsequence 2 | 3 | class Solution(object): 4 | def isSubsequence(self, s, t): 5 | i = 0 6 | 7 | for char in t: 8 | if i < len(s) and char == s[i]: 9 | i += 1 10 | 11 | return i == len(s) 12 | 13 | solution = Solution() 14 | print(solution.isSubsequence("abc", "ahbgdc")) -------------------------------------------------------------------------------- /Python/isomorphic_strings.py: -------------------------------------------------------------------------------- 1 | # Isomorphic Strings 2 | 3 | class Solution(object): 4 | def isIsomorphic(self, s, t): 5 | return len(set(zip(s, t))) == len(set(s)) == len(set(t)) 6 | 7 | solution = Solution() 8 | print(solution.isIsomorphic("egg", "add")) -------------------------------------------------------------------------------- /Python/jewels_and_stones.py: -------------------------------------------------------------------------------- 1 | # Jewels and Stones 2 | 3 | class Solution(object): 4 | def numJewelsInStones(self, jewels, stones): 5 | count = 0 6 | for jewel in jewels: 7 | for stone in stones: 8 | count += stone.count(jewel) 9 | return count 10 | 11 | test = Solution() 12 | print(test.numJewelsInStones("aA", "aAAbbbb")) -------------------------------------------------------------------------------- /Python/kids_with_the_greatest_number_of_candies.py: -------------------------------------------------------------------------------- 1 | # Kids With the Greatest Number of Candies 2 | 3 | class Solution(object): 4 | def kidsWithCandies(self, candies, extraCandies): 5 | max_candies = max(candies) 6 | result = [kid_candies + extraCandies >= max_candies for kid_candies in candies] 7 | return result 8 | 9 | test = Solution() 10 | print(test.kidsWithCandies([2,3,5,1,3], 3)) -------------------------------------------------------------------------------- /Python/kth_distinct_string_in_an_array.py: -------------------------------------------------------------------------------- 1 | # Kth Distinct String in an Array 2 | 3 | class Solution: 4 | def kthDistinct(self, arr, k): 5 | count = {} 6 | 7 | for string in arr: 8 | count[string] = count.get(string, 0) + 1 9 | 10 | distinct_strings = [string for string, freq in count.items() if freq == 1] 11 | 12 | if len(distinct_strings) < k: 13 | return "" 14 | 15 | return distinct_strings[k - 1] 16 | 17 | solution = Solution() 18 | print(solution.kthDistinct(["d","b","c","b","c","a"], 2)) -------------------------------------------------------------------------------- /Python/largest_local_values_in_a_matrix.py: -------------------------------------------------------------------------------- 1 | # Largest Local Values in a Matrix 2 | 3 | class Solution(object): 4 | def largestLocal(self, grid): 5 | n = len(grid) 6 | max_local = [] 7 | 8 | for i in range(n - 2): 9 | row_max = [] 10 | for j in range(n - 2): 11 | submatrix_max = max( 12 | grid[i][j], grid[i][j+1], grid[i][j+2], 13 | grid[i+1][j], grid[i+1][j+1], grid[i+1][j+2], 14 | grid[i+2][j], grid[i+2][j+1], grid[i+2][j+2], 15 | 16 | ) 17 | row_max.append(submatrix_max) 18 | max_local.append(row_max) 19 | 20 | return max_local 21 | 22 | test = Solution() 23 | print(test.largestLocal([[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]])) -------------------------------------------------------------------------------- /Python/left_and_right_sum_differences.py: -------------------------------------------------------------------------------- 1 | # Left and Right Sum Differences 2 | 3 | class Solution(object): 4 | def leftRightDifference(self, nums): 5 | total_sum = sum(nums) 6 | left_sum = 0 7 | answer = [] 8 | 9 | for num in nums: 10 | total_sum -=num 11 | answer.append(abs(left_sum - total_sum)) 12 | left_sum += num 13 | 14 | return answer 15 | 16 | test = Solution() 17 | print(test.leftRightDifference([10,4,8,3])) -------------------------------------------------------------------------------- /Python/length_of_last_word.py: -------------------------------------------------------------------------------- 1 | # Length of Last Word 2 | 3 | class Solution(object): 4 | def lengthOfLastWord(self, s): 5 | words = s.strip().split() 6 | 7 | if not words: 8 | return 0 9 | 10 | return len(words[-1]) 11 | 12 | solution = Solution() 13 | print(solution.lengthOfLastWord("Hello World")) -------------------------------------------------------------------------------- /Python/letter_combinations_of_a_phone_number.py: -------------------------------------------------------------------------------- 1 | # Letter Combinations of a Phone Number 2 | 3 | class Solution(object): 4 | def letterCombinations(self, digits): 5 | if not digits: 6 | return [] 7 | 8 | mappings = { 9 | "2": "abc", 10 | "3": "def", 11 | "4": "ghi", 12 | "5": "jkl", 13 | "6": "mno", 14 | "7": "pqrs", 15 | "8": "tuv", 16 | "9": "wxyz" 17 | } 18 | 19 | def backtrack(index, path): 20 | if index == len(digits): 21 | combinations.append("".join(path)) 22 | return 23 | 24 | for char in mappings[digits[index]]: 25 | path.append(char) 26 | backtrack(index + 1, path) 27 | path.pop() 28 | 29 | combinations = [] 30 | backtrack(0, []) 31 | return combinations 32 | 33 | solution = Solution() 34 | print(solution.letterCombinations("23")) -------------------------------------------------------------------------------- /Python/lexicographically_smallest_palindrome.py: -------------------------------------------------------------------------------- 1 | # Lexicographically Smallest Palindrome 2 | 3 | class Solution(object): 4 | def makeSmallestPalindrome(self, s): 5 | return ''.join(map(min, zip(s, s[::-1]))) 6 | 7 | solution = Solution() 8 | print(solution.makeSmallestPalindrome("egcfe")) -------------------------------------------------------------------------------- /Python/longest_common_prefix.py: -------------------------------------------------------------------------------- 1 | # Longest Common Prefix 2 | 3 | class Solution(object): 4 | def longestCommonPrefix(self, strs): 5 | min_len = min(len(s) for s in strs) 6 | prefix = "" 7 | for i in range(min_len): 8 | char = strs[0][i] 9 | if all(s[i] == char for s in strs): 10 | prefix += char 11 | else: 12 | break 13 | return prefix 14 | 15 | solution = Solution() 16 | print(solution.longestCommonPrefix(["flower","flow","flight"])) -------------------------------------------------------------------------------- /Python/longest_common_suffix_queries.py: -------------------------------------------------------------------------------- 1 | # Longest Common Suffix Queries 2 | 3 | class Node: 4 | def __init__(self): 5 | self.link = [None] * 26 6 | self.idx = -1 7 | self.end = -1 8 | self.min_len = 10**9 9 | 10 | class Trie: 11 | def __init__(self): 12 | self.root = Node() 13 | 14 | def insert(self, s, i): 15 | s = s[::-1] 16 | ptr = self.root 17 | for ch in s: 18 | if not ptr.link[ord(ch) - ord('a')]: 19 | ptr.link[ord(ch) - ord('a')] = Node() 20 | if len(s) < ptr.min_len: 21 | ptr.idx = i 22 | ptr.min_len = len(s) 23 | ptr = ptr.link[ord(ch) - ord('a')] 24 | 25 | if ptr.end == -1: 26 | ptr.end = i 27 | 28 | def find(self, s): 29 | s = s[::-1] 30 | ptr = self.root 31 | for ch in s: 32 | if not ptr.link[ord(ch) - ord('a')]: 33 | if ptr.end != -1: 34 | return ptr.end 35 | return ptr.idx 36 | ptr = ptr.link[ord(ch) - ord('a')] 37 | 38 | if ptr.end != -1: 39 | return ptr.end 40 | 41 | return ptr.idx 42 | 43 | class Solution: 44 | def stringIndices(self, wordsContainer, wordsQuery): 45 | t = Trie() 46 | for i in range(len(wordsContainer)): 47 | t.insert(wordsContainer[i], i) 48 | 49 | ans = [0] * len(wordsQuery) 50 | for i in range(len(ans)): 51 | ans[i] = t.find(wordsQuery[i]) 52 | 53 | return ans 54 | 55 | solution = Solution() 56 | 57 | wordsContainer = ["apple", "banana", "app", "application", "bat", "ball"] 58 | 59 | wordsQuery = ["app", "b", "ban", "apples"] 60 | 61 | result = solution.stringIndices(wordsContainer, wordsQuery) 62 | 63 | print("Indices of words in wordsContainer matching the prefixes in wordsQuery:") 64 | for i in range(len(wordsQuery)): 65 | print(f"Query: {wordsQuery[i]}, Index: {result[i]}") -------------------------------------------------------------------------------- /Python/longest_palindromic_substring.py: -------------------------------------------------------------------------------- 1 | # Longest Palindromic Substring 2 | 3 | class Solution(object): 4 | def longestPalindrome(self, s): 5 | n = len(s) 6 | if n < 2: 7 | return s 8 | 9 | start = 0 10 | max_len = 1 11 | 12 | is_palindrome = [[False] * n for _ in range(n)] 13 | 14 | for i in range(n): 15 | is_palindrome[i][i] = True 16 | 17 | for i in range(n - 1): 18 | if s[i] == s[i + 1]: 19 | is_palindrome[i][i + 1] = True 20 | start = i 21 | max_len = 2 22 | 23 | for length in range(3, n + 1): 24 | for i in range(n - length + 1): 25 | j = i + length - 1 26 | if s[i] == s[j] and is_palindrome[i + 1][j - 1]: 27 | is_palindrome[i][j] = True 28 | start = i 29 | max_len = length 30 | 31 | return s[start:start + max_len] 32 | 33 | solution = Solution() 34 | print(solution.longestPalindrome("babad")) -------------------------------------------------------------------------------- /Python/majority_element.py: -------------------------------------------------------------------------------- 1 | # Majority Element 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def majorityElement(self, nums): 7 | counts = Counter(nums) 8 | return max(counts.keys(), key=counts.get) 9 | 10 | solution = Solution() 11 | print(solution.majorityElement([3,2,3])) -------------------------------------------------------------------------------- /Python/make_array_zero_by_subtracting_equal_amounts.py: -------------------------------------------------------------------------------- 1 | # Make Array Zero by Subtracting Equal Amounts 2 | 3 | class Solution(object): 4 | def minimumOperations(self, nums): 5 | return len(set(nums) - {0}) 6 | 7 | solution = Solution() 8 | print(solution.minimumOperations([59, 5, 51, 97, 40, 56, 24, 79, 57, 29, 15, 25, 14, 5, 36, 96, 21, 83, 17, 22, 11, 49, 84, 32, 62, 44, 1, 64, 69, 15, 78, 51, 96, 47, 25, 68, 82, 70, 80, 99, 6, 78, 38, 64, 95, 47, 24, 99, 50, 39, 40, 37, 66, 80, 56, 49, 52, 94, 58, 17, 48, 98, 65, 27, 87, 82, 47, 95, 67, 84, 44, 42, 96, 5, 50, 15, 34, 92, 34, 59, 18, 28, 4, 39, 77, 51, 86, 1, 90, 19, 25, 96, 100, 62, 4, 79, 55, 93, 81, 60])) -------------------------------------------------------------------------------- /Python/matrix_diagonal_sum.py: -------------------------------------------------------------------------------- 1 | # Matrix Diagonal Sum 2 | 3 | class Solution(object): 4 | def diagonalSum(self, mat): 5 | count = 0 6 | n = len(mat) 7 | for i in range(n): 8 | count += mat[i][i] + mat[i][-(i+1)] 9 | if n % 2 == 0: 10 | return count 11 | return count - mat[n // 2][n // 2] 12 | 13 | test = Solution() 14 | print(test.diagonalSum([[1,2,3], 15 | [4,5,6], 16 | [7,8,9]])) -------------------------------------------------------------------------------- /Python/maximum_69_number.py: -------------------------------------------------------------------------------- 1 | # Maximum 69 Number 2 | 3 | class Solution(object): 4 | def maximum69Number (self, num): 5 | k, i = 0, 1 6 | 7 | while i < num: 8 | if num // i % 10 == 6: 9 | k = i 10 | i *= 10 11 | 12 | return num + 3 * k 13 | 14 | solution = Solution() 15 | print(solution.maximum69Number(9669)) -------------------------------------------------------------------------------- /Python/maximum_depth_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | # Maximum Depth of Binary Tree 2 | 3 | class TreeNode: 4 | def __init__(self, value): 5 | self.val = value 6 | self.left = None 7 | self.right = None 8 | 9 | class Solution: 10 | def maxDepth(self, root): 11 | if not root: 12 | return 0 13 | else: 14 | left_depth = self.maxDepth(root.left) 15 | right_depth = self.maxDepth(root.right) 16 | return max(left_depth, right_depth) + 1 17 | 18 | root = TreeNode(3) 19 | root.left = TreeNode(9) 20 | root.right = TreeNode(20) 21 | root.right.left = TreeNode(15) 22 | root.right.right = TreeNode(7) 23 | 24 | solution = Solution() 25 | 26 | print(solution.maxDepth(root)) -------------------------------------------------------------------------------- /Python/maximum_length_substring_with_two_occurrences.py: -------------------------------------------------------------------------------- 1 | # Maximum Length Substring With Two Occurrences 2 | 3 | class Solution: 4 | def maximumLengthSubstring(self, s: str) -> int: 5 | mpp = {} 6 | l = 0 7 | max_len = 0 8 | 9 | for r in range(len(s)): 10 | if s[r] in mpp: 11 | mpp[s[r]] += 1 12 | while mpp[s[r]] > 2: 13 | mpp[s[l]] -= 1 14 | if mpp[s[l]] == 0: 15 | del mpp[s[l]] 16 | l += 1 17 | else: 18 | mpp[s[r]] = 1 19 | 20 | max_len = max(max_len, r - l + 1) 21 | 22 | return max_len 23 | 24 | solution = Solution() 25 | print(solution.maximumLengthSubstring("bcbbbcba")) -------------------------------------------------------------------------------- /Python/maximum_number_of_balls_in_a_box.py: -------------------------------------------------------------------------------- 1 | # Maximum Number of Balls in a Box 2 | 3 | class Solution(object): 4 | def countBalls(self, lowLimit, highLimit): 5 | box_counts = {} 6 | 7 | for num in range(lowLimit, highLimit + 1): 8 | box_number = sum(int(digit) for digit in str(num)) 9 | box_counts[box_number] = box_counts.get(box_number, 0) + 1 10 | 11 | max_balls = max(box_counts.values()) 12 | 13 | return max_balls 14 | 15 | solution = Solution() 16 | print(solution.countBalls(1, 10)) -------------------------------------------------------------------------------- /Python/maximum_number_of_pairs_in_array.py: -------------------------------------------------------------------------------- 1 | # Maximum Number of Pairs in Array 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def numberOfPairs(self, nums): 7 | nums_counts = Counter(nums) 8 | leftover_count = 0 9 | formed_count = 0 10 | 11 | for count in nums_counts.values(): 12 | leftover_count += count % 2 13 | formed_count += count // 2 14 | 15 | return [formed_count, leftover_count] 16 | 17 | solution = Solution() 18 | print(solution.numberOfPairs([1,3,2,1,3,2,2])) -------------------------------------------------------------------------------- /Python/maximum_number_of_words_found_in_sentences.py: -------------------------------------------------------------------------------- 1 | # Maximum Number of Words Found in Sentences 2 | 3 | class Solution(object): 4 | def mostWordsFound(self, sentences): 5 | return max([sentence.count(' ') for sentence in sentences]) + 1 6 | 7 | test = Solution() 8 | print(test.mostWordsFound(["alice and bob love leetcode", "i think so too", "this is great thanks very much"])) -------------------------------------------------------------------------------- /Python/maximum_number_of_words_you_can_type.py: -------------------------------------------------------------------------------- 1 | # Maximum Number of Words You Can Type 2 | 3 | class Solution(object): 4 | def canBeTypedWords(self, text, brokenLetters): 5 | broken_set = set(brokenLetters) 6 | words = text.split() 7 | fully_typed_count = 0 8 | 9 | for word in words: 10 | if any(letter in broken_set for letter in word): 11 | continue 12 | fully_typed_count += 1 13 | 14 | return fully_typed_count 15 | 16 | solution = Solution() 17 | print(solution.canBeTypedWords("hello world", "ad")) -------------------------------------------------------------------------------- /Python/maximum_odd_binary_number.py: -------------------------------------------------------------------------------- 1 | # Maximum Odd Binary Number 2 | 3 | class Solution(object): 4 | def maximumOddBinaryNumber(self, s): 5 | ones_count = s.count("1") 6 | zeros_count = len(s) - ones_count 7 | 8 | return "1" * (ones_count - 1) + "0" * zeros_count + "1" 9 | 10 | solution = Solution() 11 | print(solution.maximumOddBinaryNumber("010")) -------------------------------------------------------------------------------- /Python/maximum_product_difference_between_two_pairs.py: -------------------------------------------------------------------------------- 1 | # Maximum Product Difference Between Two Pairs 2 | 3 | class Solution(object): 4 | def maxProductDifference(self, nums): 5 | nums.sort() 6 | return (nums[-1] * nums[-2]) - (nums[0] * nums[1]) 7 | 8 | solution = Solution() 9 | print(solution.maxProductDifference([5,6,2,7,4])) -------------------------------------------------------------------------------- /Python/maximum_product_of_two_elements_in_an_array.py: -------------------------------------------------------------------------------- 1 | # Maximum Product of Two Elements in an Array 2 | 3 | class Solution(object): 4 | def maxProduct(self, nums): 5 | count = 0 6 | n = len(nums) 7 | for i in range(n): 8 | for j in range(i+1, n): 9 | count = max(count, (nums[i]-1) * (nums[j]-1)) 10 | return count 11 | 12 | solution = Solution() 13 | print(solution.maxProduct([3,4,5,2])) -------------------------------------------------------------------------------- /Python/maximum_strong_pair_xor_i.py: -------------------------------------------------------------------------------- 1 | # Maximum Strong Pair XOR I 2 | 3 | class Solution(object): 4 | def maximumStrongPairXor(self, nums): 5 | xor = 0 6 | n = len(nums) 7 | for i in range(n): 8 | for j in range(i, n): 9 | x = nums[i] 10 | y = nums[j] 11 | if abs(x - y) <= min(x, y) and x ^ y > xor: 12 | xor = x ^ y 13 | return xor 14 | 15 | solution = Solution() 16 | print(solution.maximumStrongPairXor([1,2,3,4,5])) -------------------------------------------------------------------------------- /Python/maximum_sum_with_exactly_k_elements_.py: -------------------------------------------------------------------------------- 1 | # Maximum Sum With Exactly K Elements 2 | 3 | class Solution(object): 4 | def maximizeSum(self, nums, k): 5 | nums.sort() 6 | count = 0 7 | for i in range(k): 8 | count += nums[-1] 9 | nums[-1] = nums[-1] + 1 10 | return count 11 | 12 | solution = Solution() 13 | print(solution.maximizeSum([1,2,3,4,5], 3)) -------------------------------------------------------------------------------- /Python/maximum_units_on_a_truck.py: -------------------------------------------------------------------------------- 1 | # Maximum Units on a Truck 2 | 3 | class Solution(object): 4 | def maximumUnits(self, boxTypes, truckSize): 5 | boxTypes.sort(key=lambda x: x[1], reverse=True) 6 | 7 | total_units = 0 8 | boxes_added = 0 9 | 10 | for boxes, units_per_box in boxTypes: 11 | if boxes_added + boxes <= truckSize: 12 | total_units += boxes * units_per_box 13 | boxes_added += boxes 14 | else: 15 | remaining_space = truckSize - boxes_added 16 | total_units += remaining_space * units_per_box 17 | break 18 | 19 | return total_units 20 | 21 | solution = Solution() 22 | print(solution.maximumUnits([[1,3],[2,2],[3,1]], 4)) -------------------------------------------------------------------------------- /Python/merge_in_between_linked_lists.py: -------------------------------------------------------------------------------- 1 | # Merge In Between Linked Lists 2 | 3 | class ListNode: 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | class Solution(object): 9 | def mergeInBetween(self, list1, a, b, list2): 10 | ptr = list1 11 | for _ in range(a - 1): 12 | ptr = ptr.next 13 | 14 | qtr = ptr.next 15 | for _ in range(b - a + 1): 16 | qtr = qtr.next 17 | 18 | ptr.next = list2 19 | while list2.next: 20 | list2 = list2.next 21 | list2.next = qtr 22 | 23 | return list1 24 | 25 | def print_linked_list(head): 26 | current = head 27 | while current: 28 | print(current.val, end=" -> ") 29 | current = current.next 30 | print("None") 31 | 32 | list1 = ListNode(0) 33 | current = list1 34 | for i in range(1, 6): 35 | current.next = ListNode(i) 36 | current = current.next 37 | 38 | list2 = ListNode(10) 39 | current = list2 40 | for i in range(11, 13): 41 | current.next = ListNode(i) 42 | current = current.next 43 | 44 | print("Original list1:") 45 | print_linked_list(list1) 46 | print("Original list2:") 47 | print_linked_list(list2) 48 | 49 | sol = Solution() 50 | merged_list = sol.mergeInBetween(list1, 2, 4, list2) 51 | 52 | print("Merged list:") 53 | print_linked_list(merged_list) -------------------------------------------------------------------------------- /Python/merge_similar_items.py: -------------------------------------------------------------------------------- 1 | # Merge Similar Items 2 | 3 | class Solution(object): 4 | def mergeSimilarItems(self, items1, items2): 5 | value_weights = {} 6 | items = items1 + items2 7 | for item in items: 8 | value = item[0] 9 | weight = item[1] 10 | if value not in value_weights: 11 | value_weights[value] = 0 12 | value_weights[value] += weight 13 | 14 | sorted_values = sorted(value_weights.items()) 15 | ret = [[value, weight] for value, weight in sorted_values] 16 | 17 | return ret 18 | 19 | solution = Solution() 20 | print(solution.mergeSimilarItems([[1,1],[4,5],[3,8]], [[3,1],[1,5]])) -------------------------------------------------------------------------------- /Python/merge_sorted_array.py: -------------------------------------------------------------------------------- 1 | # Merge Sorted Array 2 | 3 | class Solution(object): 4 | def merge(self, nums1, m, nums2, n): 5 | i = m - 1 6 | j = n - 1 7 | k = m + n - 1 8 | 9 | while j >= 0: 10 | if i >= 0 and nums1[i] > nums2[j]: 11 | nums1[k] = nums1[i] 12 | i -= 1 13 | else: 14 | nums1[k] = nums2[j] 15 | j -= 1 16 | k -= 1 17 | 18 | solution = Solution() 19 | nums1 = [1, 2, 3, 0, 0, 0] 20 | m = 3 21 | nums2 = [2, 5, 6] 22 | n = 3 23 | solution.merge(nums1, m, nums2, n) 24 | print(nums1) -------------------------------------------------------------------------------- /Python/merge_two_2d_arrays_by_summing_values.py: -------------------------------------------------------------------------------- 1 | # Merge Two 2D Arrays by Summing Values 2 | 3 | class Solution(object): 4 | def mergeArrays(self, nums1, nums2): 5 | dic = {} 6 | 7 | for nums in [nums1, nums2]: 8 | for sublist in nums: 9 | id, val = sublist[0], sublist[1] 10 | dic[id] = dic.get(id, 0) + val 11 | 12 | return sorted(dic.items(), key=lambda x: x[0]) 13 | 14 | solution = Solution() 15 | print(solution.mergeArrays([[1,2],[2,3],[4,5]], [[1,4],[3,2],[4,1]])) -------------------------------------------------------------------------------- /Python/merge_two_sorted_lists.py: -------------------------------------------------------------------------------- 1 | # Merge Two Sorted Lists 2 | 3 | class ListNode: 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | class Solution(object): 9 | def mergeTwoLists(self, list1, list2): 10 | if not list1: return list2 11 | if not list2: return list1 12 | if list1.val < list2.val: 13 | list1.next = self.mergeTwoLists(list1.next, list2) 14 | return list1 15 | else: 16 | list2.next = self.mergeTwoLists(list1, list2.next) 17 | return list2 18 | 19 | list1 = ListNode(1) 20 | list1.next = ListNode(2) 21 | list1.next.next = ListNode(4) 22 | 23 | list2 = ListNode(1) 24 | list2.next = ListNode(3) 25 | list2.next.next = ListNode(4) 26 | 27 | solution = Solution() 28 | 29 | merged_list = solution.mergeTwoLists(list1, list2) 30 | 31 | while merged_list: 32 | print(merged_list.val, end=" ") 33 | merged_list = merged_list.next -------------------------------------------------------------------------------- /Python/middle_of_the_linked_list.py: -------------------------------------------------------------------------------- 1 | # Middle of the Linked List 2 | 3 | class Solution(object): 4 | def middleNode(self, head): 5 | slow_pointer = head 6 | fast_pointer = head 7 | 8 | while fast_pointer is not None and fast_pointer.next is not None: 9 | slow_pointer = slow_pointer.next 10 | fast_pointer = fast_pointer.next.next 11 | 12 | return slow_pointer 13 | 14 | solution = Solution() 15 | print(solution.middleNode([1,2,3,4,5])) -------------------------------------------------------------------------------- /Python/minimize_string_length.py: -------------------------------------------------------------------------------- 1 | # Minimize String Length 2 | 3 | class Solution(object): 4 | def minimizedStringLength(self, s): 5 | return len(set(s)) 6 | 7 | solution = Solution() 8 | print(solution.minimizedStringLength("aaabc")) -------------------------------------------------------------------------------- /Python/minimum_common_value.py: -------------------------------------------------------------------------------- 1 | # Minimum Common Value 2 | 3 | class Solution(object): 4 | def getCommon(self, nums1, nums2): 5 | i = 0 6 | j = 0 7 | common = float('inf') 8 | 9 | while i < len(nums1) and j < len(nums2): 10 | if nums1[i] == nums2[j]: 11 | common = nums1[i] 12 | break 13 | elif nums1[i] < nums2[j]: 14 | i += 1 15 | else: 16 | j += 1 17 | 18 | return common if common != float('inf') else -1 19 | 20 | solution = Solution() 21 | print(solution.getCommon([1,2,3], [2,4])) -------------------------------------------------------------------------------- /Python/minimum_deletions_to_make_string_k-special.py: -------------------------------------------------------------------------------- 1 | # Minimum Deletions to Make String K-Special 2 | 3 | class Solution(object): 4 | def minimumDeletions(self, word, k): 5 | hash_map = {} 6 | 7 | for i in word : 8 | hash_map[i] = hash_map.get(i , 0)+1 9 | 10 | l = sorted(list(hash_map.values()) , reverse = True) 11 | min_deletions = float("inf") 12 | 13 | for i in range(len(l)): 14 | t = l[i] 15 | deletions = 0 16 | for j in range(len(l)): 17 | if l[j] > t+k : 18 | deletions += (l[j] - (t+k)) 19 | elif l[j] < t : 20 | deletions += l[j] 21 | min_deletions = min(min_deletions , deletions) 22 | 23 | return min_deletions 24 | 25 | solution = Solution() 26 | print(solution.minimumDeletions()) -------------------------------------------------------------------------------- /Python/minimum_length_of_string_after_deleting_similar_ends.py: -------------------------------------------------------------------------------- 1 | # Minimum Length of String After Deleting Similar Ends 2 | 3 | class Solution(object): 4 | def minimumLength(self, s): 5 | left, right = 0, len(s) - 1 6 | 7 | while left < right and s[left] == s[right]: 8 | char = s[left] 9 | while left <= right and s[left] == char: 10 | left += 1 11 | while right >= left and s[right] == char: 12 | right -= 1 13 | 14 | return right - left + 1 15 | 16 | solution = Solution() 17 | print(solution.minimumLength("ca")) -------------------------------------------------------------------------------- /Python/minimum_number_game.py: -------------------------------------------------------------------------------- 1 | # Minimum Number Game 2 | 3 | class Solution(object): 4 | def numberGame(self, nums): 5 | nums.sort() 6 | for i in range(0, len(nums), 2): 7 | num = nums[i] 8 | nums[i] = nums[i+1] 9 | nums[i+1] = num 10 | return nums 11 | 12 | test = Solution() 13 | print(test.numberGame([5,4,2,3])) -------------------------------------------------------------------------------- /Python/minimum_number_of_moves_to_seat_everyone.py: -------------------------------------------------------------------------------- 1 | # Minimum Number of Moves to Seat Everyone 2 | 3 | class Solution(object): 4 | def minMovesToSeat(self, seats, students): 5 | seats.sort() 6 | students.sort() 7 | count = 0 8 | for seat, student, in zip(seats, students): 9 | count += abs(seat - student) 10 | return count 11 | 12 | solution = Solution() 13 | print(solution.minMovesToSeat([3,1,5], [2,7,4])) -------------------------------------------------------------------------------- /Python/minimum_operations_to_exceed_threshold_value_i.py: -------------------------------------------------------------------------------- 1 | # Minimum Operations to Exceed Threshold Value I 2 | 3 | class Solution(object): 4 | def minOperations(self, nums, k): 5 | return sum(n < k for n in nums) 6 | 7 | solution = Solution() 8 | print(solution.build_array()) -------------------------------------------------------------------------------- /Python/minimum_operations_to_make_the_array_increasing.py: -------------------------------------------------------------------------------- 1 | # Minimum Operations to Make the Array Increasing 2 | 3 | class Solution(object): 4 | def minOperations(self, nums): 5 | operations = 0 6 | prev = nums[0] 7 | 8 | for i in range(1, len(nums)): 9 | if nums[i] <= prev: 10 | operations += prev - nums[i] + 1 11 | prev += 1 12 | else: 13 | prev = nums[i] 14 | 15 | return operations 16 | 17 | solution = Solution() 18 | print(solution.minOperations([1,1,1])) -------------------------------------------------------------------------------- /Python/minimum_sum_of_four_digit_number_after_splitting_digits.py: -------------------------------------------------------------------------------- 1 | # Minimum Sum of Four Digit Number After Splitting Digits 2 | 3 | class Solution(object): 4 | def minimumSum(self, num): 5 | digits = [int(d) for d in str(num)] 6 | 7 | digits.sort() 8 | 9 | part1 = 0 10 | part2 = 0 11 | 12 | for i in range(len(digits)): 13 | if i == 0 and digits[i] == 0: 14 | continue 15 | 16 | if i % 2 == 0: 17 | part1 = part1 * 10 + digits[i] 18 | else: 19 | part2 = part2 * 10 + digits[i] 20 | 21 | return part1 + part2 22 | 23 | solution = Solution() 24 | print(solution.minimumSum(2932)) -------------------------------------------------------------------------------- /Python/minimum_time_visiting_all_points.py: -------------------------------------------------------------------------------- 1 | # Minimum Time Visiting All Points 2 | 3 | class Solution(object): 4 | def to_time(self, from_point, to_point): 5 | x_diff = abs(from_point[0] - to_point[0]) 6 | y_diff = abs(from_point[1] - to_point[1]) 7 | 8 | return max(x_diff, y_diff) 9 | 10 | def minTimeToVisitAllPoints(self, points): 11 | time = 0 12 | 13 | for i in range(1, len(points)): 14 | time += self.to_time(points[i - 1], points[i]) 15 | 16 | return time 17 | 18 | solution = Solution() 19 | print(solution.minTimeToVisitAllPoints([[1,1],[3,4],[-1,0]])) -------------------------------------------------------------------------------- /Python/modify_the_matrix.py: -------------------------------------------------------------------------------- 1 | # Modify the Matrix 2 | 3 | class Solution(object): 4 | def modifiedMatrix(self, matrix): 5 | m = len(matrix) 6 | n = len(matrix[0]) 7 | 8 | max_values = [max(matrix[i][j] for i in range(m)) for j in range(n)] 9 | 10 | for i in range(m): 11 | for j in range(n): 12 | if matrix[i][j] == -1: 13 | matrix[i][j] = max_values[j] 14 | 15 | return matrix 16 | 17 | solution = Solution() 18 | print(solution.modifiedMatrix([[1,2,-1],[4,-1,6],[7,8,9]])) -------------------------------------------------------------------------------- /Python/most_common_word.py: -------------------------------------------------------------------------------- 1 | # Most Common Word 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def mostCommonWord(self, paragraph, banned): 7 | symbols = "!?',;." 8 | for s in symbols: 9 | paragraph = paragraph.replace(s," ") 10 | 11 | paraList = paragraph.lower().split() 12 | wordCounter = Counter(paraList) 13 | 14 | for banned_word in banned: 15 | del wordCounter[banned_word] 16 | 17 | most_frequent = wordCounter.most_common(1) 18 | 19 | return most_frequent[0][0] 20 | 21 | solution = Solution() 22 | print(solution.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"])) -------------------------------------------------------------------------------- /Python/most_frequent_ids.py: -------------------------------------------------------------------------------- 1 | # Most Frequent IDs 2 | 3 | class Solution(object): 4 | def build_array(self, nums): 5 | # Your solution here 6 | pass 7 | 8 | solution = Solution() 9 | print(solution.build_array()) -------------------------------------------------------------------------------- /Python/move_zeroes.py: -------------------------------------------------------------------------------- 1 | # Move Zeroes 2 | 3 | class Solution(object): 4 | def moveZeroes(self, nums): 5 | insert_pos = 0 6 | 7 | for num in nums: 8 | if num != 0: 9 | nums[insert_pos] = num 10 | insert_pos += 1 11 | 12 | while insert_pos < len(nums): 13 | nums[insert_pos] = 0 14 | insert_pos += 1 15 | 16 | solution = Solution() 17 | print(solution.moveZeroes([0,1,0,3,12])) -------------------------------------------------------------------------------- /Python/n-queens.py: -------------------------------------------------------------------------------- 1 | # N-Queens 2 | 3 | class Solution(object): 4 | def solveNQueens(self, n): 5 | def is_safe(board, row, col): 6 | for i in range(row): 7 | if board[i][col] == 'Q': 8 | return False 9 | 10 | for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)): 11 | if board[i][j] == 'Q': 12 | return False 13 | 14 | for i, j in zip(range(row-1, -1, -1), range(col+1, n)): 15 | if board[i][j] == 'Q': 16 | return False 17 | 18 | return True 19 | 20 | def backtrack(board, row): 21 | if row == n: 22 | solutions.append(["".join(row) for row in board]) 23 | return 24 | 25 | for col in range(n): 26 | if is_safe(board, row, col): 27 | board[row][col] = 'Q' 28 | backtrack(board, row + 1) 29 | board[row][col] = '.' 30 | 31 | solutions = [] 32 | board = [['.' for _ in range(n)] for _ in range(n)] 33 | backtrack(board, 0) 34 | return solutions 35 | 36 | solution = Solution() 37 | print(solution.solveNQueens(4)) -------------------------------------------------------------------------------- /Python/n-repeated_element_in_size_2n_array.py: -------------------------------------------------------------------------------- 1 | # N-Repeated Element in Size 2N Array 2 | 3 | class Solution(object): 4 | def repeatedNTimes(self, nums): 5 | count = {} 6 | n = len(nums) // 2 7 | 8 | for num in nums: 9 | count[num] = count.get(num, 0) + 1 10 | if count[num] == n: 11 | return num 12 | 13 | solution = Solution() 14 | print(solution.repeatedNTimes([1,2,3,3])) -------------------------------------------------------------------------------- /Python/neither_minimum_nor_maximum.py: -------------------------------------------------------------------------------- 1 | # Neither Minimum nor Maximum 2 | 3 | class Solution(object): 4 | def findNonMinOrMax(self, nums): 5 | if len(nums) < 3: 6 | return -1 7 | 8 | sorted_nums = sorted(nums) 9 | return sorted_nums[1] 10 | 11 | solution = Solution() 12 | print(solution.findNonMinOrMax([3,2,1,4])) -------------------------------------------------------------------------------- /Python/next_greater_element_i.py: -------------------------------------------------------------------------------- 1 | # Next Greater Element I 2 | 3 | class Solution(object): 4 | def nextGreaterElement(self, nums1, nums2): 5 | stack = [] 6 | next_greater = {} 7 | 8 | for num in reversed(nums2): 9 | while stack and stack[-1] <= num: 10 | stack.pop() 11 | 12 | if stack: 13 | next_greater[num] = stack[-1] 14 | else: 15 | next_greater[num] = -1 16 | 17 | stack.append(num) 18 | 19 | ans = [next_greater[num] for num in nums1] 20 | return ans 21 | 22 | solution = Solution() 23 | print(solution.nextGreaterElement([4,1,2], [1,3,4,2])) -------------------------------------------------------------------------------- /Python/number_of_arithmetic_triplets.py: -------------------------------------------------------------------------------- 1 | # Number of Arithmetic Triplets 2 | 3 | class Solution(object): 4 | def arithmeticTriplets(self, nums, diff): 5 | count = 0 6 | n = len(nums) 7 | for i in range(n): 8 | for j in range(i+1, n): 9 | for k in range(j+1, n): 10 | if nums[j] - nums[i] == diff and nums[k] - nums[j] == diff: 11 | count += 1 12 | return count 13 | 14 | test = Solution() 15 | print(test.arithmeticTriplets([0,1,4,6,7,10], 3)) -------------------------------------------------------------------------------- /Python/number_of_employees_who_met_the_target.py: -------------------------------------------------------------------------------- 1 | # Number of Employees Who Met the Target 2 | 3 | class Solution(object): 4 | def numberOfEmployeesWhoMetTarget(self, hours, target): 5 | return len([None for hour in hours if hour >= target]) 6 | 7 | test = Solution() 8 | print(test.numberOfEmployeesWhoMetTarget([0,1,2,3,4], 2)) -------------------------------------------------------------------------------- /Python/number_of_good_pairs.py: -------------------------------------------------------------------------------- 1 | # Number of Good Pairs 2 | 3 | class Solution(object): 4 | def numIdenticalPairs(self, nums): 5 | n = len(nums) 6 | count = 0 7 | for i in range(n): 8 | for j in range(i+1, n): 9 | if nums[i] == nums[j]: 10 | count += 1 11 | return count 12 | 13 | test = Solution() 14 | print(test.numIdenticalPairs([1,2,3,1,1,3])) -------------------------------------------------------------------------------- /Python/number_of_rectangles_that_can_form_the_largest_square.py: -------------------------------------------------------------------------------- 1 | # Number Of Rectangles That Can Form The Largest Square 2 | 3 | class Solution(object): 4 | def countGoodRectangles(self, rectangles): 5 | max_side_length = 0 6 | count = 0 7 | 8 | for rectangle in rectangles: 9 | side_length = min(rectangle) 10 | max_side_length = max(max_side_length, side_length) 11 | 12 | for rectangle in rectangles: 13 | if min(rectangle) >= max_side_length: 14 | count += 1 15 | 16 | return count 17 | 18 | solution = Solution() 19 | print(solution.countGoodRectangles([[5,8],[3,9],[5,12],[16,5]])) -------------------------------------------------------------------------------- /Python/number_of_senior_citizens.py: -------------------------------------------------------------------------------- 1 | # Number of Senior Citizens 2 | 3 | class Solution(object): 4 | def countSeniors(self, details): 5 | count = 0 6 | for detail in details: 7 | age = int(detail[11:13]) 8 | if age > 60: 9 | count += 1 10 | return count 11 | 12 | solution = Solution() 13 | print(solution.countSeniors(["7868190130M7522","5303914400F9211","9273338290F4010"])) -------------------------------------------------------------------------------- /Python/number_of_students_doing_homework_at_a_given_time.py: -------------------------------------------------------------------------------- 1 | # Number of Students Doing Homework at a Given Time 2 | 3 | class Solution(object): 4 | def busyStudent(self, startTime, endTime, queryTime): 5 | count = 0 6 | for start, end, in zip(startTime, endTime): 7 | if start <= queryTime and end >= queryTime: 8 | count += 1 9 | return count 10 | 11 | solution = Solution() 12 | print(solution.busyStudent([1,2,3], [3,2,7], 4)) -------------------------------------------------------------------------------- /Python/number_of_students_unable_to_eat_lunch.py: -------------------------------------------------------------------------------- 1 | # Number of Students Unable to Eat Lunch 2 | 3 | class Solution(object): 4 | def countStudents(self, students, sandwiches): 5 | temp = 0 6 | while True: 7 | if not students or temp == len(students): 8 | break 9 | if students[0] == sandwiches[0]: 10 | del students[0] 11 | del sandwiches[0] 12 | temp = 0 13 | else: 14 | temp += 1 15 | students.append(students[0]) 16 | del students[0] 17 | 18 | return len(students) 19 | 20 | solution = Solution() 21 | print(solution.countStudents([1,1,1,0,0,1], [1,0,0,0,1,1])) -------------------------------------------------------------------------------- /Python/number_of_unequal_triplets_in_array.py: -------------------------------------------------------------------------------- 1 | # Number of Unequal Triplets in Array 2 | 3 | class Solution(object): 4 | def unequalTriplets(self, nums): 5 | count = 0 6 | n = len(nums) 7 | 8 | for i in range(n): 9 | for j in range(i + 1, n): 10 | for k in range(j + 1, n): 11 | if nums[i] != nums[j] and nums[j] != nums[k] and nums[i] != nums[k]: 12 | count += 1 13 | 14 | return count 15 | 16 | solution = Solution() 17 | print(solution.unequalTriplets([4,4,2,4,3])) -------------------------------------------------------------------------------- /Python/palindrome_number.py: -------------------------------------------------------------------------------- 1 | # Palindrome Number 2 | 3 | class Solution(object): 4 | def isPalindrome(self, x): 5 | return str(x) == str(x)[::-1] 6 | 7 | test = Solution() 8 | print(test.isPalindrome(121)) -------------------------------------------------------------------------------- /Python/pascals_triangle.py: -------------------------------------------------------------------------------- 1 | # Pascal's Triangle 2 | 3 | class Solution(object): 4 | def generate(self, numRows): 5 | triangle = [] 6 | for i in range(numRows): 7 | row = [1] 8 | for j in range(1, i): 9 | row.append(triangle[i - 1][j - 1] + triangle[i - 1][j]) 10 | if i > 0: 11 | row.append(1) 12 | triangle.append(row) 13 | return triangle 14 | 15 | solution = Solution() 16 | print(solution.generate(5)) -------------------------------------------------------------------------------- /Python/permutations.py: -------------------------------------------------------------------------------- 1 | # Permutations 2 | 3 | class Solution(object): 4 | def permute(self, nums): 5 | def backtrack(start): 6 | if start == len(nums): 7 | permutations.append(nums[:]) 8 | else: 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 | permutations = [] 15 | backtrack(0) 16 | return permutations 17 | 18 | solution = Solution() 19 | print(solution.permute([1,2,3])) -------------------------------------------------------------------------------- /Python/plus_one.py: -------------------------------------------------------------------------------- 1 | # Plus One 2 | 3 | class Solution(object): 4 | def plusOne(self, digits): 5 | total = str(int(int(''.join(map(str, digits)))) + 1) 6 | return [int(num) for num in total] 7 | 8 | solution = Solution() 9 | print(solution.plusOne([1,2,3])) -------------------------------------------------------------------------------- /Python/points_that_intersect_with_cars.py: -------------------------------------------------------------------------------- 1 | # Points That Intersect With Cars 2 | 3 | class Solution(object): 4 | def numberOfPoints(self, nums): 5 | covered_points = set() 6 | 7 | for start, end in nums: 8 | for point in range(start, end + 1): 9 | covered_points.add(point) 10 | 11 | return len(covered_points) 12 | 13 | solution = Solution() 14 | print(solution.numberOfPoints([[3,6],[1,5],[4,7]])) -------------------------------------------------------------------------------- /Python/product_of_array_except_self.py: -------------------------------------------------------------------------------- 1 | # Product of Array Except Self 2 | 3 | class Solution(object): 4 | def productExceptSelf(self, nums): 5 | total_product = 1 6 | for num in nums: 7 | total_product *= num 8 | 9 | result = [] 10 | 11 | for num in nums: 12 | result.append(total_product // num) 13 | 14 | return result 15 | 16 | solution = Solution() 17 | print(solution.productExceptSelf([1,2,3,4])) -------------------------------------------------------------------------------- /Python/ransom_note.py: -------------------------------------------------------------------------------- 1 | # Ransom Note 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def canConstruct(self, ransomNote, magazine): 7 | s1, s2 = Counter(ransomNote), Counter(magazine) 8 | return True if s1 & s2 == s1 else False 9 | 10 | solution = Solution() 11 | print(solution.canConstruct("a", "b")) -------------------------------------------------------------------------------- /Python/remove_duplicates_from_sorted_array.py: -------------------------------------------------------------------------------- 1 | # Remove Duplicates from Sorted Array 2 | 3 | class Solution(object): 4 | def removeDuplicates(self, nums): 5 | k = 1 6 | 7 | for i in range(1, len(nums)): 8 | if nums[i] != nums[i - 1]: 9 | nums[k] = nums[i] 10 | k += 1 11 | 12 | return k 13 | 14 | solution = Solution() 15 | print(solution.removeDuplicates([1,1,2])) -------------------------------------------------------------------------------- /Python/remove_element.py: -------------------------------------------------------------------------------- 1 | # Remove Element 2 | 3 | class Solution(object): 4 | def removeElement(self, nums, val): 5 | left, right = 0, len(nums) - 1 6 | 7 | while left <= right: 8 | if nums[left] == val: 9 | nums[left], nums[right] = nums[right], nums[left] 10 | right -= 1 11 | else: 12 | left += 1 13 | 14 | return left 15 | 16 | solution = Solution() 17 | print(solution.removeElement([3,2,2,3], 3)) 18 | -------------------------------------------------------------------------------- /Python/remove_linked_list_elements.py: -------------------------------------------------------------------------------- 1 | # Remove Linked List Elements 2 | 3 | class LinkedList: 4 | def __init__(self, val : None): 5 | self.val = val 6 | self.next = None 7 | 8 | class Solution(object): 9 | def removeElements(self, head, val): 10 | while head and head.val == val: 11 | head = head.next 12 | 13 | current = head 14 | while current and current.next: 15 | if current.next.val == val: 16 | current.next = current.next.next 17 | else: 18 | current = current.next 19 | 20 | return head 21 | 22 | head = LinkedList(1) 23 | head.next = LinkedList(2) 24 | head.next.next = LinkedList(6) 25 | head.next.next.next = LinkedList(3) 26 | head.next.next.next.next = LinkedList(4) 27 | head.next.next.next.next.next = LinkedList(5) 28 | head.next.next.next.next.next.next = LinkedList(6) 29 | 30 | solution = Solution() 31 | head = solution.removeElements(head, 6) 32 | 33 | while head: 34 | print(head.val, end=" -> ") 35 | head = head.next 36 | 37 | print(None) -------------------------------------------------------------------------------- /Python/remove_nth_node_from_end_of_list.py: -------------------------------------------------------------------------------- 1 | # Remove Nth Node From End of List 2 | 3 | class ListNode(object): 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | class Solution(object): 9 | def removeNthFromEnd(self, head, n): 10 | dummy = ListNode(0) 11 | dummy.next = head 12 | first = dummy 13 | second = dummy 14 | 15 | for _ in range(n + 1): 16 | first = first.next 17 | 18 | while first is not None: 19 | first = first.next 20 | second = second.next 21 | 22 | second.next = second.next.next 23 | 24 | return dummy.next 25 | 26 | 27 | head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) 28 | n = 2 29 | 30 | solution = Solution() 31 | result = solution.removeNthFromEnd(head, n) 32 | 33 | while result: 34 | print(result.val, end=" -> ") 35 | result = result.next 36 | print("None") -------------------------------------------------------------------------------- /Python/remove_palindromic_subsequences.py: -------------------------------------------------------------------------------- 1 | # Remove Palindromic Subsequences 2 | 3 | class Solution(object): 4 | def removePalindromeSub(self, s): 5 | return 1 if s == s[::-1] else 2 6 | 7 | solution = Solution() 8 | print(solution.removePalindromeSub("ababa")) -------------------------------------------------------------------------------- /Python/remove_zero_sum_consecutive_nodes_from_linked_list.py: -------------------------------------------------------------------------------- 1 | # Remove Zero Sum Consecutive Nodes from Linked List 2 | 3 | class ListNode(object): 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | class Solution(object): 9 | def removeZeroSumSublists(self, head): 10 | dummy = ListNode(0) 11 | dummy.next = head 12 | prefix_sum = 0 13 | prefix_sums = {0: dummy} 14 | current = head 15 | 16 | while current: 17 | prefix_sum += current.val 18 | if prefix_sum in prefix_sums: 19 | to_delete = prefix_sums[prefix_sum].next 20 | temp_sum = prefix_sum + to_delete.val 21 | while to_delete != current: 22 | del prefix_sums[temp_sum] 23 | to_delete = to_delete.next 24 | temp_sum += to_delete.val 25 | prefix_sums[prefix_sum].next = current.next 26 | else: 27 | prefix_sums[prefix_sum] = current 28 | current = current.next 29 | 30 | return dummy.next 31 | 32 | solution = Solution() 33 | head = ListNode(1) 34 | head.next = ListNode(2) 35 | head.next.next = ListNode(-3) 36 | head.next.next.next = ListNode(3) 37 | head.next.next.next.next = ListNode(1) 38 | 39 | result = solution.removeZeroSumSublists(head) 40 | 41 | while result: 42 | print(result.val, end=" -> ") 43 | result = result.next -------------------------------------------------------------------------------- /Python/replace_all_digits_with_characters.py: -------------------------------------------------------------------------------- 1 | # Replace All Digits with Characters 2 | 3 | class Solution(object): 4 | def replaceDigits(self, s): 5 | for i in range(1,len(s),2): 6 | s = s[:i] + chr(ord(s[i-1])+int(s[i])) + s[i+1:] 7 | return s 8 | 9 | solution = Solution() 10 | print(solution.replaceDigits("a1c1e1")) -------------------------------------------------------------------------------- /Python/reverse_linked_list.py: -------------------------------------------------------------------------------- 1 | # Reverse Linked List 2 | 3 | class ListNode: 4 | def __init__(self, val=0, next=None): 5 | self.val = val 6 | self.next = next 7 | 8 | class Solution(object): 9 | def reverseList(self, head): 10 | prev_node = None 11 | current_node = head 12 | 13 | while current_node is not None: 14 | next_node = current_node.next 15 | current_node.next = prev_node 16 | prev_node = current_node 17 | current_node = next_node 18 | 19 | return prev_node 20 | 21 | # Create a linked list: 1 -> 2 -> 3 -> 4 -> 5 22 | head = ListNode(1) 23 | head.next = ListNode(2) 24 | head.next.next = ListNode(3) 25 | head.next.next.next = ListNode(4) 26 | head.next.next.next.next = ListNode(5) 27 | 28 | solution = Solution() 29 | reversed_head = solution.reverseList(head) 30 | 31 | while reversed_head is not None: 32 | print(reversed_head.val, end=" ") 33 | reversed_head = reversed_head.next -------------------------------------------------------------------------------- /Python/reverse_words_in_a_string_iii.py: -------------------------------------------------------------------------------- 1 | # Reverse Words in a String III 2 | 3 | class Solution(object): 4 | def reverseWords(self, s): 5 | words = s.split() 6 | reversed_words = [word[::-1] for word in words] 7 | return ' '.join(reversed_words) 8 | 9 | solution = Solution() 10 | print(solution.reverseWords("Let's take LeetCode contest")) -------------------------------------------------------------------------------- /Python/richest_customer_wealth.py: -------------------------------------------------------------------------------- 1 | # Richest Customer Wealth 2 | 3 | class Solution(object): 4 | def maximumWealth(self, accounts): 5 | max_wealth = 0 6 | for account in accounts: 7 | max_wealth = max(max_wealth, sum(account)) 8 | return max_wealth 9 | 10 | test = Solution() 11 | print(test.maximumWealth([[1,2,3],[3,2,1]])) -------------------------------------------------------------------------------- /Python/rings_and_rods.py: -------------------------------------------------------------------------------- 1 | # Rings and Rods 2 | 3 | class Solution(object): 4 | def countPoints(self, rings): 5 | rods = {str(i) : set() for i in range(10)} 6 | 7 | for i in range(0, len(rings), 2): 8 | color, rod = rings[i], rings[i + 1] 9 | rods[rod].add(color) 10 | 11 | count = 0 12 | for rod_colors in rods.values(): 13 | if len(rod_colors) == 3: 14 | count += 1 15 | 16 | return count 17 | 18 | solution = Solution() 19 | print(solution.countPoints("B0B6G0R6R0R6G9")) -------------------------------------------------------------------------------- /Python/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | # Roman to Integer 2 | 3 | class Solution(object): 4 | def romanToInt(self, s): 5 | num = 0 6 | dic = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, 'Z' : 0} 7 | s += 'Z' 8 | for i in range(len(s)-1): 9 | if dic[s[i]] < dic[s[i+1]]: 10 | num -= dic[s[i]] 11 | else: 12 | num += dic[s[i]] 13 | return num 14 | 15 | solution = Solution() 16 | print(solution.romanToInt("MCMXCIV")) -------------------------------------------------------------------------------- /Python/row_with_maximum_ones.py: -------------------------------------------------------------------------------- 1 | # Row With Maximum Ones 2 | 3 | class Solution(object): 4 | def rowAndMaximumOnes(self, mat): 5 | smaller_row_index = 0 6 | max_count = 0 7 | m = len(mat) 8 | 9 | for i in range(m): 10 | count = mat[i].count(1) 11 | if count > max_count: 12 | max_count = count 13 | smaller_row_index = i 14 | 15 | return [smaller_row_index, max_count] 16 | 17 | solution = Solution() 18 | print(solution.rowAndMaximumOnes([[0,1],[1,0]])) -------------------------------------------------------------------------------- /Python/running_sum_of_1d_array.py: -------------------------------------------------------------------------------- 1 | # Running Sum of 1d Array 2 | 3 | class Solution(object): 4 | def runningSum(self, nums): 5 | count = 0 6 | for i in range(len(nums)): 7 | count += nums[i] 8 | nums[i] = count 9 | return nums 10 | 11 | test = Solution() 12 | print(test.runningSum([1,2,3,4])) -------------------------------------------------------------------------------- /Python/same_tree.py: -------------------------------------------------------------------------------- 1 | # Same Tree 2 | 3 | class TreeNode(object): 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution: 10 | def isSameTree(self, p, q): 11 | stack = [(p, q)] 12 | while stack: 13 | node1, node2 = stack.pop() 14 | if not node1 and not node2: 15 | continue 16 | if not node1 or not node2 or node1.val != node2.val: 17 | return False 18 | stack.append((node1.left, node2.left)) 19 | stack.append((node1.right, node2.right)) 20 | return True 21 | 22 | tree1 = TreeNode(1, TreeNode(2), TreeNode(3)) 23 | tree2 = TreeNode(1, TreeNode(2), TreeNode(3)) 24 | 25 | test = Solution() 26 | print(test.isSameTree(tree1, tree2)) -------------------------------------------------------------------------------- /Python/separate_the_digits_in_an_array.py: -------------------------------------------------------------------------------- 1 | # Separate the Digits in an Array 2 | 3 | class Solution(object): 4 | def separateDigits(self, nums): 5 | return [int(digit) for num in nums for digit in str(num)] 6 | 7 | solution = Solution() 8 | print(solution.separateDigits([13,25,83,77])) -------------------------------------------------------------------------------- /Python/shuffle_string.py: -------------------------------------------------------------------------------- 1 | # Shuffle String 2 | 3 | class Solution(object): 4 | def restoreString(self, s, indices): 5 | shuffled = [''] * len(s) 6 | for i, char in zip(indices, s): 7 | shuffled[i] = char 8 | return ''.join(shuffled) 9 | 10 | test = Solution() 11 | print(test.restoreString("codeleet", [4,5,6,7,0,2,1,3])) -------------------------------------------------------------------------------- /Python/shuffle_the_array.py: -------------------------------------------------------------------------------- 1 | # Shuffle the Array 2 | 3 | class Solution(object): 4 | def shuffle(self, nums, n): 5 | result = [] 6 | for i in range(n): 7 | result.extend([nums[i], nums[i + n]]) 8 | return result 9 | 10 | test = Solution() 11 | print(test.shuffle([2,5,1,3,4,7], 3)) -------------------------------------------------------------------------------- /Python/single_number.py: -------------------------------------------------------------------------------- 1 | # Single Number 2 | 3 | class Solution(object): 4 | def singleNumber(self, nums): 5 | result = 0 6 | for num in nums: 7 | result ^= num 8 | return result 9 | 10 | solution = Solution() 11 | print(solution.singleNumber([2,2,1])) -------------------------------------------------------------------------------- /Python/smallest_index_with_equal_value.py: -------------------------------------------------------------------------------- 1 | # Smallest Index With Equal Value 2 | 3 | class Solution(object): 4 | def smallestEqual(self, nums): 5 | for i in range(len(nums)): 6 | if i % 10 == nums[i]: 7 | return i 8 | return -1 9 | 10 | solution = Solution() 11 | print(solution.smallestEqual([0,1,2])) -------------------------------------------------------------------------------- /Python/sort_array_by_parity.py: -------------------------------------------------------------------------------- 1 | # Sort Array By Parity 2 | 3 | class Solution(object): 4 | def sortArrayByParity(self, nums): 5 | left = 0 6 | right = len(nums) - 1 7 | 8 | while left < right: 9 | if nums[left] % 2 == 0: 10 | left += 1 11 | elif nums[right] % 2 != 0: 12 | right -= 1 13 | else: 14 | nums[left], nums[right] = nums[right], nums[left] 15 | left += 1 16 | right -= 1 17 | 18 | return nums 19 | 20 | solution = Solution() 21 | print(solution.sortArrayByParity([3,1,2,4])) -------------------------------------------------------------------------------- /Python/sort_integers_by_the_number_of_1_bits.py: -------------------------------------------------------------------------------- 1 | # Sort Integers by The Number of 1 Bits 2 | 3 | class Solution(object): 4 | def sortByBits(self, arr): 5 | def count_ones(num): 6 | return bin(num).count('1'), num 7 | 8 | arr.sort(key=count_ones) 9 | 10 | return arr 11 | 12 | solution = Solution() 13 | print(solution.sortByBits([0,1,2,3,4,5,6,7,8])) -------------------------------------------------------------------------------- /Python/sort_the_people.py: -------------------------------------------------------------------------------- 1 | # Sort the People 2 | 3 | class Solution(object): 4 | def sortPeople(self, names, heights): 5 | combined_data = list(zip(names, heights)) 6 | 7 | sorted_data = sorted(combined_data, key=lambda x: x[1], reverse=True) 8 | 9 | sorted_names = [name for name, _ in sorted_data] 10 | 11 | return sorted_names 12 | 13 | test = Solution() 14 | print(test.sortPeople(["Mary","John","Emma"], [180,165,170])) -------------------------------------------------------------------------------- /Python/sorting_the_sentence.py: -------------------------------------------------------------------------------- 1 | # Sorting the Sentence 2 | 3 | class Solution(object): 4 | def sortSentence(self, s): 5 | shuffled_words = s.split() 6 | 7 | original_words = [word[:-1] for word in sorted(shuffled_words, key=lambda x: int(x[-1]))] 8 | 9 | reconstructed_sentence = ' '.join(original_words) 10 | 11 | return reconstructed_sentence 12 | 13 | solution = Solution() 14 | print(solution.sortSentence("is2 sentence4 This1 a3")) -------------------------------------------------------------------------------- /Python/split_a_string_in_balanced_strings.py: -------------------------------------------------------------------------------- 1 | # Split a String in Balanced Strings 2 | 3 | class Solution(object): 4 | def balancedStringSplit(self, s): 5 | count_L, count_R, max_splits = 0, 0, 0 6 | 7 | for char in s: 8 | if char == 'L': 9 | count_L += 1 10 | elif char == 'R': 11 | count_R += 1 12 | 13 | if count_L == count_R: 14 | max_splits += 1 15 | 16 | return max_splits 17 | 18 | solution = Solution() 19 | print(solution.balancedStringSplit("RLRRLLRLRL")) -------------------------------------------------------------------------------- /Python/split_strings_by_separator.py: -------------------------------------------------------------------------------- 1 | # Split Strings by Separator 2 | 3 | class Solution(object): 4 | def splitWordsBySeparator(self, words, separator): 5 | return [char for word in words for char in word.split(separator) if char] 6 | 7 | solution = Solution() 8 | print(solution.splitWordsBySeparator(["one.two.three","four.five","six"], '.')) -------------------------------------------------------------------------------- /Python/split_the_array.py: -------------------------------------------------------------------------------- 1 | # Split the Array 2 | 3 | class Solution(object): 4 | def isPossibleToSplit(self, nums): 5 | counts = {} 6 | 7 | for num in nums: 8 | counts[num] = counts.get(num, 0) + 1 9 | if counts[num] >= 3: 10 | return False 11 | 12 | return True 13 | 14 | solution = Solution() 15 | print(solution.isPossibleToSplit([1,1,2,2,3,4])) -------------------------------------------------------------------------------- /Python/squares_of_a_sorted_array.py: -------------------------------------------------------------------------------- 1 | # Squares of a Sorted Array 2 | 3 | class Solution(object): 4 | def sortedSquares(self, nums): 5 | squares = [num * num for num in nums] 6 | squares.sort() 7 | return squares 8 | 9 | solution = Solution() 10 | print(solution.sortedSquares([-4,-1,0,3,10])) -------------------------------------------------------------------------------- /Python/subarray_product_less_than_k.py: -------------------------------------------------------------------------------- 1 | # Subarray Product Less Than K 2 | 3 | class Solution(object): 4 | def numSubarrayProductLessThanK(self, nums, k): 5 | if k <= 1: 6 | return 0 7 | 8 | left, right, product, count = 0, 0, 1, 0 9 | n = len(nums) 10 | 11 | while right < n: 12 | product *= nums[right] 13 | while product >= k: 14 | product //= nums[left] 15 | left += 1 16 | count += 1 + (right - left) 17 | right += 1 18 | 19 | return count 20 | 21 | solution = Solution() 22 | print(solution.numSubarrayProductLessThanK([10,5,2,6], 100)) -------------------------------------------------------------------------------- /Python/subarrays_distinct_element_sum_of_squares_i.py: -------------------------------------------------------------------------------- 1 | # Subarrays Distinct Element Sum of Squares I 2 | 3 | class Solution(object): 4 | def sumCounts(self, nums): 5 | count = 0 6 | n = len(nums) 7 | 8 | for i in range(n): 9 | for j in range(i, n): 10 | count += len(set(nums[i:j+1])) ** 2 11 | 12 | return count 13 | 14 | test = Solution() 15 | print(test.sumCounts([1,2,1])) -------------------------------------------------------------------------------- /Python/subarrays_with_k_different_integers.py: -------------------------------------------------------------------------------- 1 | # Subarrays with K Different Integers 2 | 3 | class Solution: 4 | def subarraysWithKDistinct(self, nums, k): 5 | return self.subarraysWithAtMostKDistinct(nums, k) - self.subarraysWithAtMostKDistinct(nums, k - 1) 6 | 7 | def subarraysWithAtMostKDistinct(self, nums, k): 8 | ans = 0 9 | count = [0] * (len(nums) + 1) 10 | 11 | l = 0 12 | for r in range(len(nums)): 13 | count[nums[r]] += 1 14 | if count[nums[r]] == 1: 15 | k -= 1 16 | while k == -1: 17 | count[nums[l]] -= 1 18 | if count[nums[l]] == 0: 19 | k += 1 20 | l += 1 21 | ans += r - l + 1 22 | return ans 23 | 24 | solution = Solution() 25 | print(solution.subarraysWithAtMostKDistinct([1,2,1,2,3], 2)) -------------------------------------------------------------------------------- /Python/subsets.py: -------------------------------------------------------------------------------- 1 | # Subsets 2 | 3 | class Solution(object): 4 | def subsets(self, nums): 5 | def backtrack(start, curr_subset): 6 | result.append(curr_subset[:]) 7 | 8 | for i in range(start, len(nums)): 9 | curr_subset.append(nums[i]) 10 | backtrack(i + 1, curr_subset) 11 | curr_subset.pop() 12 | 13 | result = [] 14 | backtrack(0, []) 15 | return result 16 | 17 | solution = Solution() 18 | print(solution.subsets([1,2,3])) -------------------------------------------------------------------------------- /Python/sum_of_all_odd_length_subarrays.py: -------------------------------------------------------------------------------- 1 | # Sum of All Odd Length Subarrays 2 | 3 | class Solution(object): 4 | def sumOddLengthSubarrays(self, arr): 5 | total_sum = 0 6 | n = len(arr) 7 | 8 | for i in range(n): 9 | total_sum += ((i + 1) * (n - i) + 1) // 2 * arr[i] 10 | 11 | return total_sum 12 | 13 | test = Solution() 14 | print(test.sumOddLengthSubarrays([1,4,2,5,3])) -------------------------------------------------------------------------------- /Python/sum_of_all_subset_xor_totals.py: -------------------------------------------------------------------------------- 1 | # Sum of All Subset XOR Totals 2 | 3 | class Solution(object): 4 | def subsetXORSum(self, nums): 5 | total_sum = 0 6 | n = len(nums) 7 | 8 | for mask in range(1 << n): 9 | xor_subset = 0 10 | for i in range(n): 11 | if (mask >> i) & 1: 12 | xor_subset ^= nums[i] 13 | total_sum += xor_subset 14 | 15 | return total_sum 16 | 17 | test = Solution() 18 | print(test.subsetXORSum([5,1,6])) -------------------------------------------------------------------------------- /Python/sum_of_squares_of_special_elements_.py: -------------------------------------------------------------------------------- 1 | # Sum of Squares of Special Elements 2 | 3 | class Solution(object): 4 | def sumOfSquares(self, nums): 5 | square_sum = 0 6 | n = len(nums) 7 | for i in range(1, n+1): 8 | if n % i == 0: 9 | square_sum += nums[i-1] ** 2 10 | return square_sum 11 | 12 | solution = Solution() 13 | print(solution.sumOfSquares([1,2,3,4])) -------------------------------------------------------------------------------- /Python/sum_of_unique_elements.py: -------------------------------------------------------------------------------- 1 | # Sum of Unique Elements 2 | 3 | class Solution(object): 4 | def sumOfUnique(self, nums): 5 | count = {} 6 | unique_sum = 0 7 | 8 | for num in nums: 9 | count[num] = count.get(num, 0) + 1 10 | 11 | for num, freq in count.items(): 12 | if freq == 1: 13 | unique_sum += num 14 | 15 | return unique_sum 16 | 17 | solution = Solution() 18 | print(solution.sumOfUnique([1,2,3,2])) -------------------------------------------------------------------------------- /Python/sum_of_values_at_indices_with_k_set_bits.py: -------------------------------------------------------------------------------- 1 | # Sum of Values at Indices With K Set Bits 2 | 3 | class Solution(object): 4 | def sumIndicesWithKSetBits(self, nums, k): 5 | return sum([nums[i] for i in range(len(nums)) if bin(i)[2:].count('1') == k]) 6 | 7 | test = Solution() 8 | print(test.sumIndicesWithKSetBits([5,10,1,5,2], 1)) -------------------------------------------------------------------------------- /Python/symmetric_tree.py: -------------------------------------------------------------------------------- 1 | # Symmetric Tree 2 | 3 | class TreeNode: 4 | def __init__(self, val=0, left=None, right=None): 5 | self.val = val 6 | self.left = left 7 | self.right = right 8 | 9 | class Solution(object): 10 | def isSymmetric(self, root): 11 | queue = [root.left, root.right] 12 | 13 | while queue: 14 | left_node = queue.pop(0) 15 | right_node = queue.pop(0) 16 | 17 | if not left_node and not right_node: 18 | continue 19 | if not left_node or not right_node: 20 | return False 21 | if left_node.val != right_node.val: 22 | return False 23 | 24 | queue.append(left_node.left) 25 | queue.append(right_node.right) 26 | queue.append(left_node.right) 27 | queue.append(right_node.left) 28 | 29 | return True 30 | 31 | root = TreeNode(1) 32 | root.left = TreeNode(2) 33 | root.right = TreeNode(2) 34 | root.left.left = TreeNode(3) 35 | root.left.right = TreeNode(4) 36 | root.right.left = TreeNode(4) 37 | root.right.right = TreeNode(3) 38 | 39 | solution = Solution() 40 | print(solution.isSymmetric(root)) -------------------------------------------------------------------------------- /Python/to_lower_case.py: -------------------------------------------------------------------------------- 1 | # To Lower Case 2 | 3 | class Solution(object): 4 | def toLowerCase(self, s): 5 | return s.lower() 6 | 7 | test = Solution() 8 | print(test.toLowerCase("Hello")) -------------------------------------------------------------------------------- /Python/top_k_frequent_elements.py: -------------------------------------------------------------------------------- 1 | # Top K Frequent Elements 2 | 3 | from collections import Counter 4 | 5 | class Solution(object): 6 | def topKFrequent(self, nums, k): 7 | counter = Counter(nums) 8 | return [num for num, _ in counter.most_common(k)] 9 | 10 | solution = Solution() 11 | print(solution.topKFrequent([1,1,1,2,2,3], 2)) -------------------------------------------------------------------------------- /Python/transpose_matrix.py: -------------------------------------------------------------------------------- 1 | # Transpose Matrix 2 | 3 | class Solution(object): 4 | def transpose(self, matrix): 5 | rows = len(matrix) 6 | cols = len(matrix[0]) 7 | 8 | transpose_matrix = [[0] * rows for _ in range(cols)] 9 | 10 | for i in range(rows): 11 | for j in range(cols): 12 | transpose_matrix[j][i] = matrix[i][j] 13 | 14 | return transpose_matrix 15 | 16 | solution = Solution() 17 | print(solution.transpose([[1,2,3],[4,5,6],[7,8,9]])) -------------------------------------------------------------------------------- /Python/trapping_rain_water.py: -------------------------------------------------------------------------------- 1 | # Trapping Rain Water 2 | 3 | class Solution(object): 4 | def trap(self, height): 5 | left, right = 0, len(height) - 1 6 | left_max = right_max = water_trapped = 0 7 | 8 | while left < right: 9 | if height[left] <= height[right]: 10 | if height[left] > left_max: 11 | left_max = height[left] 12 | else: 13 | water_trapped += left_max - height[left] 14 | left += 1 15 | else: 16 | if height[right] > right_max: 17 | right_max = height[right] 18 | else: 19 | water_trapped += right_max - height[right] 20 | right -= 1 21 | 22 | return water_trapped 23 | 24 | solution = Solution() 25 | print(solution.trap([0,1,0,2,1,0,1,3,2,1,2,1])) -------------------------------------------------------------------------------- /Python/truncate_sentence.py: -------------------------------------------------------------------------------- 1 | # Truncate Sentence 2 | 3 | class Solution(object): 4 | def truncateSentence(self, s, k): 5 | return ''.join([word + ' ' for word in s.split(' ')[:k]])[:-1] 6 | 7 | test = Solution() 8 | print(test.truncateSentence("Hello how are you Contestant", 4)) -------------------------------------------------------------------------------- /Python/two_out_of_three.py: -------------------------------------------------------------------------------- 1 | # Two Out of Three 2 | 3 | class Solution(object): 4 | def twoOutOfThree(self, nums1, nums2, nums3): 5 | nums = set(nums1 + nums2 + nums3) 6 | arr = [] 7 | for num in nums: 8 | count = 0 9 | if num in nums1: 10 | count += 1 11 | if num in nums2: 12 | count += 1 13 | if num in nums3: 14 | count += 1 15 | if count > 1: 16 | arr.append(num) 17 | 18 | return arr 19 | 20 | solution = Solution() 21 | print(solution.twoOutOfThree([1,1,3,2], [2,3], [3])) -------------------------------------------------------------------------------- /Python/two_sum.py: -------------------------------------------------------------------------------- 1 | # Two Sum 2 | 3 | class Solution(object): 4 | def twoSum(self, nums, target): 5 | num_indices = {} 6 | 7 | for i, num in enumerate(nums): 8 | complement = target - num 9 | 10 | if complement in num_indices: 11 | return [num_indices[complement], i] 12 | 13 | num_indices[num] = i 14 | 15 | test = Solution() 16 | print(test.twoSum([2,7,11,15], 9)) -------------------------------------------------------------------------------- /Python/unique_number_of_occurrences.py: -------------------------------------------------------------------------------- 1 | # Unique Number of Occurrences 2 | 3 | class Solution(object): 4 | def uniqueOccurrences(self, arr): 5 | count = {} 6 | 7 | for num in arr: 8 | count[num] = count.get(num, 0) + 1 9 | 10 | return len(count.values()) == len(set(count.values())) 11 | 12 | solution = Solution() 13 | print(solution.uniqueOccurrences([1,2,2,1,1,3])) -------------------------------------------------------------------------------- /Python/valid_anagram.py: -------------------------------------------------------------------------------- 1 | # Valid Anagram 2 | 3 | class Solution(object): 4 | def isAnagram(self, s, t): 5 | return sorted(s) == sorted(t) 6 | 7 | solution = Solution() 8 | print(solution.isAnagram()) -------------------------------------------------------------------------------- /Python/valid_palindrome.py: -------------------------------------------------------------------------------- 1 | # Valid Palindrome 2 | 3 | class Solution(object): 4 | def isSubsequence(self, s, t): 5 | i = 0 6 | 7 | for char in t: 8 | if i < len(s) and char == s[i]: 9 | i += 1 10 | 11 | return i == len(s) 12 | 13 | solution = Solution() 14 | print(solution.isSubsequence("abc", "ahbgdc")) -------------------------------------------------------------------------------- /Python/valid_parentheses.py: -------------------------------------------------------------------------------- 1 | # Valid Parentheses 2 | 3 | class Solution(object): 4 | def isValid(self, s): 5 | 6 | stack = [] 7 | mapping = {')': '(', '}': '{', ']': '['} 8 | 9 | for char in s: 10 | if char in mapping.values(): 11 | stack.append(char) 12 | elif char in mapping.keys(): 13 | if not stack or mapping[char] != stack.pop(): 14 | return False 15 | else: 16 | continue 17 | 18 | return not stack 19 | 20 | solution = Solution() 21 | print(solution.isValid("()")) 22 | -------------------------------------------------------------------------------- /Python/widest_vertical_area_between_two_points_containing_no_points.py: -------------------------------------------------------------------------------- 1 | # Widest Vertical Area Between Two Points Containing No Points 2 | 3 | class Solution(object): 4 | def maxWidthOfVerticalArea(self, points): 5 | points.sort(key=lambda x: x[0]) 6 | max_width = 0 7 | for i in range(1, len(points)): 8 | width = points[i][0] - points[i-1][0] 9 | max_width = max(max_width, width) 10 | return max_width 11 | 12 | test = Solution() 13 | print(test.maxWidthOfVerticalArea([[8,7],[9,9],[7,4],[9,7]])) -------------------------------------------------------------------------------- /Python/winner_of_the_linked_list_game.py: -------------------------------------------------------------------------------- 1 | # Winner of the Linked List Game 2 | 3 | class ListNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.next = None 7 | 8 | 9 | class Solution(object): 10 | def gameResult(self, head): 11 | odd, even = 0, 0 12 | while head: 13 | if head.val > head.next.val: 14 | even += 1 15 | else: 16 | odd += 1 17 | 18 | head = head.next.next 19 | 20 | if odd == even: 21 | return "Tie" 22 | if odd > even: 23 | return "Odd" 24 | else: 25 | return "Even" 26 | 27 | head = ListNode(2) 28 | head.next = ListNode(5) 29 | head.next.next = ListNode(4) 30 | head.next.next.next = ListNode(7) 31 | head.next.next.next.next = ListNode(20) 32 | head.next.next.next.next.next = ListNode(5) 33 | 34 | solution = Solution() 35 | print(solution.gameResult(head)) -------------------------------------------------------------------------------- /Python/word_search.py: -------------------------------------------------------------------------------- 1 | # Word Search 2 | 3 | class Solution(object): 4 | def exist(self, board, word): 5 | def dfs(board, i, j, word): 6 | if len(word) == 0: 7 | return True 8 | if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[0]: 9 | return False 10 | 11 | temp = board[i][j] 12 | board[i][j] = "#" 13 | 14 | found = dfs(board, i+1, j, word[1:]) or dfs(board, i-1, j, word[1:]) \ 15 | or dfs(board, i, j+1, word[1:]) or dfs(board, i, j-1, word[1:]) 16 | 17 | board[i][j] = temp 18 | 19 | return found 20 | 21 | for i in range(len(board)): 22 | for j in range(len(board[0])): 23 | if dfs(board, i, j, word): 24 | return True 25 | 26 | return False 27 | 28 | 29 | solution = Solution() 30 | print(solution.exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED")) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # LeetCode Python Solutions 4 | 5 | Welcome to my LeetCode Python Solutions repository! Here, you'll find my solutions to various LeetCode problems implemented in Python. 6 | 7 | ## About 8 | 9 | I'm dedicated to solving LeetCode problems using the Python programming language. This repository serves as a collection of my solutions, providing a reference for others and showcasing my problem-solving skills. 10 | 11 | ## Folder Structure 12 | 13 | - Each problem solution is organized in its dedicated folder. 14 | - The folder name corresponds to the problem's title. 15 | - Inside each folder, you'll find the Python script containing the solution. 16 | 17 | ## How to Navigate 18 | 19 | Feel free to explore the folders to find solutions to specific problems. Each Python script is thoroughly commented to explain the thought process and approach used to solve the problem. 20 | 21 | ## License 22 | 23 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 24 | 25 | ## My LeetCode stats 26 | [![DevOgabek's LeetCode Stats](https://leetcode-stats.vercel.app/api?username=DevOgabek&theme=Dark)](https://leetcode.com/DevOgabek/) 27 | 28 | ## Solved Problems 29 | 30 | - [Concatenation of Array](Python/concatenation_of_array.py) 31 | - [Build Array from Permutation](Python/build_array_from_permutation.py) 32 | - [Number of Good Pairs](Python/number_of_good_pairs.py) 33 | - [Final Value of Variable After Performing Operations](Python/final_value_of_variable_after_performing_operations.py) 34 | - [Shuffle the Array](Python/shuffle_the_array.py) 35 | - [Find Words Containing Character](Python/find_words_containing_character.py) 36 | - [Widest Vertical Area Between Two Points Containing No Points](Python/widest_vertical_area_between_two_points_containing_no_points.py) 37 | - [Richest Customer Wealth](Python/richest_customer_wealth.py) 38 | - [Kids With the Greatest Number of Candies](Python/kids_with_the_greatest_number_of_candies.py) 39 | - [Number of Employees Who Met the Target](Python/number_of_employees_who_met_the_target.py) 40 | - [Count Pairs Whose Sum is Less than Target](Python/count_pairs_whose_sum_is_less_than_target.py) 41 | - [Running Sum of 1d Array](Python/running_sum_of_1d_array.py) 42 | - [How Many Numbers Are Smaller Than the Current Number](Python/how_many_numbers_are_smaller_than_the_current_number.py) 43 | - [Maximum Number of Words Found in Sentences](Python/maximum_number_of_words_found_in_sentences.py) 44 | - [Sum of Values at Indices With K Set Bits](Python/sum_of_values_at_indices_with_k_set_bits.py) 45 | - [Decode XORed Array](Python/decode_xored_array.py) 46 | - [Left and Right Sum Differences](Python/left_and_right_sum_differences.py) 47 | - [Minimum Number Game](Python/minimum_number_game.py) 48 | - [Create Target Array in the Given Order](Python/create_target_array_in_the_given_order.py) 49 | - [Decompress Run-Length Encoded List](Python/decompress_run-length_encoded_list.py) 50 | - [Check If Two String Arrays are Equivalent](Python/check_if_two_string_arrays_are_equivalent.py) 51 | - [Count Items Matching a Rule](Python/count_items_matching_a_rule.py) 52 | - [Shuffle String](Python/shuffle_string.py) 53 | - [Truncate Sentence](Python/truncate_sentence.py) 54 | - [Find First Palindromic String in the Array](Python/find_first_palindromic_string_in_the_array.py) 55 | - [Difference Between Element Sum and Digit Sum of an Array](Python/difference_between_element_sum_and_digit_sum_of_an_array.py) 56 | - [Number of Arithmetic Triplets](Python/number_of_arithmetic_triplets.py) 57 | - [Count Number of Pairs With Absolute Difference K](Python/count_number_of_pairs_with_absolute_difference_k.py) 58 | - [Sum of All Odd Length Subarrays](Python/sum_of_all_odd_length_subarrays.py) 59 | - [Count the Number of Consistent Strings](Python/count_the_number_of_consistent_strings.py) 60 | - [Defanging an IP Address](Python/defanging_an_ip_address.py) 61 | - [Find All People With Secret](Python/find_all_people_with_secret.py) 62 | - [Jewels and Stones](Python/jewels_and_stones.py) 63 | - [Cheapest Flights Within K Stops](Python/cheapest_flights_within_k_stops.py) 64 | - [Find the Town Judge](Python/find_the_town_judge.py) 65 | - [Greatest Common Divisor Traversal](Python/greatest_common_divisor_traversal.py) 66 | - [Largest Local Values in a Matrix](Python/largest_local_values_in_a_matrix.py) 67 | - [Find the Highest Altitude](Python/find_the_highest_altitude.py) 68 | - [Check if a String Is an Acronym of Words](Python/check_if_a_string_is_an_acronym_of_words.py) 69 | - [Maximum Product Difference Between Two Pairs](Python/maximum_product_difference_between_two_pairs.py) 70 | - [Diameter of Binary Tree](Python/diameter_of_binary_tree.py) 71 | - [Two Sum](Python/two_sum.py) 72 | - [Find Bottom Left Tree Value](Python/find_bottom_left_tree_value.py) 73 | - [Sort the People](Python/sort_the_people.py) 74 | - [Palindrome Number](Python/palindrome_number.py) 75 | - [Matrix Diagonal Sum](Python/matrix_diagonal_sum.py) 76 | - [Same Tree](Python/same_tree.py) 77 | - [To Lower Case](Python/to_lower_case.py) 78 | - [Subarrays Distinct Element Sum of Squares I](Python/subarrays_distinct_element_sum_of_squares_i.py) 79 | - [Sum of All Subset XOR Totals](Python/sum_of_all_subset_xor_totals.py) 80 | - [Even Odd Tree](Python/even_odd_tree.py) 81 | - [Count Good Triplets](Python/count_good_triplets.py) 82 | - [Flipping an Image](Python/flipping_an_image.py) 83 | - [Maximum Odd Binary Number](Python/maximum_odd_binary_number.py) 84 | - [Count Tested Devices After Test Operations](Python/count_tested_devices_after_test_operations.py) 85 | - [Squares of a Sorted Array](Python/squares_of_a_sorted_array.py) 86 | - [Sum of Squares of Special Elements ](Python/sum_of_squares_of_special_elements_.py) 87 | - [Remove Nth Node From End of List](Python/remove_nth_node_from_end_of_list.py) 88 | - [Count Equal and Divisible Pairs in an Array](Python/count_equal_and_divisible_pairs_in_an_array.py) 89 | - [Find Maximum Number of String Pairs](Python/find_maximum_number_of_string_pairs.py) 90 | - [Separate the Digits in an Array](Python/separate_the_digits_in_an_array.py) 91 | - [Roman to Integer](Python/roman_to_integer.py) 92 | - [DI String Match](Python/di_string_match.py) 93 | - [Find the Difference of Two Arrays](Python/find_the_difference_of_two_arrays.py) 94 | - [Find Maximum Number of String Pairs](Python/find_maximum_number_of_string_pairs.py) 95 | - [Array Partition](Python/array_partition.py) 96 | - [Bag of Tokens](Python/bag_of_tokens.py) 97 | - [Goal Parser Interpretation](Python/goal_parser_interpretation.py) 98 | - [Maximum Sum With Exactly K Elements ](Python/maximum_sum_with_exactly_k_elements_.py) 99 | - [Remove Palindromic Subsequences](Python/remove_palindromic_subsequences.py) 100 | - [Design an Ordered Stream](Python/design_an_ordered_stream.py) 101 | - [Maximum Product Difference Between Two Pairs](Python/maximum_product_difference_between_two_pairs.py) 102 | - [Minimum Number of Moves to Seat Everyone](Python/minimum_number_of_moves_to_seat_everyone.py) 103 | - [Find Common Elements Between Two Arrays](Python/find_common_elements_between_two_arrays.py) 104 | - [Minimum Operations to Exceed Threshold Value I](Python/minimum_operations_to_exceed_threshold_value_i.py) 105 | - [Cells with Odd Values in a Matrix](Python/cells_with_odd_values_in_a_matrix.py) 106 | - [Sort Integers by The Number of 1 Bits](Python/sort_integers_by_the_number_of_1_bits.py) 107 | - [Counting Words With a Given Prefix](Python/counting_words_with_a_given_prefix.py) 108 | - [Delete Greatest Value in Each Row](Python/delete_greatest_value_in_each_row.py) 109 | - [Find Greatest Common Divisor of Array](Python/find_greatest_common_divisor_of_array.py) 110 | - [Final Prices With a Special Discount in a Shop](Python/final_prices_with_a_special_discount_in_a_shop.py) 111 | - [Count Negative Numbers in a Sorted Matrix](Python/count_negative_numbers_in_a_sorted_matrix.py) 112 | - [Find Numbers with Even Number of Digits](Python/find_numbers_with_even_number_of_digits.py) 113 | - [Sum of Unique Elements](Python/sum_of_unique_elements.py) 114 | - [Unique Number of Occurrences](Python/unique_number_of_occurrences.py) 115 | - [Neither Minimum nor Maximum](Python/neither_minimum_nor_maximum.py) 116 | - [N-Repeated Element in Size 2N Array](Python/n-repeated_element_in_size_2n_array.py) 117 | - [Height Checker](Python/height_checker.py) 118 | - [Find the Peaks](Python/find_the_peaks.py) 119 | - [Sort Array By Parity](Python/sort_array_by_parity.py) 120 | - [Sort Array By Parity](Python/sort_array_by_parity.py) 121 | - [Number of Senior Citizens](Python/number_of_senior_citizens.py) 122 | - [Find Target Indices After Sorting Array](Python/find_target_indices_after_sorting_array.py) 123 | - [Points That Intersect With Cars](Python/points_that_intersect_with_cars.py) 124 | - [Baseball Game](Python/baseball_game.py) 125 | - [Minimum Length of String After Deleting Similar Ends](Python/minimum_length_of_string_after_deleting_similar_ends.py) 126 | - [Decode the Message](Python/decode_the_message.py) 127 | - [Find N Unique Integers Sum up to Zero](Python/find_n_unique_integers_sum_up_to_zero.py) 128 | - [Minimum Operations to Make the Array Increasing](Python/minimum_operations_to_make_the_array_increasing.py) 129 | - [Replace All Digits with Characters](Python/replace_all_digits_with_characters.py) 130 | - [Sorting the Sentence](Python/sorting_the_sentence.py) 131 | - [Split a String in Balanced Strings](Python/split_a_string_in_balanced_strings.py) 132 | - [Number of Students Doing Homework at a Given Time](Python/number_of_students_doing_homework_at_a_given_time.py) 133 | - [Ant on the Boundary](Python/ant_on_the_boundary.py) 134 | - [Middle of the Linked List](Python/middle_of_the_linked_list.py) 135 | - [Split Strings by Separator](Python/split_strings_by_separator.py) 136 | - [Count Elements With Maximum Frequency](Python/count_elements_with_maximum_frequency.py) 137 | - [Maximum Strong Pair XOR I](Python/maximum_strong_pair_xor_i.py) 138 | - [Minimum Common Value](Python/minimum_common_value.py) 139 | - [Letter Combinations of a Phone Number](Python/letter_combinations_of_a_phone_number.py) 140 | - [Generate Parentheses](Python/generate_parentheses.py) 141 | - [Symmetric Tree](Python/symmetric_tree.py) 142 | - [Combination Sum](Python/combination_sum.py) 143 | - [Longest Common Prefix](Python/longest_common_prefix.py) 144 | - [Intersection of Two Arrays](Python/intersection_of_two_arrays.py) 145 | - [Permutations](Python/permutations.py) 146 | - [Merge Similar Items](Python/merge_similar_items.py) 147 | - [Maximum Number of Pairs in Array](Python/maximum_number_of_pairs_in_array.py) 148 | - [Maximum Units on a Truck](Python/maximum_units_on_a_truck.py) 149 | - [Merge Sorted Array](Python/merge_sorted_array.py) 150 | - [Best Time to Buy and Sell Stock](Python/best_time_to_buy_and_sell_stock.py) 151 | - [Majority Element](Python/majority_element.py) 152 | - [Transpose Matrix](Python/transpose_matrix.py) 153 | - [Remove Zero Sum Consecutive Nodes from Linked List](Python/remove_zero_sum_consecutive_nodes_from_linked_list.py) 154 | - [N-Queens](Python/n-queens.py) 155 | - [Subsets](Python/subsets.py) 156 | - [Binary Tree Inorder Traversal](Python/binary_tree_inorder_traversal.py) 157 | - [Single Number](Python/single_number.py) 158 | - [Move Zeroes](Python/move_zeroes.py) 159 | - [Convert Sorted Array to Binary Search Tree](Python/convert_sorted_array_to_binary_search_tree.py) 160 | - [Pascal's Triangle](Python/pascals_triangle.py) 161 | - [Find the Pivot Integer](Python/find_the_pivot_integer.py) 162 | - [Find the Index of the First Occurrence in a String](Python/find_the_index_of_the_first_occurrence_in_a_string.py) 163 | - [Binary Subarrays With Sum](Python/binary_subarrays_with_sum.py) 164 | - [Valid Palindrome](Python/valid_palindrome.py) 165 | - [Is Subsequence](Python/is_subsequence.py) 166 | - [Climbing Stairs](Python/climbing_stairs.py) 167 | - [Merge Two Sorted Lists](Python/merge_two_sorted_lists.py) 168 | - [Modify the Matrix](Python/modify_the_matrix.py) 169 | - [Next Greater Element I](Python/next_greater_element_i.py) 170 | - [Binary Subarrays With Sumvv](Python/binary_subarrays_with_sumvv.py) 171 | - [Maximum Depth of Binary Tree](Python/maximum_depth_of_binary_tree.py) 172 | - [Product of Array Except Self](Python/product_of_array_except_self.py) 173 | - [Contiguous Array](Python/contiguous_array.py) 174 | - [Destination City](Python/destination_city.py) 175 | - [Split Strings by Separator](Python/split_strings_by_separator.py) 176 | - [Make Array Zero by Subtracting Equal Amounts](Python/make_array_zero_by_subtracting_equal_amounts.py) 177 | - [Most Common Word](Python/most_common_word.py) 178 | - [Insert Interval](Python/insert_interval.py) 179 | - [Valid Anagram](Python/valid_anagram.py) 180 | - [Word Search](Python/word_search.py) 181 | - [Number of Students Unable to Eat Lunch](Python/number_of_students_unable_to_eat_lunch.py) 182 | - [Check if the Sentence Is Pangram](Python/check_if_the_sentence_is_pangram.py) 183 | - [Rings and Rods](Python/rings_and_rods.py) 184 | - [Two Out of Three](Python/two_out_of_three.py) 185 | - [Check if All Characters Have Equal Number of Occurrences](Python/check_if_all_characters_have_equal_number_of_occurrences.py) 186 | - [Find the Distinct Difference Array](Python/find_the_distinct_difference_array.py) 187 | - [First Letter to Appear Twice](Python/first_letter_to_appear_twice.py) 188 | - [Ransom Note](Python/ransom_note.py) 189 | - [Contains Duplicate II](Python/contains_duplicate_ii.py) 190 | - [Existence of a Substring in a String and Its Reverse](Python/existence_of_a_substring_in_a_string_and_its_reverse.py) 191 | - [Count Substrings Starting and Ending with Given Character](Python/count_substrings_starting_and_ending_with_given_character.py) 192 | - [Minimum Deletions to Make String K-Special](Python/minimum_deletions_to_make_string_k-special.py) 193 | - [Merge In Between Linked Lists](Python/merge_in_between_linked_lists.py) 194 | - [Find Missing and Repeated Values](Python/find_missing_and_repeated_values.py) 195 | - [Reverse Words in a String III](Python/reverse_words_in_a_string_iii.py) 196 | - [Cells in a Range on an Excel Sheet](Python/cells_in_a_range_on_an_excel_sheet.py) 197 | - [Row With Maximum Ones](Python/row_with_maximum_ones.py) 198 | - [Find the K-or of an Array](Python/find_the_k-or_of_an_array.py) 199 | - [Count Prefixes of a Given String](Python/count_prefixes_of_a_given_string.py) 200 | - [Find Champion I](Python/find_champion_i.py) 201 | - [Merge Two 2D Arrays by Summing Values](Python/merge_two_2d_arrays_by_summing_values.py) 202 | - [Smallest Index With Equal Value](Python/smallest_index_with_equal_value.py) 203 | - [Number of Unequal Triplets in Array](Python/number_of_unequal_triplets_in_array.py) 204 | - [Reverse Linked List](Python/reverse_linked_list.py) 205 | - [Split the Array](Python/split_the_array.py) 206 | - [Find Pivot Index](Python/find_pivot_index.py) 207 | - [Plus One](Python/plus_one.py) 208 | - [Distribute Candies](Python/distribute_candies.py) 209 | - [Minimize String Length](Python/minimize_string_length.py) 210 | - [Divide Array Into Equal Pairs](Python/divide_array_into_equal_pairs.py) 211 | - [Maximum Number of Balls in a Box](Python/maximum_number_of_balls_in_a_box.py) 212 | - [Check if Number Has Equal Digit Count and Digit Value](Python/check_if_number_has_equal_digit_count_and_digit_value.py) 213 | - [Maximum Number of Words You Can Type](Python/maximum_number_of_words_you_can_type.py) 214 | - [Kth Distinct String in an Array](Python/kth_distinct_string_in_an_array.py) 215 | - [Top K Frequent Elements](Python/top_k_frequent_elements.py) 216 | - [Longest Palindromic Substring](Python/longest_palindromic_substring.py) 217 | - [Minimum Sum of Four Digit Number After Splitting Digits](Python/minimum_sum_of_four_digit_number_after_splitting_digits.py) 218 | - [Maximum 69 Number](Python/maximum_69_number.py) 219 | - [Lexicographically Smallest Palindrome](Python/lexicographically_smallest_palindrome.py) 220 | - [Maximum Units on a Truck](Python/maximum_units_on_a_truck.py) 221 | - [Longest Common Suffix Queries](Python/longest_common_suffix_queries.py) 222 | - [Most Frequent IDs](Python/most_frequent_ids.py) 223 | - [Apply Operations to Make Sum of Array Greater Than or Equal to k](Python/apply_operations_to_make_sum_of_array_greater_than_or_equal_to_k.py) 224 | - [Maximum Length Substring With Two Occurrences](Python/maximum_length_substring_with_two_occurrences.py) 225 | - [Find the Duplicate Number](Python/find_the_duplicate_number.py) 226 | - [Buy Two Chocolates](Python/buy_two_chocolates.py) 227 | - [First Missing Positive](Python/first_missing_positive.py) 228 | - [Subarray Product Less Than K](Python/subarray_product_less_than_k.py) 229 | - [Valid Parentheses](Python/valid_parentheses.py) 230 | - [Remove Element](Python/remove_element.py) 231 | - [Remove Duplicates from Sorted Array](Python/remove_duplicates_from_sorted_array.py) 232 | - [Subarrays with K Different Integers](Python/subarrays_with_k_different_integers.py) 233 | - [Count Subarrays With Fixed Bounds](Python/count_subarrays_with_fixed_bounds.py) 234 | - [Length of Last Word](Python/length_of_last_word.py) 235 | - [Isomorphic Strings](Python/isomorphic_strings.py) 236 | - [Convert Binary Number in a Linked List to Integer](Python/convert_binary_number_in_a_linked_list_to_integer.py) 237 | - [Winner of the Linked List Game](Python/winner_of_the_linked_list_game.py) 238 | - [Remove Linked List Elements](Python/remove_linked_list_elements.py) 239 | - [Minimum Time Visiting All Points](Python/minimum_time_visiting_all_points.py) 240 | - [Trapping Rain Water](Python/trapping_rain_water.py) 241 | - [Number Of Rectangles That Can Form The Largest Square](Python/number_of_rectangles_that_can_form_the_largest_square.py) -------------------------------------------------------------------------------- /generate_file.py: -------------------------------------------------------------------------------- 1 | def create_python_file(problem_name): 2 | 3 | file_name = problem_name.lower().replace(' ', '_') + '.py' 4 | file_path = f'Python/{file_name}' 5 | 6 | with open(file_path, 'w') as file: 7 | file.write(f"""# {problem_name} 8 | 9 | class Solution(object): 10 | def build_array(self, nums): 11 | # Your solution here 12 | pass 13 | 14 | solution = Solution() 15 | print(solution.build_array())""") 16 | 17 | print(f"File '{file_path}' has been created.") 18 | 19 | return file_name 20 | 21 | if __name__ == "__main__": 22 | problem_name = input("Enter the name of the problem: ") 23 | file_name = create_python_file(problem_name) 24 | with open('README.md', 'a') as readme: 25 | readme.write(f"\n- [{problem_name}](Python/{file_name})") 26 | print("Entry added to README.md.") -------------------------------------------------------------------------------- /generate_lists.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def create_demo_lists(list_length, num_lists, min_value, max_value): 4 | demo_lists = [] 5 | 6 | for _ in range(num_lists): 7 | new_list = [random.randint(min_value, max_value) for _ in range(list_length)] 8 | demo_lists.append(new_list) 9 | 10 | return demo_lists 11 | 12 | list_length = int(input("Enter the length of each list: ")) 13 | num_lists = int(input("Enter the number of lists: ")) 14 | min_value = int(input("Enter the minimum value for elements: ")) 15 | max_value = int(input("Enter the maximum value for elements: ")) 16 | 17 | result_lists = create_demo_lists(list_length, num_lists, min_value, max_value) 18 | 19 | print("Demo Lists:") 20 | for demo_list in result_lists: 21 | print(demo_list) -------------------------------------------------------------------------------- /img/repo_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DevOgabek/LeetCodePythonSolutions/43a3ab92795aac45b9aa18e14c82818a74813270/img/repo_icon.png -------------------------------------------------------------------------------- /search_problem.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def search_problem_status(problem_name): 4 | problem_filename = problem_name.lower().replace(' ', '_') + '.py' 5 | 6 | files = os.listdir('.') 7 | if problem_filename in files: 8 | file_number = files.index(problem_filename) + 1 9 | print(f'The problem "{problem_name}" is resolved.') 10 | print(f'Solution found in file: {problem_filename}') 11 | print(f'File position in the list: {file_number}') 12 | else: 13 | print(f'The problem "{problem_name}" is not resolved.') 14 | 15 | if __name__ == "__main__": 16 | user_input = input("Enter the name of the problem: ") 17 | search_problem_status(user_input) --------------------------------------------------------------------------------