├── .gitignore ├── BST.md ├── LICENSE ├── README.md ├── cpp └── ds │ └── linked_list │ ├── node.cpp │ └── singly_linked_list.hpp ├── go ├── ds │ └── singlyLinkedList.go ├── go.mod └── main.go ├── java └── src │ └── io │ └── soumasish │ ├── AddTwoNumbers.java │ ├── BinaryTreeColoringGame.java │ ├── BullsAndCows.java │ ├── DeleteNodesAndReturnForest.java │ ├── FindLeavesOfBinaryTree.java │ ├── IsomorphicStrings.java │ ├── LongestPalindromicSubstring.java │ ├── LongestSubstringWithoutRepeatingCharacters.java │ ├── Main.java │ ├── MedianOfTwoSortedArrays.java │ ├── MergeSortedArrays.java │ ├── NumberOfIslands.java │ ├── RemoveNthNodeFromList.java │ ├── ReverseLinkedList.java │ ├── SearchInRotatedArray.java │ ├── SentenceSimilarity.java │ ├── SentenceSimilarityII.java │ ├── SingleRowKeyboard.java │ ├── TwoSum.java │ ├── ValidateBinarySearchTree.java │ ├── WordBreak.java │ └── utils │ ├── BinarySearchTree.java │ ├── DoublyLinkedList.java │ ├── Graph.java │ ├── Queue.java │ ├── SinglyLinkedList.java │ ├── Stack.java │ ├── Trie.java │ └── UnionFind.java ├── javascript ├── .babelrc ├── ds │ ├── avlTree.js │ ├── binarySearchTree.js │ ├── doublyLinkedList.js │ ├── fenwickTree.js │ ├── graph.js │ ├── hashMap.js │ ├── priorityQueue.js │ ├── queue.js │ ├── redBlackTree.js │ ├── singlyLinkedList.js │ ├── stack.js │ ├── trie.js │ └── unionFind.js └── src │ ├── addTwoNumbers.js │ ├── checkCompletenessOfBinaryTree.js │ ├── findTheTownJudge.js │ ├── goatLatin.js │ ├── kClosetPointstoOrigin.js │ ├── keysAndRooms.js │ ├── kthLargestElementInAStream.js │ ├── longestPalindromicSubstring.js │ ├── longestSubstringWithoutRepeatingCharacters.js │ ├── longestWordInDictionary.js │ ├── minAbsoluteDifference.js │ ├── minAddToMakeParanthesisValid.js │ ├── minimizeMalwareSpread.js │ ├── minimumDistanceBetweenBSTNodes.js │ ├── minimumIndexSumOfTwoLists.js │ ├── monotonicArray.js │ ├── rangeSumOfBST.js │ ├── reorderLogFiles.js │ ├── reverseInteger.js │ ├── smallest_subtree_with_all_deepest_nodes.js │ ├── splitBST.js │ ├── twoSum.js │ └── verifyingAlienDictionary.js ├── linkedin └── engagement.sql ├── python ├── 3sum.py ├── 3sum_smaller.py ├── 792_number_of_matching_subsequences.py ├── __init__.py ├── add_binary.py ├── add_bold_tag_in_string.py ├── add_two_numbers.py ├── assessments │ └── maximum_number_of_contestants.py ├── asteroid_collision.py ├── average_of_levels_in_binary_tree.py ├── backspace_string_compare.py ├── baseball_game.py ├── battleships_in_a_board.py ├── best_time_to_buy_and_sell_stock.py ├── binary_search_tree_iterator.py ├── binary_tree_coloring_game.py ├── binary_tree_inorder_traversal.py ├── binary_tree_level_order_traversal.py ├── binary_tree_level_order_traversal_ii.py ├── binary_tree_longest_consecutive_sequence.py ├── binary_tree_paths.py ├── binary_tree_postorder_traversal.py ├── binary_tree_preorder_traversal.py ├── binary_tree_right_side_view.py ├── binary_tree_upside_down.py ├── binary_tree_vertical_order_traversal.py ├── binary_tree_zigzag_level_order_traversal.py ├── bomb_enemy.py ├── bounded_blocking_queue.py ├── buddy_strings.py ├── burst_balloons.py ├── can_i_win.py ├── can_place_flowers.py ├── car_fleet.py ├── check_completeness_of_binary_tree.py ├── climbing_stairs.py ├── clone_graph.py ├── closest_binary_search_tree_value.py ├── compare_version_numbers.py ├── complex_number_multiplication.py ├── computational_geometry │ ├── README.md │ ├── __init__.py │ ├── intersection_of_two_line_segments.py │ └── point_inside_polygon.py ├── conceptual │ ├── README.md │ ├── __init__.py │ ├── decorators.py │ └── local_functions.py ├── construct_binary_search_tree_from_preorder.py ├── construct_string_from_binary_tree.py ├── container_with_most_water.py ├── continuous_subarray_sum.py ├── copy_list_with_random_pointer.py ├── count_number_with_unique_digits.py ├── course_schedule_ii.py ├── decode_ways.py ├── delete_node_in_a_linked_list.py ├── delete_node_in_binary_search_tree.py ├── design_add_and_search_words_data_structure.py ├── design_patterns │ ├── before_strategy.py │ └── strategy.py ├── design_tic_tac_toe.py ├── ds │ ├── README.md │ ├── __init__.py │ ├── __queue.py │ ├── binary_search_tree.py │ ├── disjoint_set.py │ ├── doubly_linked_list.py │ ├── graph │ │ ├── __init__.py │ │ ├── graph.py │ │ ├── graph_errors.py │ │ ├── node.py │ │ ├── shortest_path.py │ │ ├── topological_sort.py │ │ └── traversal.py │ ├── hash_map.py │ ├── heap │ │ ├── __init__.py │ │ ├── error.py │ │ ├── heap.py │ │ └── tests.py │ ├── priority_queue.py │ ├── singly_linked_list.py │ ├── stack.py │ ├── string_builder.py │ ├── substring_search.py │ ├── tests │ │ ├── __init__.py │ │ └── graph.py │ └── trie.py ├── dynamic_programming │ └── fibonacci.py ├── employee_importance.py ├── encode_and_decode_strings.py ├── enocde_and_decode_tiny_url.py ├── evaluate_reverse_polish_notation.py ├── excel_column_sheet_title.py ├── excel_sheet_column_number.py ├── exclusive_time_functions.py ├── factor_combinations.py ├── fibonacci_number.py ├── find_all_anagrams_in_a_string.py ├── find_celebrity.py ├── find_first_and_last_position_of_element_in_sorted_array.py ├── find_k_pairs_with_smallest_sum.py ├── find_leaves_of_binary_tree.py ├── find_median_from_data_stream.py ├── find_mode_in_binary_search_tree.py ├── find_peak_element.py ├── first_bad_version.py ├── first_unique_character_in_a_string.py ├── flatten_2d_vector.py ├── flatten_binary_tree_to_linked_list.py ├── flatten_nested_list_iterator.py ├── flip_binary_tree_to_match_preorder_traversal.py ├── flipping_an_image.py ├── flood_fill.py ├── game_of_life.py ├── generate_parantheses.py ├── h_index.py ├── happy_number.py ├── house_robber.py ├── hr.py ├── implement_trie.py ├── inorder_successor.py ├── inorder_successor_ii.py ├── insert_delete_get_random.py ├── insert_interval.py ├── insert_into_a_cyclic_sorted_list.py ├── integer_to_english_words.py ├── intersection_of_two_arrays_ii.py ├── is_subsequence.py ├── isomorphic_strings.py ├── k_diff_pairs_in_an_array.py ├── k_similar_strings.py ├── kth_largest_element_in_an_array.py ├── largest_component_size_by_common_factor.py ├── largest_rectangle_in_a_histogram.py ├── largest_value_in_each_tree_row.py ├── letter_case_permutation.py ├── letter_combinations_of_a_phone_number.py ├── lfu_cache.py ├── license_key_formatting.py ├── linked_list_components.py ├── logger_rate_limiter.py ├── longest_absolute_file_path.py ├── longest_arithmetic_sequence.py ├── longest_consecutive_sequence.py ├── longest_palindromic_subsequence.py ├── longest_palindromic_substring.py ├── longest_substring_with_at_most_2_distinct_characters.py ├── longest_substring_with_at_most_k_distinct_characters.py ├── longest_substring_without_repeating_characters.py ├── lowest_common_ancestor.py ├── lru_cache.py ├── magic_squares_in_a_grid.py ├── malware_spread_problem.py ├── max_consecutive_ones_iii.py ├── max_points_on_a_line.py ├── max_stack.py ├── maximal_rectangle.py ├── maximal_square.py ├── maximize_distance_to_closest_person.py ├── maximum_binary_tree.py ├── maximum_consecutive_ones.py ├── maximum_depth_of_binary_tree.py ├── maximum_difference_between_node_ancestor.py ├── maximum_length_of_pair_chain.py ├── maximum_product_subarray.py ├── maximum_size_subarray_sum_equals_k.py ├── maximum_subarray.py ├── median_of_two_sorted_arrays.py ├── meeting_rooms.py ├── meeting_rooms_ii.py ├── merge_intervals.py ├── merge_k_sorted_lists.py ├── merge_two_binary_trees.py ├── merge_two_sorted_lists.py ├── min_cost_climbing_stairs.py ├── min_stack.py ├── minimum_absolute_difference_in_bst.py ├── minimum_distance_between_bst_nodes.py ├── minimum_genetic_mutation.py ├── minimum_window_substring.py ├── missing_ranges.py ├── most_frequent_subtree_sum.py ├── move_zeroes.py ├── moving_average_of_a_data_stream.py ├── n_ary_tree_level_order_traversal.py ├── n_ary_tree_postorder_traversal.py ├── n_ary_tree_preorder_traversal.py ├── n_queens.py ├── n_th_tribonacci_number.py ├── nested_list_weight_sum.py ├── nested_list_weight_sum_ii.py ├── next_closest_time.py ├── next_permutation.py ├── number_of_boomerangs.py ├── number_of_islands.py ├── one_edit_distance.py ├── outliers │ ├── README.md │ ├── __init__.py │ ├── area_under_shadow.py │ ├── boggle_solver.py │ ├── cartesian_tree.py │ ├── detect_loop_in_singly_linked_list.py │ ├── duplicate_users.py │ ├── evaluate_a_string.py │ ├── find_all_permutations_of_string.py │ ├── find_files_with_same_content.py │ ├── find_the_n_fibonacci_number.py │ ├── huffman_coding.py │ ├── infer_spaces.py │ ├── longest_series_of_consecutive_integers.py │ ├── longest_subsequence_less_than_target.py │ ├── median_of_a_data_stream.py │ ├── n_queens.py │ ├── number_of_paths.py │ ├── optimal_component_cost.py │ ├── optimal_utilization.py │ ├── second_largest_element_in_a_bst.py │ ├── stack_server.py │ ├── task_scheduler.py │ └── word_finder.py ├── paint_fence.py ├── paint_house.py ├── palindrome_number.py ├── palindrome_permutation.py ├── palindromic_substring.py ├── partition_equal_subset_sum.py ├── pascals_triangle.py ├── path_sum_iii.py ├── peak_index_in_a_mountain_array.py ├── peeking_iterator.py ├── permutations.py ├── plus_one.py ├── populating_next_right_pointers_in_ each_ node.py ├── populating_next_right_pointers_in_each_node_II.py ├── positions_of_large_groups.py ├── pow_x_n.py ├── power_of_three.py ├── power_of_two.py ├── print_foobar_alternately.py ├── print_in_order.py ├── product_of_array_except_self.py ├── ransom_note.py ├── reaching_points.py ├── read_n_characters_given_read_4_ii.py ├── read_n_chars_given_read_4.py ├── recover_a_tree_from_preorder_traversal.py ├── regex │ ├── README.md │ ├── __init__.py │ └── address_book.py ├── regions_cut_by_slashes.py ├── regular_expression_matching.py ├── remove_duplicate_letters.py ├── remove_duplicates.py ├── remove_invalid_parahthesis.py ├── remove_outermost_parantheses.py ├── reorder_list.py ├── repeated_dna_sequence.py ├── repeated_substring_pattern.py ├── reverse_a_linked_list.py ├── reverse_integer.py ├── reverse_vowels_of_a_string.py ├── roman_to_integer.py ├── rotate_image.py ├── rotting_oranges.py ├── s_from_t.py ├── same_tree.py ├── satisfiability_of_equations.py ├── scratch │ ├── __init__.py │ ├── closures.py │ ├── dominos.py │ ├── hello_world.py │ ├── higher_order_functions.py │ └── toptal.py ├── search_a_2d_matrix.py ├── search_in_a_rotated_array.py ├── search_in_a_sorted_array_of_unknown_size.py ├── sentence_screen_formatting.py ├── serialize_and_deserialize_bst.py ├── serialize_deserialize_binary_tree.py ├── set_mismatch.py ├── shortest_path_to_all_keys.py ├── shortest_word_distance.py ├── shortest_word_distance_ii.py ├── shortest_word_distance_iii.py ├── similar_string_groups.py ├── single_element_in_a_soted_array.py ├── sliding_window_maximum.py ├── solve_the_equation.py ├── sort_characters_by_frequency.py ├── sort_colors.py ├── spiral_matrix.py ├── sqrt_x.py ├── string_to_integer.py ├── strobogrammatic_number.py ├── strobogrammatic_number_ii.py ├── subsets.py ├── sudoku_solver.py ├── sum_of_left_leaves.py ├── sum_of_root_to_leaf_binary_numbers.py ├── sum_of_square_numbers.py ├── swap_nodes_in_pairs.py ├── symmetric_tree.py ├── text_justification.py ├── trapping_rain_water.py ├── two_sum.py ├── two_sum_iii_data_structure_design.py ├── two_sum_iv_input_is_a_bst.py ├── unique_binary_search_trees_ii.py ├── valid_palindrome.py ├── valid_parantheses.py ├── valid_perfect_square.py ├── validate_binary_search_tree.py ├── vertical_order_traversal_of_a_binary_tree.py ├── walls_and_gates.py ├── wildcard_matching.py ├── word_break.py ├── word_ladder.py ├── word_pattern.py ├── word_search_ii.py ├── zig_zag_conversion.py └── zig_zag_iterator.py └── sql ├── actors_and_directors_who_cooperated_atleast_3_times.sql ├── ads_performance.sql ├── big_countries.sql ├── biggest_single_number.sql ├── combine_two_tables.sql ├── consecutive_numbers.sql ├── customers_who_bought_all_products.sql ├── customers_who_never_order.sql ├── delete_duplicate_emails.sql ├── duplicate_emails.sql ├── employees_earning_more_than_their_managers.sql ├── find_start_and_end_number_of_continuous_ranges.sql ├── find_team_size.sql ├── fix_names_in_table.sql ├── friend_requests_i.sql ├── game_plan_analysis_iii.sql ├── game_plan_analysis_iv.sql ├── game_play_analysis_i.sql ├── game_play_analysis_ii.sql ├── highest_grade_for_each_student.sql ├── nth_highest_salary.sql ├── number_of_comments_per_post.sql ├── project_employees_i.sql ├── recyclable_and_low_fat_products.sql ├── rising_temperature.sql ├── second_highest_salary.sql └── winning_candidate.sql /.gitignore: -------------------------------------------------------------------------------- 1 | env/ 2 | venv/ 3 | .idea 4 | __pycache__/ 5 | java/.idea 6 | java/*.iml 7 | facebook -------------------------------------------------------------------------------- /BST.md: -------------------------------------------------------------------------------- 1 | | # | Problem | Level | 2 | |---|:--------|:------| 3 | | 94 | [Binary Tree Inorder Traversal](https://github.com/soumasish/leetcode/blob/master/leetcode/binary_tree_inorder_traversal.py) | Medium | 4 | | 95 | [Unique Binary Search Trees -II](https://github.com/soumasish/leetcode/blob/master/leetcode/unique_binary_search_trees_ii.py) | Medium | 5 | | 449 | [Serialize & Deserialize a BST](https://github.com/soumasish/leetcode/blob/master/leetcode/serailize_and_deserialize_bst.py) | Medium | 6 | | 450 | [Delete a Node in a BST](https://github.com/soumasish/leetcode/blob/master/leetcode/delete_node_in_binary_search_tree.py) | Medium | 7 | | 501 | [Find Mode in Binary Search Tree](https://github.com/soumasish/leetcode/blob/master/leetcode/find_mode_in_binary_search_tree.py) | Medium | 8 | | 508 | [Most Frequent Subtree sum](https://github.com/soumasish/leetcode/blob/master/leetcode/most_frequent_subtree_sum.py) | Medium | 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Soumasish Goswami 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. 22 | -------------------------------------------------------------------------------- /cpp/ds/linked_list/node.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/cpp/ds/linked_list/node.cpp -------------------------------------------------------------------------------- /go/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/soumasish/leetcodely/go 2 | 3 | go 1.12 4 | -------------------------------------------------------------------------------- /go/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/soumasish/leetcodely/go/ds" 5 | ) 6 | 7 | func main() { 8 | l := ds.NewSinglyLinkedList() 9 | l.Insert(23) 10 | l.Insert(32) 11 | l.Print() 12 | l.Remove(23) 13 | l.Print() 14 | } 15 | -------------------------------------------------------------------------------- /java/src/io/soumasish/AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | public class AddTwoNumbers { 4 | public class ListNode { 5 | int val; 6 | ListNode next; 7 | 8 | ListNode(int x) { 9 | val = x; 10 | } 11 | } 12 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 | ListNode p = null, head = null; 14 | int carry = 0; 15 | while(true){ 16 | int sum = 0; 17 | if(l1 != null) sum += l1.val; 18 | if (l2 != null) sum += l2.val; 19 | sum += carry; 20 | if(sum >= 10){ 21 | sum = sum - 10; 22 | carry = 1; 23 | }else{ 24 | carry = 0; 25 | } 26 | ListNode temp = new ListNode(sum); 27 | if(p == null){ 28 | p = temp; 29 | head = p; 30 | } 31 | else{ 32 | p.next = temp; 33 | p = p.next; 34 | } 35 | if(l1 != null) l1 = l1.next; 36 | if(l2 != null) l2 = l2.next; 37 | if(l1 == null && l2 == null && carry == 0) break; 38 | 39 | } 40 | return head; 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /java/src/io/soumasish/BullsAndCows.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | import java.util.*; 4 | 5 | public class BullsAndCows { 6 | public String getHint(String secret, String guess) { 7 | int bulls=0, cows =0; 8 | return null; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/src/io/soumasish/DeleteNodesAndReturnForest.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | public class DeleteNodesAndReturnForest { 4 | } 5 | -------------------------------------------------------------------------------- /java/src/io/soumasish/IsomorphicStrings.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class IsomorphicStrings { 7 | public boolean isIsomorphic(String s, String t) { 8 | if(s.length() != t.length()) return false; 9 | Map forwardMap = new HashMap<>(); 10 | Map reverseMap = new HashMap<>(); 11 | for (int i = 0; i < s.length(); i++) { 12 | if(forwardMap.containsKey(s.charAt(i))){ 13 | if(forwardMap.get(s.charAt(i)) != t.charAt(i)) return false; 14 | } 15 | else{ 16 | forwardMap.put(s.charAt(i),t.charAt(i)); 17 | } 18 | if(reverseMap.containsKey(t.charAt(i))){ 19 | if(reverseMap.get(t.charAt(i)) != s.charAt(i)) return false; 20 | }else{ 21 | reverseMap.put(t.charAt(i), s.charAt(i)); 22 | } 23 | 24 | } 25 | return true; 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/src/io/soumasish/LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | import java.util.HashMap; 4 | 5 | public class LongestPalindromicSubstring { 6 | public int lengthOfLongestSubstring(String s) { 7 | int j,k; 8 | for (int i = 0; i map = new HashMap<>(); 15 | int currLen = 0, startIndex = 0, maxLen = 0; 16 | for (int i = 0; i nums2[k]){ 15 | arr[idx] = nums2[k]; 16 | k++; 17 | idx ++; 18 | } 19 | } 20 | for (int i = 0; i grid.length || j < 0 || j > grid[0].length || grid[i][j] == '0') return; 23 | grid[i][j] = '0'; 24 | for (int k = 0; k <4 ; k++) { 25 | int nx = i + dx[k]; 26 | int ny = j + dy[k]; 27 | dfs(grid, nx, ny); 28 | 29 | } 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/src/io/soumasish/RemoveNthNodeFromList.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | public class RemoveNthNodeFromList { 4 | private class ListNode{ 5 | int val; 6 | ListNode next; 7 | ListNode(int x){ val = x;} 8 | } 9 | public ListNode removeNthFromEnd(ListNode head, int n) { 10 | ListNode previous=head, current=head, next=head; 11 | while(current.next != null){ 12 | current = current.next; 13 | } 14 | return null; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/src/io/soumasish/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | public class ReverseLinkedList { 4 | public class ListNode { 5 | int val; 6 | ListNode next; 7 | ListNode(int x) { 8 | val = x; 9 | } 10 | } 11 | 12 | public ListNode reverseList(ListNode head) { 13 | if(head == null || head.next == null){ 14 | return head; 15 | } 16 | ListNode p = reverseList(head.next); 17 | head.next.next = head; 18 | head.next = null; 19 | return p; 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /java/src/io/soumasish/SearchInRotatedArray.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | public class SearchInRotatedArray { 4 | 5 | public int search(int[] nums, int target) { 6 | if(nums.length==0)return -1; 7 | 8 | int low = 0; 9 | int high = nums.length-1; 10 | 11 | int stPoint = getStartingPoint(nums); 12 | if(target>nums[high])high=stPoint; 13 | else low = stPoint; 14 | 15 | while(low<=high){ 16 | int mid = low + (high-low)/2; 17 | if(nums[mid]==target)return mid; 18 | if(nums[mid]>target)high=mid-1; 19 | else low=mid+1; 20 | } 21 | return -1; 22 | 23 | } 24 | 25 | public int getStartingPoint(int[] nums){ 26 | int low = 0; 27 | int high = nums.length-1; 28 | 29 | while(low<=high){ 30 | int mid = low + (high-low)/2; 31 | 32 | if(mid!=0 && nums[mid-1]>nums[mid])return mid; 33 | 34 | if(nums[mid]>nums[high])low=mid+1; 35 | else high=mid-1; 36 | 37 | } 38 | 39 | return 0; 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/src/io/soumasish/SingleRowKeyboard.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class SingleRowKeyboard { 7 | public int calculateTime(String keyboard, String word) { 8 | Map map = new HashMap<>(); 9 | for (int i = 0; i check = new HashMap<>(); 10 | for(int i=0; i < nums.length; i++){ 11 | if (check.containsKey(target - nums[i])){ 12 | result[0] = check.get(target - nums[i]); 13 | result[1] = i; 14 | break; 15 | }else{ 16 | check.put(nums[i], i); 17 | } 18 | } 19 | 20 | return result; 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/src/io/soumasish/ValidateBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | public class ValidateBinarySearchTree { 4 | 5 | private class TreeNode{ 6 | int val; 7 | TreeNode left; 8 | TreeNode right; 9 | TreeNode(int x){ val = x;} 10 | } 11 | public boolean isValidBST(TreeNode root) { 12 | 13 | return helper(root, Integer.MIN_VALUE, Integer.MAX_VALUE); 14 | } 15 | private boolean helper(TreeNode p, Integer minKey, Integer maxKey){ 16 | if(p == null) return true; 17 | if(p.val <= minKey || p.val >= maxKey) return false; 18 | return helper(p.left, minKey , p.val) && helper(p.right, p.val, maxKey); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/src/io/soumasish/WordBreak.java: -------------------------------------------------------------------------------- 1 | package io.soumasish; 2 | 3 | import java.util.List; 4 | 5 | public class WordBreak { 6 | public boolean wordBreak(String s, List wordDict) { 7 | 8 | boolean [] A = new boolean[s.length()]; 9 | for (int i = 0; i { 2 | const queue = [root]; 3 | let isLast = false; 4 | 5 | while (queue.length > 0) { 6 | const node = queue.shift(); 7 | 8 | if (node.left) { 9 | if (isLast) return false; 10 | queue.push(node.left); 11 | } else { 12 | isLast = true; 13 | } 14 | 15 | if (node.right) { 16 | if (isLast) return false; 17 | queue.push(node.right); 18 | } else { 19 | isLast = true; 20 | } 21 | } 22 | 23 | return true; 24 | }; -------------------------------------------------------------------------------- /javascript/src/findTheTownJudge.js: -------------------------------------------------------------------------------- 1 | //// Created by leananepari on 05/08/19. //// 2 | 3 | // /** 4 | // * @param {number} N 5 | // * @param {number[][]} trust 6 | // * @return {number} 7 | // */ 8 | const findJudge = (N, trust) => { 9 | let hashMap = {}; 10 | let judge = []; 11 | 12 | for (let i = 1; i <= N; i++) { 13 | hashMap[i] = []; 14 | judge.push(i); 15 | } 16 | 17 | for (let i = 0; i < trust.length; i++) { 18 | if (hashMap[trust[i][0]]) { 19 | hashMap[trust[i][0]].push(trust[i][1]); 20 | if (judge.includes(trust[i][0])) { 21 | judge.splice(judge.indexOf(trust[i][0]), 1); 22 | } 23 | } 24 | } 25 | 26 | if (judge.length === 0) { 27 | return -1; 28 | } else { 29 | for (let key in hashMap) { 30 | if (key !== judge[0].toString() && !hashMap[key].includes(judge[0])) { 31 | return -1; 32 | } 33 | } 34 | } 35 | return judge[0]; 36 | }; -------------------------------------------------------------------------------- /javascript/src/goatLatin.js: -------------------------------------------------------------------------------- 1 | const toGoatLatin = S =>{ 2 | const result = []; 3 | let curr; 4 | S.split(" ").map((word, index) => { 5 | if(!isVowel(word.charAt(0))) { 6 | curr = word.substr(1) + word[0]; 7 | 8 | }else{ 9 | curr = word; 10 | } 11 | 12 | curr += 'maa'; 13 | curr += 'a'.repeat(index); 14 | console.log(curr); 15 | result.push(curr) 16 | 17 | }); 18 | return result.join(" "); 19 | 20 | }; 21 | 22 | const isVowel = (c =>{ 23 | if(c === 'a' || c === 'A' || c === 'e' || c === 'E' || c === 'i' || c === 'I' || c === 'o' || c === 'O' || c === 'u' || c === 'U'){ 24 | return true; 25 | } 26 | 27 | }); 28 | 29 | const S = "I speak Goat Latin"; 30 | console.log(toGoatLatin(S)); 31 | 32 | -------------------------------------------------------------------------------- /javascript/src/kClosetPointstoOrigin.js: -------------------------------------------------------------------------------- 1 | /*We have a list of points on the plane. Find the K closest points to the origin (0, 0). 2 | (Here, the distance between two points on a plane is the Euclidean distance.) 3 | You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)*/ 4 | 5 | /** 6 | * @param {number[][]} points 7 | * @param {number} K 8 | * @return {number[][]} 9 | */ 10 | 11 | const kClosest = (points, K) => { 12 | 13 | }; -------------------------------------------------------------------------------- /javascript/src/keysAndRooms.js: -------------------------------------------------------------------------------- 1 | //// Created by leananepari on 05/08/19. //// 2 | 3 | 4 | // /** 5 | // * @param {number[][]} rooms 6 | // * @return {boolean} 7 | // */ 8 | const canVisitAllRooms = (rooms) => { 9 | let roomsMap = {}; 10 | 11 | for (let i = 0; i < rooms.length; i++) { 12 | roomsMap[i] = false; 13 | } 14 | 15 | const traverse = (node, i) => { 16 | roomsMap[i] = true; 17 | for (let i = 0; i < node.length; i++) { 18 | if (roomsMap[node[i]] === false) { 19 | traverse(rooms[node[i]], node[i]); 20 | } 21 | } 22 | } 23 | 24 | traverse(rooms[0], 0); 25 | 26 | for (let key in roomsMap) { 27 | if (roomsMap[key] === false) { 28 | return false; 29 | } 30 | } 31 | 32 | return true; 33 | }; -------------------------------------------------------------------------------- /javascript/src/longestPalindromicSubstring.js: -------------------------------------------------------------------------------- 1 | /*Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 2 | */ 3 | 4 | const longestPalindrome = s => { 5 | let arr = [...s]; 6 | let longest =""; 7 | for(let i=0; i< arr.length * 2; i++){ 8 | let left = Math.floor(i/2); 9 | let right = Math.floor(i/2) + i%2; 10 | while(left >=0 && right < arr.length && arr[left] === arr[right]){ 11 | let sub = arr.slice(left, right +1); 12 | if(sub.length >= longest.length){ 13 | longest = sub; 14 | } 15 | left --; 16 | right ++; 17 | } 18 | } 19 | return longest.join(""); 20 | 21 | }; 22 | const s = "cbbd"; 23 | console.log(longestPalindrome(s)); -------------------------------------------------------------------------------- /javascript/src/longestSubstringWithoutRepeatingCharacters.js: -------------------------------------------------------------------------------- 1 | /*Given a string, find the length of the longest substring without repeating characters.*/ 2 | 3 | const lengthOfLongestSubstring = s => { 4 | let arr = [...s]; 5 | const dict = {}; 6 | let currLen = 0; 7 | let maxLen = 0; 8 | let start = 0; 9 | for(let i=0; i < arr.length; i++){ 10 | if(arr[i] in dict) { 11 | start = dict[arr[i]] + 1; 12 | } 13 | currLen = i - start + 1; 14 | maxLen = Math.max(currLen, maxLen); 15 | dict[arr[i]] = i; 16 | } 17 | return maxLen; 18 | 19 | }; 20 | s1 = "abba"; 21 | console.log(lengthOfLongestSubstring(s1)); -------------------------------------------------------------------------------- /javascript/src/minAbsoluteDifference.js: -------------------------------------------------------------------------------- 1 | // Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. 2 | 3 | getMinimumDifference = root =>{ 4 | let prev = Infinity; 5 | let diff = Infinity; 6 | let traverse = root => { 7 | if (!root) { 8 | return; 9 | } 10 | traverse(root.left); 11 | diff = Math.min(diff, Math.abs(root.val - prev)); 12 | prev = root.val; 13 | traverse(root.right); 14 | }; 15 | traverse(root); 16 | return diff; 17 | 18 | }; 19 | 20 | 21 | -------------------------------------------------------------------------------- /javascript/src/minAddToMakeParanthesisValid.js: -------------------------------------------------------------------------------- 1 | const minAddToMakeValid = S => { 2 | const stack = []; 3 | let count = 0; 4 | [...S].map((c) => { 5 | if(c === '('){ 6 | stack.push(c); 7 | } 8 | else if(c === ')' && stack[stack.length -1] === '('){ 9 | stack.pop(); 10 | } 11 | else{ 12 | count ++; 13 | } 14 | }); 15 | return count + stack.length; 16 | 17 | }; 18 | const S = "())"; 19 | console.log(minAddToMakeValid(S)); -------------------------------------------------------------------------------- /javascript/src/minimumDistanceBetweenBSTNodes.js: -------------------------------------------------------------------------------- 1 | //Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. 2 | 3 | minDiffInBST = root => { 4 | let prev = Infinity; 5 | let minDiff = Infinity; 6 | 7 | const traverse = node =>{ 8 | if(!node){ 9 | return; 10 | } 11 | traverse(node.left); 12 | minDiff = Math.min(minDiff, Math.abs(node.val - prev)); 13 | prev = node.val; 14 | traverse(node.right); 15 | }; 16 | traverse(root); 17 | return minDiff 18 | 19 | }; -------------------------------------------------------------------------------- /javascript/src/monotonicArray.js: -------------------------------------------------------------------------------- 1 | // An array is monotonic if it is either monotone increasing or monotone decreasing. 2 | // An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. 3 | // Return true if and only if the given array A is monotonic. 4 | 5 | isMonotonic = A => { 6 | let d = 0; 7 | 8 | for(let i=1; i< A.length; i++){ 9 | 10 | if(A[i] < A[i-1] && d >= 0) d = 1; 11 | else if(A[i] > A[i-1] && d <= 0) d = -1; 12 | else return false 13 | } 14 | return true 15 | 16 | }; 17 | const A = [6,5,4,4]; 18 | console.log(isMonotonic(A)); -------------------------------------------------------------------------------- /javascript/src/rangeSumOfBST.js: -------------------------------------------------------------------------------- 1 | rangeSumBST = (root, L, R) => { 2 | let total = 0; 3 | 4 | const traverse = root =>{ 5 | if(!root){ 6 | return; 7 | } 8 | traverse(root.left); 9 | if(root.val >= L && root.val <= R){ 10 | total += root.val; 11 | } 12 | traverse(root.right); 13 | }; 14 | traverse(root); 15 | return total; 16 | 17 | }; -------------------------------------------------------------------------------- /javascript/src/reverseInteger.js: -------------------------------------------------------------------------------- 1 | /*Given a 32-bit signed integer, reverse digits of an integer.*/ 2 | 3 | const reverse = x => { 4 | if(x === 0) { 5 | return 0; 6 | } 7 | 8 | let a = [...x.toString()]; 9 | let arr; 10 | if(a[0] === '-'){ 11 | arr = a.slice(1).reverse(); 12 | arr.unshift('-') 13 | console.log(arr); 14 | 15 | }else if(a[0] === '0'){ 16 | arr = a.slice(1).reverse(); 17 | }else{ 18 | arr = a.reverse() 19 | } 20 | const res = parseInt(arr.join('')); 21 | if(res > 2147483648 || res < -2147483648){ 22 | return 0; 23 | }else{ 24 | return res; 25 | } 26 | 27 | }; 28 | console.log(reverse(-123)); -------------------------------------------------------------------------------- /javascript/src/smallest_subtree_with_all_deepest_nodes.js: -------------------------------------------------------------------------------- 1 | const subtreeWithAllDeepest = root => { 2 | 3 | }; 4 | 5 | const lca = (root, p, q) =>{ 6 | if(!root){ 7 | return null; 8 | } 9 | if(root === p || root === q){ 10 | return root; 11 | } 12 | const left = this.lca(root.left, p, q); 13 | const right = this.lca(root.right, p, q); 14 | 15 | if(left && right){ 16 | return root; 17 | } 18 | if(left) return left; 19 | else return right; 20 | }; -------------------------------------------------------------------------------- /javascript/src/splitBST.js: -------------------------------------------------------------------------------- 1 | splitBST = (root, V) =>{ 2 | 3 | 4 | }; -------------------------------------------------------------------------------- /javascript/src/twoSum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, return indices of the two numbers such that they insert up to a specific target. 3 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | * @param {number[]} nums 6 | * @param {number} target 7 | * @return {number[]} 8 | */ 9 | 10 | twoSum = (nums, target) => { 11 | let dict = {}; 12 | let result; 13 | nums.map((curr, index) => { 14 | if ((target - curr) in dict){ 15 | result = [dict[target - curr], index] 16 | }else{ 17 | dict[curr] =index 18 | } 19 | 20 | }); 21 | if (result !== null){ 22 | return result; 23 | }else{ 24 | return [] 25 | } 26 | 27 | }; 28 | nums = [2, 7, 11, 15]; 29 | target = 9; 30 | console.log(twoSum(nums, target)); -------------------------------------------------------------------------------- /javascript/src/verifyingAlienDictionary.js: -------------------------------------------------------------------------------- 1 | isAlienSorted = (words, order) => { 2 | order = " " + order; 3 | for(let i=1; i < words.length; i++){ 4 | let prev = words[i-1] + " "; 5 | let curr = words[i] + " "; 6 | let minLen = Math.min(prev.length, curr.length); 7 | for(let j=0; j order.indexOf(cc)){ 12 | return false; 13 | } 14 | break; 15 | } 16 | } 17 | } 18 | return true; 19 | 20 | }; -------------------------------------------------------------------------------- /python/3sum_smaller.py: -------------------------------------------------------------------------------- 1 | """Given an array of n integers nums and a target, find the number of index triplets i, j, k with 2 | 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.""" 3 | from typing import List 4 | 5 | 6 | class Solution(object): 7 | def threeSumSmaller(self, nums: List[int], target: int) -> int: 8 | """ 9 | :type nums: List[int] 10 | :type target: int 11 | :rtype: int 12 | """ 13 | if not nums or len(nums) < 3: 14 | return 0 15 | nums = sorted(nums) 16 | count = 0 17 | for i in range(len(nums)): 18 | l, h = i + 1, len(nums) - 1 19 | while l < h: 20 | if (nums[i] + nums[l] + nums[h]) >= target: 21 | h -= 1 22 | else: 23 | count += h - l 24 | l += 1 25 | return count 26 | 27 | 28 | if __name__ == '__main__': 29 | solution = Solution() 30 | print(solution.threeSumSmaller([0, 0, 0], 0)) 31 | -------------------------------------------------------------------------------- /python/792_number_of_matching_subsequences.py: -------------------------------------------------------------------------------- 1 | """Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.""" 2 | 3 | 4 | class Solution(object): 5 | def numMatchingSubseq(self, S, words): 6 | """ 7 | :type S: str 8 | :type words: List[str] 9 | :rtype: int 10 | """ 11 | count = 0 12 | for word in words: 13 | if self.is_subsequence(word, S): 14 | count += 1 15 | return count 16 | 17 | def is_subsequence(self, a, b): 18 | if len(a) == 0: 19 | return True 20 | i, j = 0, 0 21 | while j < len(b): 22 | if a[i] == b[j]: 23 | i += 1 24 | if i == len(a): 25 | return True 26 | j += 1 27 | return False 28 | -------------------------------------------------------------------------------- /python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/__init__.py -------------------------------------------------------------------------------- /python/add_binary.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/3/17.""" 2 | """Given two binary strings, return their sum (also a binary string). 3 | For example, 4 | a = \"11\" 5 | b = \"1\" 6 | Return \"100\".""" 7 | 8 | 9 | class Solution(object): 10 | def addBinary(self, a: str, b: str)-> str: 11 | """ 12 | :type a: str 13 | :type b: str 14 | :rtype: str 15 | """ 16 | max_length = max(len(a), len(b)) 17 | a = a.zfill(max_length) 18 | b = b.zfill(max_length) 19 | 20 | result = "" 21 | carry = 0 22 | for i in range(max_length - 1, -1, -1): 23 | ones = (a[i] == '1') + (b[i] == '1') + (carry == '1') 24 | 25 | if ones == 0: 26 | result = '0' + result 27 | carry = '0' 28 | elif ones == 1: 29 | result = '1' + result 30 | carry = '0' 31 | elif ones == 2: 32 | result = '0' + result 33 | carry = '1' 34 | else: 35 | result = '1' + result 36 | carry = '1' 37 | if carry == '1': 38 | result = '1' + result 39 | return result 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /python/add_two_numbers.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 10/7/17.""" 2 | """You are given two non-empty linked lists representing two non-negative integers. The digits are stored in 3 | reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 4 | 5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself.""" 6 | 7 | 8 | class ListNode: 9 | def __init__(self, x): 10 | self.val = x 11 | self.next = None 12 | 13 | 14 | class Solution(object): 15 | def addTwoNumbers(self, l1, l2): 16 | """ 17 | :type l1: ListNode 18 | :type l2: ListNode 19 | :rtype: ListNode 20 | """ 21 | p = root = ListNode(0) 22 | carry = 0 23 | while l1 or l2 or carry: 24 | v1 = v2 = 0 25 | if l1: 26 | v1 = l1.val 27 | l1 = l1.next 28 | if l2: 29 | v2 = l2.val 30 | l2 = l2.next 31 | carry, val = divmod(v1 + v2 + carry, 10) 32 | p.next = ListNode(val) 33 | p = p.next 34 | return root.next 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /python/assessments/maximum_number_of_contestants.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | def countMaximumTeams(skill, teamSize, maxDiff): 5 | min_heap = [] 6 | for item in skill: 7 | heapq.heappush(item, min_heap) 8 | 9 | teams = 0 10 | while len(min_heap) >= teamSize: 11 | store = [] 12 | for _ in range(teamSize): 13 | if len(store) == 0 or abs(store[-1] - min_heap[0]) <= maxDiff: 14 | ele = heapq.heappop(min_heap) 15 | store.append() 16 | if len(store) == teamSize: 17 | teams += 1 18 | return teams 19 | 20 | 21 | 22 | from itertools import combinations 23 | from collections import Counter 24 | 25 | 26 | def findPasswordStrength(password): 27 | length = len(password) + 1 28 | all_substrings = [password[x:y] for x, y in combinations(range(length), r=2)] 29 | strength = 0 30 | for item in all_substrings: 31 | mapper = {} 32 | for i in item: 33 | if i not in mapper: 34 | mapper[i] = 1 35 | count = 0 36 | for v in mapper.values(): 37 | count += v 38 | strength += count 39 | return strength 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /python/backspace_string_compare.py: -------------------------------------------------------------------------------- 1 | """Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a 2 | backspace character.""" 3 | 4 | 5 | class Solution(object): 6 | def backspaceCompare(self, S, T): 7 | """ 8 | :type S: str 9 | :type T: str 10 | :rtype: bool 11 | """ 12 | 13 | def next_char(s): 14 | bs = 0 15 | for c in s[::-1]: 16 | if c == '#': 17 | bs += 1 18 | elif bs > 0: 19 | bs -= 1 20 | else: 21 | yield c 22 | 23 | _S = next_char(S) 24 | _T = next_char(T) 25 | 26 | 27 | if __name__ == '__main__': 28 | solution = Solution() 29 | print(solution.backspaceCompare("ab#c", "ad#c")) 30 | print(solution.backspaceCompare("ab##", "c#d#")) 31 | print(solution.backspaceCompare("a##c", "#a#c")) 32 | print(solution.backspaceCompare("a#c", "b")) 33 | -------------------------------------------------------------------------------- /python/best_time_to_buy_and_sell_stock.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/18/17.""" 2 | """Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), 5 | design an algorithm to find the maximum profit.""" 6 | import sys 7 | 8 | 9 | class Solution(object): 10 | def maxProfit(self, prices): 11 | """ 12 | :type prices: List[int] 13 | :rtype: int 14 | """ 15 | # min_buying, profit = sys.maxint, 0 16 | # 17 | # for i, v in enumerate(prices): 18 | # if v < min_buying: 19 | # min_buying = v 20 | # profit = max(profit, v-min_buying) 21 | # return profit 22 | min_buying, profit = sys.maxsize, 0 23 | 24 | for i, v in enumerate(prices): 25 | min_buying = min(min_buying, v) 26 | profit = max(profit, v - min_buying) 27 | return profit 28 | 29 | 30 | -------------------------------------------------------------------------------- /python/binary_tree_coloring_game.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/binary_tree_coloring_game.py -------------------------------------------------------------------------------- /python/binary_tree_inorder_traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def inorderTraversal(self, root: TreeNode) -> [int]: 11 | res = [] 12 | 13 | def inorder_recursive(root, res): 14 | if not root: 15 | return 16 | inorder_recursive(root.left, res) 17 | res.append(root.val) 18 | inorder_recursive(root.right, res) 19 | 20 | # inorder_recursive(root, res) 21 | 22 | def inorder_iterative(root, res): 23 | stack = [] 24 | curr = root 25 | while True: 26 | if curr: 27 | stack.append(curr) 28 | curr = curr.left 29 | else: 30 | if len(stack) == 0: 31 | break 32 | curr = stack.pop() 33 | res.append(curr.value) 34 | curr = curr.right 35 | 36 | inorder_iterative(root, res) 37 | return res 38 | -------------------------------------------------------------------------------- /python/binary_tree_longest_consecutive_sequence.py: -------------------------------------------------------------------------------- 1 | """ Given a binary tree, find the length of the longest consecutive sequence path. 2 | The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child 3 | connections. The longest consecutive path need to be from parent to child (cannot be the reverse). """ 4 | 5 | class Solution(object): 6 | def longestConsecutive(self, root): 7 | """ 8 | :type root: TreeNode 9 | :rtype: int 10 | """ 11 | if not root: 12 | return 0 13 | return self.dfs(root, root.val + 1, 1, 1) 14 | 15 | def dfs(self, root, target, curr_val, max_val): 16 | if not root: 17 | return max_val 18 | if root.val == target: 19 | curr_val += 1 20 | max_val = max(curr_val, max_val) 21 | else: 22 | curr_val = 1 23 | return max(self.dfs(root.left, root.val + 1, curr_val, max_val), self.dfs(root.right, root.val + 1, curr_val, max_val)) 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /python/binary_tree_postorder_traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def postorderTraversal(self, root: TreeNode) -> List[int]: 11 | def _helper(root, res): 12 | if not root: 13 | return 14 | _helper(root.left, res) 15 | _helper(root.right, res) 16 | res.append(root.val) 17 | res = [] 18 | _helper(root, res) 19 | return res -------------------------------------------------------------------------------- /python/binary_tree_preorder_traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def preorderTraversal(self, root: TreeNode) -> List[int]: 11 | def _helper(root, res): 12 | if not root: 13 | return 14 | res.append(root.val) 15 | _helper(root.left, res) 16 | _helper(root.right, res) 17 | res = [] 18 | _helper(root, res) 19 | return res -------------------------------------------------------------------------------- /python/binary_tree_right_side_view.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | 4 | class Solution: 5 | def rightSideView(self, root: Treenode) -> List[int]: 6 | if not root: 7 | return [] 8 | levels = defaultdict(list) 9 | queue = deque() 10 | queue.append((root, 0)) 11 | while len(queue) > 0: 12 | item = queue.popleft() 13 | levels[item[1]].append(item[0].val) 14 | if item[0].left: 15 | queue.append((item[0].left, item[1] + 1)) 16 | if item[0].right: 17 | queue.append((item[0].right, item[1] + 1)) 18 | 19 | return [val[-1] for val in levels.values()] 20 | -------------------------------------------------------------------------------- /python/binary_tree_upside_down.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/30/17.""" 2 | """Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the 3 | same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into 4 | left leaf nodes.""" 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.left = None 11 | # self.right = None 12 | 13 | class Solution(object): 14 | def upsideDownBinaryTree(self, root): 15 | """ 16 | :type root: TreeNode 17 | :rtype: TreeNode 18 | """ 19 | 20 | if not root or not root.left: 21 | return root 22 | new_root = self.upsideDownBinaryTree(root.left) 23 | root.left.left = root.right 24 | root.left.right = root 25 | 26 | root.left = None 27 | root.right = None 28 | return new_root 29 | 30 | -------------------------------------------------------------------------------- /python/bounded_blocking_queue.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | import threading 3 | 4 | 5 | class BoundedBlockingQueue(object): 6 | 7 | def __init__(self, capacity: int): 8 | self.queue = deque() 9 | self.capacity = capacity 10 | self.lock = threading.Lock() 11 | self.buffer_not_full = threading.Condition(lock=self.lock) 12 | self.buffer_not_empty = threading.Condition(lock=self.lock) 13 | 14 | def enqueue(self, element: int) -> None: 15 | with self.lock: 16 | while len(self.queue) == self.capacity: 17 | self.buffer_not_full.wait() 18 | self.queue.append(element) 19 | self.buffer_not_empty.notify_all() 20 | 21 | def dequeue(self) -> int: 22 | with self.lock: 23 | while len(self.queue) == 0: 24 | self.buffer_not_empty.wait() 25 | item = self.queue.popleft() 26 | self.buffer_not_full.notify_all() 27 | return item 28 | 29 | def size(self) -> int: 30 | return len(self.queue) -------------------------------------------------------------------------------- /python/buddy_strings.py: -------------------------------------------------------------------------------- 1 | """Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so 2 | that the result equals B.""" 3 | 4 | 5 | class Solution(object): 6 | def buddyStrings(self, A, B): 7 | """ 8 | :type A: str 9 | :type B: str 10 | :rtype: bool 11 | """ 12 | if len(A) != len(B): 13 | return False 14 | if A == B: 15 | if len(set(A)) < len(A): 16 | return True 17 | diff = [(a, b) for a, b in zip(A, B) if a != b] 18 | return len(diff) == 2 and diff[0] == diff[1][::-1] 19 | 20 | 21 | if __name__ == '__main__': 22 | solution = Solution() 23 | print(solution.buddyStrings("ab", "ba")) 24 | print(solution.buddyStrings("ab", "ab")) 25 | print(solution.buddyStrings("aa", "aa")) 26 | print(solution.buddyStrings("aaaaaaabc", "aaaaaaacb")) 27 | print(solution.buddyStrings("", "aa")) 28 | -------------------------------------------------------------------------------- /python/burst_balloons.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Solution(object): 4 | def maxCoins(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | 10 | 11 | def helper(self, nums, max_list): 12 | 13 | curr_max, idx = -sys.maxsize, -1 14 | for i in range(len(nums) - 2): 15 | p = nums[i] * nums[i+1] * nums[i+2] 16 | if p > curr_max: 17 | curr_max, idx = p, i+1 18 | max_list.append(curr_max) 19 | n = nums[:idx] + nums[idx:] 20 | self.helper(n, max_list) 21 | 22 | -------------------------------------------------------------------------------- /python/can_i_win.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/22/17.""" 2 | """In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who 3 | first causes the running total to reach or exceed 100 wins. 4 | 5 | What if we change the game so that players cannot re-use integers? 6 | 7 | For example, two players might take turns drawing from a common pool of numbers of 1..15 without replacement until 8 | they reach a total >= 100. 9 | 10 | Given an integer maxChoosableInteger and another integer desiredTotal, determine if the first player to move can 11 | force a win, assuming both players play optimally. 12 | 13 | You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger 14 | than 300.""" 15 | 16 | class Solution(object): 17 | def canIWin(self, maxChoosableInteger, desiredTotal): 18 | """ 19 | :type maxChoosableInteger: int 20 | :type desiredTotal: int 21 | :rtype: bool 22 | """ -------------------------------------------------------------------------------- /python/can_place_flowers.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/7/17.""" 2 | """Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, 3 | flowers cannot be planted in adjacent plots - they would compete for water and both would die. 4 | 5 | Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), 6 | and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.""" 7 | 8 | 9 | class Solution(object): 10 | def canPlaceFlowers(self, flowerbed, n): 11 | """ 12 | :type flowerbed: List[int] 13 | :type n: int 14 | :rtype: bool 15 | """ 16 | flowerbed.insert(0, 0) 17 | flowerbed.append(0) 18 | for i in range(1, len(flowerbed) -1): 19 | if flowerbed[i-1] == flowerbed[i] == flowerbed[i+1] == 0: 20 | flowerbed[i] = 1 21 | n -= 1 22 | return n <= 0 23 | 24 | 25 | if __name__ == '__main__': 26 | solution = Solution() 27 | print(solution.canPlaceFlowers([1,0,0,0,1], 1)) 28 | -------------------------------------------------------------------------------- /python/car_fleet.py: -------------------------------------------------------------------------------- 1 | """N cars are going to the same destination along a one lane road. The destination is target miles away. 2 | Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the 3 | target along the road. 4 | A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. 5 | The distance between these two cars is ignored - they are assumed to have the same position. 6 | A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also 7 | a car fleet. 8 | If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. 9 | How many car fleets will arrive at the destination?""" 10 | import heapq 11 | 12 | 13 | class Solution(object): 14 | def carFleet(self, target, position, speed): 15 | """ 16 | :type target: int 17 | :type position: List[int] 18 | :type speed: List[int] 19 | :rtype: int 20 | """ 21 | 22 | 23 | if __name__ == '__main__': 24 | solution = Solution() 25 | print(solution.carFleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3])) 26 | -------------------------------------------------------------------------------- /python/check_completeness_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, x): 6 | self.val = x 7 | self.left = None 8 | self.right = None 9 | 10 | 11 | class Solution: 12 | def isCompleteTree(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: bool 16 | """ 17 | seen_null = False 18 | queue = deque() 19 | queue.appendleft(root.left) 20 | queue.appendleft(root.right) 21 | 22 | while len(queue) > 0: 23 | curr = queue.pop() 24 | if curr is None: 25 | seen_null = True 26 | else: 27 | if seen_null: 28 | return False 29 | queue.appendleft(curr.left) 30 | queue.appendleft(curr.right) 31 | 32 | return True 33 | -------------------------------------------------------------------------------- /python/climbing_stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n == 1: 4 | return 1 5 | dp = [0 for _ in range(n + 1)] 6 | dp[1] = 1 7 | dp[2] = 2 8 | 9 | for i in range(3, n+1): 10 | dp[i] = dp[i-1] + dp[i-2] 11 | return dp[n] 12 | -------------------------------------------------------------------------------- /python/clone_graph.py: -------------------------------------------------------------------------------- 1 | """Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. 2 | """ 3 | from collections import deque 4 | 5 | 6 | # Definition for a undirected graph node 7 | class UndirectedGraphNode: 8 | def __init__(self, x): 9 | self.label = x 10 | self.neighbors = [] 11 | 12 | 13 | class Solution: 14 | # @param node, a undirected graph node 15 | # @return a undirected graph node 16 | def cloneGraph(self, node): 17 | if not node: 18 | return None 19 | p = UndirectedGraphNode(node.label) 20 | visited = {node.lable: p} 21 | queue = deque() 22 | queue.appendleft(node) 23 | while len(queue) > 0: 24 | curr = queue.pop() 25 | for neighbor in curr.neighbors: 26 | if neighbor.label not in visited: 27 | visited[neighbor.label] = UndirectedGraphNode(neighbor.label) 28 | queue.appendleft(neighbor) 29 | visited[curr.label].neighbors.append(visited[neighbor.label]) 30 | return p 31 | -------------------------------------------------------------------------------- /python/complex_number_multiplication.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/6/17.""" 2 | """Given two strings representing two complex numbers. 3 | You need to return a string representing their multiplication. Note i2 = -1 according to the definition.""" 4 | 5 | class Solution(object): 6 | def complexNumberMultiply(self, a, b): 7 | """ 8 | :type a: str 9 | :type b: str 10 | :rtype: str 11 | """ -------------------------------------------------------------------------------- /python/computational_geometry/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/computational_geometry/README.md -------------------------------------------------------------------------------- /python/computational_geometry/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/computational_geometry/__init__.py -------------------------------------------------------------------------------- /python/computational_geometry/point_inside_polygon.py: -------------------------------------------------------------------------------- 1 | """Given a Point and a list of points that make a polygon, find if the point is inside the polygon.""" 2 | 3 | 4 | class Solution: 5 | def isInside(self, points, point): 6 | pass 7 | 8 | 9 | class Point: 10 | def __init__(self, x, y): 11 | self.x = x 12 | self.y = y 13 | -------------------------------------------------------------------------------- /python/conceptual/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/conceptual/README.md -------------------------------------------------------------------------------- /python/conceptual/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/conceptual/__init__.py -------------------------------------------------------------------------------- /python/conceptual/decorators.py: -------------------------------------------------------------------------------- 1 | def escape_unicode(f): 2 | def wrap(*args, **kwargs): 3 | x = f(*args, **kwargs) 4 | return ascii(x) 5 | 6 | return wrap 7 | -------------------------------------------------------------------------------- /python/conceptual/local_functions.py: -------------------------------------------------------------------------------- 1 | def sort_by_last_letter(s): 2 | return sorted(s, key=lambda p: p[-1]) 3 | 4 | 5 | def _sort_by_last_letter(s): 6 | def last_letter(p): 7 | return p[-1] 8 | 9 | return sorted(s, key=last_letter) 10 | 11 | 12 | def outer(): 13 | x = 3 14 | 15 | def inner(y): 16 | return x + y 17 | 18 | return inner 19 | 20 | 21 | # function factory 22 | 23 | 24 | def raise_to(exp): 25 | def raise_to_exp(x): 26 | return pow(x, exp) 27 | 28 | return raise_to_exp 29 | 30 | 31 | if __name__ == '__main__': 32 | print(sort_by_last_letter(['My', 'name', 'is', 'soumasish', 'goswami'])) 33 | print(_sort_by_last_letter(['My', 'name', 'is', 'soumasish', 'goswami'])) 34 | i = outer() 35 | print(i(4)) 36 | square = raise_to(2) 37 | print(square(5)) 38 | print(square.__closure__) 39 | -------------------------------------------------------------------------------- /python/construct_binary_search_tree_from_preorder.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | class Solution: 9 | def bstFromPreorder(self, preorder: [int]) -> TreeNode: 10 | root = TreeNode(preorder[0]) 11 | stack = [root] 12 | for item in preorder[1:]: 13 | if item < stack[-1].val: 14 | stack[-1].left = TreeNode(item) 15 | stack.append(stack[-1].left) 16 | else: 17 | while stack and stack[-1].val < item: 18 | last = stack.pop() 19 | last.right = TreeNode(item) 20 | stack.append(last.right) 21 | return root 22 | 23 | -------------------------------------------------------------------------------- /python/construct_string_from_binary_tree.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/7/17.""" 2 | """You need to construct a string consists of parenthesis and integers from a binary tree with the preorder 3 | traversing way. 4 | 5 | The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis 6 | pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.""" 7 | 8 | # Definition for a binary tree node. 9 | # class TreeNode(object): 10 | # def __init__(self, x): 11 | # self.val = x 12 | # self.left = None 13 | # self.right = None 14 | 15 | 16 | class Solution(object): 17 | def tree2str(self, t): 18 | """ 19 | :type t: TreeNode 20 | :rtype: str 21 | """ 22 | if not t: 23 | return '' 24 | if not t.left and not t.right: 25 | return str(t.val) 26 | l = self.tree2str(t.left) 27 | r = self.tree2str(t.right) 28 | res = str(t.val) + '(' + l + ')' 29 | if t.right: 30 | res += '(' + r + ')' 31 | return res 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /python/container_with_most_water.py: -------------------------------------------------------------------------------- 1 | """Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical 2 | lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with 3 | x-axis forms a container, such that the container contains the most water. 4 | 5 | 6 | Note: You may not slant the container and n is at least 2.""" 7 | 8 | 9 | class Solution(object): 10 | def maxArea(self, height): 11 | """ 12 | :type height: List[int] 13 | :rtype: int 14 | """ 15 | water = 0 16 | i, j = 0, len(height) - 1 17 | while i < j: 18 | water = max(water, (j - i) * min(height[i], height[j])) 19 | if height[i] < height[j]: 20 | i += 1 21 | else: 22 | j -= 1 23 | return water 24 | 25 | 26 | if __name__ == '__main__': 27 | solution = Solution() 28 | print(solution.maxArea([1, 1])) 29 | -------------------------------------------------------------------------------- /python/continuous_subarray_sum.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/2/17.""" 2 | """Given a list of non-negative numbers and a target integer k, write a function to check if the array 3 | has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.""" 4 | 5 | class Solution(object): 6 | def checkSubarraySum(self, nums, k): 7 | """ 8 | :type nums: List[int] 9 | :type k: int 10 | :rtype: bool 11 | """ 12 | memo = [0 for _ in range(len(nums))] 13 | cumulative_sum = 0 14 | for i in range(len(nums)): 15 | cumulative_sum += nums[i] 16 | memo[i] = cumulative_sum 17 | 18 | i, j = 0, len(memo)-1 19 | while i < j: 20 | if memo[j] - memo[i] % k == 0 and j - i >= 2: 21 | return True 22 | 23 | -------------------------------------------------------------------------------- /python/copy_list_with_random_pointer.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 4/12/17 as part of leetcode""" 2 | """A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | Return a deep copy of the list.""" 4 | 5 | 6 | class RandomListNode(object): 7 | def __init__(self, x): 8 | self.label = x 9 | self.next = None 10 | self.random = None 11 | 12 | from collections import OrderedDict 13 | 14 | 15 | class Solution(object): 16 | def copyRandomList(self, head): 17 | """ 18 | :type head: RandomListNode 19 | :rtype: RandomListNode 20 | """ 21 | if head is None: 22 | return 23 | curr = head 24 | d = OrderedDict() 25 | 26 | while curr: 27 | d[curr] = RandomListNode(curr.label) 28 | curr = curr.next 29 | m = head 30 | while m: 31 | n = d[m] 32 | if m.random is not None: 33 | n.random = d[m.random] 34 | if m.next is not None: 35 | n.next = d[m.next] 36 | m = m.next 37 | return d[head] 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /python/count_number_with_unique_digits.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countNumbersWithUniqueDigits(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | if n == 0: 8 | return 1 9 | if n == 1: 10 | return 10 11 | ans, base = 10, 9 12 | for i in range(1, n): 13 | base *= (10 - i) 14 | ans += base 15 | return ans 16 | 17 | if __name__ == '__main__': 18 | solution = Solution() 19 | print(solution.countNumbersWithUniqueDigits(2)) -------------------------------------------------------------------------------- /python/decode_ways.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/9/17.""" 2 | """A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 'A' -> 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | Given an encoded message containing digits, determine the total number of ways to decode it. 8 | For example, 9 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 10 | The number of ways decoding "12" is 2.""" 11 | 12 | 13 | class Solution(object): 14 | def numDecodings(self, s): 15 | """ 16 | :type s: str 17 | :rtype: int 18 | """ 19 | 20 | if s == '' or s == '0': 21 | return 0 22 | elif len(s) == 1: 23 | return 1 24 | memo = [0 for _ in range(len(s) + 1)] 25 | memo[0] = 1 26 | memo[1] = 1 if s[0] != '0' else 0 27 | for i in range(2, len(s)+1): 28 | single = int(s[i-1:i]) 29 | double = int(s[i-2:i]) 30 | if 0 < single <= 9: 31 | memo[i] += memo[i-1] 32 | if 9 < double <= 26: 33 | memo[i] += memo[i-2] 34 | return memo[-1] 35 | 36 | 37 | if __name__ == '__main__': 38 | solution = Solution() 39 | print(solution.numDecodings('1221')) 40 | -------------------------------------------------------------------------------- /python/delete_node_in_a_linked_list.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 6/16/17.""" 2 | 3 | # Definition for singly-linked list. 4 | class ListNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.next = None 8 | 9 | class Solution(object): 10 | def deleteNode(self, node): 11 | """ 12 | :type node: ListNode 13 | :rtype: void Do not return anything, modify node in-place instead. 14 | """ 15 | if node.next is not None: 16 | node.val = node.next.val 17 | node.next = node.next.next 18 | else: 19 | node = None -------------------------------------------------------------------------------- /python/delete_node_in_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def deleteNode(self, root: TreeNode, key: int) -> TreeNode: 11 | if not root: 12 | return 13 | if key > root.val: 14 | root.right = self.deleteNode(root.right, key) 15 | elif key < root.val: 16 | root.left = self.deleteNode(root.left, key) 17 | else: 18 | if not root.right: 19 | return root.left 20 | else: 21 | p = root.right 22 | while p.left: 23 | p = p.left 24 | root.val = p.val 25 | root.right = self.deleteNode(root.right, p.val) 26 | 27 | return root 28 | -------------------------------------------------------------------------------- /python/design_patterns/before_strategy.py: -------------------------------------------------------------------------------- 1 | class Order: 2 | def __init__(self, shipper): 3 | self._shipper = shipper 4 | 5 | @property 6 | def shipper(self): 7 | return self._shipper 8 | 9 | 10 | class Shipper: 11 | fedex = 1 12 | ups = 2 13 | usps = 3 14 | 15 | 16 | class ShippingCost: 17 | def __init__(self, order): 18 | self._cost = 0 19 | if order.shipper == Shipper.fedex: 20 | self._cost = self._fedex_cost(order) 21 | elif order.shipper == Shipper.ups: 22 | self._cost = self._ups_cost(order) 23 | elif order.shipper == Shipper.usps: 24 | self._cost = self._usps_cost(order) 25 | else: 26 | raise ValueError("Invalid Shipper") 27 | 28 | def get_cost(self): 29 | return self._cost 30 | 31 | def _fedex_cost(self, order): 32 | return 3.00 33 | 34 | def _ups_cost(self, order): 35 | return 4.00 36 | 37 | def _usps_cost(self, order): 38 | return 5.00 39 | -------------------------------------------------------------------------------- /python/design_patterns/strategy.py: -------------------------------------------------------------------------------- 1 | class ShippingCost: 2 | def __init__(self, strategy): 3 | self._strategy = strategy 4 | 5 | def cost(self, order): 6 | return self._strategy.calculate(order) 7 | 8 | import abc 9 | 10 | 11 | class Strategy(abc.ABC): 12 | @abc.abstractmethod 13 | def calculate(self, order): 14 | pass 15 | 16 | 17 | class FedexStrategy(Strategy): 18 | def calculate(self, order): 19 | return 3.00 20 | 21 | 22 | class UPSStrategy(Strategy): 23 | def calculate(self, order): 24 | return 4.00 25 | 26 | 27 | class USPSStrategy(Strategy): 28 | def calculate(self, order): 29 | return 5.00 -------------------------------------------------------------------------------- /python/ds/README.md: -------------------------------------------------------------------------------- 1 | # Data Structures in Python 2 | 3 | | # | ADT | 4 | |---|:--------| 5 | | 1 |[Singly Linked List](https://github.com/soumasish/leetcodely/blob/master/python/ds/singly_linked_list.py)| 6 | | 2 |[Doubly Linked List](https://github.com/soumasish/leetcodely/blob/master/python/ds/doubly_linked_list.py)| 7 | | 3 |[Stack](https://github.com/soumasish/leetcodely/blob/master/python/ds/stack.py)| 8 | | 4 |[Queue](https://github.com/soumasish/leetcodely/blob/master/python/ds/_queue.py)| 9 | | 5 |[Hash Map](https://github.com/soumasish/leetcodely/blob/master/python/ds/hash_map.py)| 10 | | 6 |[Binary Search Tree](https://github.com/soumasish/leetcodely/blob/master/python/ds/binary_search_tree.py)| 11 | | 7 |[Heap](https://github.com/soumasish/leetcodely/blob/master/python/ds/heap.py)| 12 | | 8 |[Disjoint Set](https://github.com/soumasish/leetcodely/blob/master/python/ds/disjoint_set.py)| 13 | | 9 |[Graph](https://github.com/soumasish/leetcodely/blob/master/python/ds/graph.py)| 14 | -------------------------------------------------------------------------------- /python/ds/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/ds/__init__.py -------------------------------------------------------------------------------- /python/ds/disjoint_set.py: -------------------------------------------------------------------------------- 1 | class DisjointSet: 2 | def __init__(self, vertices): 3 | self.parent = {vertex: vertex for vertex in vertices} 4 | 5 | def union(self, a, b): 6 | x = self.find(a) 7 | y = self.find(b) 8 | if x != y: 9 | self.parent[x] = y 10 | 11 | def find(self, item): 12 | if self.parent[item] == item: 13 | return item 14 | while self.parent != item: 15 | item = self.parent[self.parent[item]] 16 | return self.parent[item] 17 | 18 | def count(self): 19 | count = 0 20 | for key, val in self.parent.items(): 21 | if key == val: 22 | count += 1 23 | return count 24 | 25 | 26 | data = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 27 | sets = [('a', 'c'), ('b', 'e', 'd'), ('f', 'g')] 28 | d = DisjointSet(data) 29 | d.union('a', 'c') 30 | d.union('b', 'e') 31 | d.union('b', 'd') 32 | d.union('e', 'd') 33 | d.union('f', 'g') 34 | print(d.count()) 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /python/ds/graph/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/ds/graph/__init__.py -------------------------------------------------------------------------------- /python/ds/graph/graph_errors.py: -------------------------------------------------------------------------------- 1 | class GraphError(Exception): 2 | def __init__(self, message): 3 | super.__init__() 4 | self.message = message 5 | 6 | def __str__(self): 7 | return self.message 8 | -------------------------------------------------------------------------------- /python/ds/graph/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, id, value): 3 | self.id = id 4 | self.value = value 5 | self.neighbors = set() 6 | 7 | def add_edge(self, v): 8 | if v.id == self.id: 9 | raise ValueError("Vertex cannot be added to itself!") 10 | self.neighbors.add(v) 11 | 12 | def get_neighbors(self): 13 | return sorted(list(self.neighbors)) 14 | 15 | def __lt__(self, other): 16 | return self.id < other.id 17 | 18 | def __gt__(self, other): 19 | return self.id > other.id 20 | 21 | def __eq__(self, other): 22 | return self.id == other.id 23 | 24 | def __hash__(self): 25 | return hash((self.id, self.value)) 26 | 27 | def __repr__(self): 28 | return '{}'.format(self.value) -------------------------------------------------------------------------------- /python/ds/graph/topological_sort.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | def topological_sort(graph): 5 | indegree_map = {v: 0 for v in graph.vertex_map.values()} 6 | for v in graph.vertex_map.values(): 7 | neighbors = v.get_neighbors() 8 | for neighbor in neighbors: 9 | indegree_map[neighbor] += 1 10 | queue = deque() 11 | for k, v in indegree_map.items(): 12 | if v == 0: 13 | queue.appendleft(k) 14 | result = [] 15 | while len(queue) > 0: 16 | vertex = queue.pop() 17 | result.append(vertex) 18 | for neighbor in vertex.get_neighbors(): 19 | indegree_map[neighbor] -= 1 20 | if indegree_map[neighbor] == 0: 21 | queue.appendleft(neighbor) 22 | return result 23 | -------------------------------------------------------------------------------- /python/ds/heap/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/ds/heap/__init__.py -------------------------------------------------------------------------------- /python/ds/heap/error.py: -------------------------------------------------------------------------------- 1 | class HeapError(Exception): 2 | def __init__(self, message): 3 | super.__init__() 4 | self.message = message 5 | 6 | def __str__(self): 7 | return self.message 8 | -------------------------------------------------------------------------------- /python/ds/heap/heap.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from python.ds.heap.error import HeapError 3 | 4 | 5 | class MinHeap: 6 | def __init__(self): 7 | self.heap = [] 8 | 9 | def push(self, item): 10 | heapq.heappush(self.heap, item) 11 | 12 | def pop(self): 13 | return heapq.heappop(self.heap) 14 | 15 | def peek(self): 16 | if len(self.heap) == 0: 17 | raise HeapError("Peeking into an empty heap") 18 | return heapq.nsmallest(1, self.heap)[0] 19 | 20 | def __len__(self): 21 | return len(self.heap) 22 | 23 | 24 | class MaxHeap(MinHeap): 25 | def __init__(self): 26 | super().__init__() 27 | 28 | def peek(self): 29 | if len(self.heap) == 0: 30 | raise HeapError("Peeking into an empty heap") 31 | return heapq.nlargest(1, self.heap)[0] 32 | 33 | def pop(self): 34 | if len(self.heap) == 0: 35 | raise HeapError("Popping off an empty heap") 36 | return self.heap.pop() 37 | 38 | 39 | if __name__ == '__main__': 40 | min_heap = MinHeap() 41 | min_heap.push(12) 42 | min_heap.push(3) 43 | min_heap.push(17) 44 | print(min_heap.pop()) 45 | print(min_heap.pop()) 46 | -------------------------------------------------------------------------------- /python/ds/priority_queue.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/ds/priority_queue.py -------------------------------------------------------------------------------- /python/ds/string_builder.py: -------------------------------------------------------------------------------- 1 | class StringBuilder: 2 | 3 | def __init__(self): 4 | self.store = [] 5 | self.size = 0 6 | 7 | def append(self, item): 8 | self.store.append(str(item)) 9 | self.size += len(item) 10 | 11 | def build(self): 12 | return ''.join(self.store) 13 | 14 | def __len__(self): 15 | return self.size 16 | 17 | -------------------------------------------------------------------------------- /python/ds/substring_search.py: -------------------------------------------------------------------------------- 1 | """This class implements a set of methods with different complexities to find if a substring p is present 2 | in a string t.""" 3 | 4 | 5 | class SubStringSearch: 6 | 7 | @staticmethod 8 | def naive_search(t, p): 9 | for i in range(len(t)): 10 | j, k = i, 0 11 | while j < len(t) and k < len(p) and t[j] == p[k]: 12 | j += 1 13 | k += 1 14 | if k == len(p): 15 | return i 16 | return -1 17 | 18 | @staticmethod 19 | def kmp(t, p): 20 | pass 21 | 22 | @staticmethod 23 | def rabin_karp(t, p): 24 | pass 25 | 26 | @staticmethod 27 | def boyer_moore(t, p): 28 | pass 29 | 30 | 31 | if __name__ == '__main__': 32 | searcher = SubStringSearch() 33 | print(searcher.naive_search('abcbcglx', 'bcglx')) 34 | 35 | -------------------------------------------------------------------------------- /python/ds/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/ds/tests/__init__.py -------------------------------------------------------------------------------- /python/ds/tests/graph.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from python.ds.graph import Graph 3 | 4 | 5 | class GraphTestMethods(unittest.TestCase): 6 | 7 | def test_repr(self): 8 | graph = Graph() 9 | graph.add_edge("A", "B") 10 | graph.add_edge("A", "C") 11 | graph.add_edge("C", "D") 12 | graph.add_edge("D", "E") 13 | # print(graph) 14 | self.assertEqual(len(graph), 5) 15 | 16 | 17 | if __name__ == '__main__': 18 | unittest.main() 19 | -------------------------------------------------------------------------------- /python/dynamic_programming/fibonacci.py: -------------------------------------------------------------------------------- 1 | """ 2 | Intuition: 3 | This is bottom up dynamic programming, which builds the memo all the way from bottom to up. 4 | Most of these problems can be solved without using the entire array and just two variables, 5 | however I find it more intuitive to understand the code using the array. 6 | """ 7 | 8 | 9 | def fibonacci(n): 10 | if n == 0: 11 | return 1 12 | if n == 1: 13 | return 1 14 | memo = [0] * n 15 | memo[1] = 1 16 | for i in range(2, n): 17 | memo[i] = memo[i - 1] + memo[i - 2] 18 | return memo[n - 1] 19 | 20 | 21 | print(fibonacci(23)) 22 | -------------------------------------------------------------------------------- /python/encode_and_decode_strings.py: -------------------------------------------------------------------------------- 1 | """Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and 2 | is decoded back to the original list of strings.""" 3 | 4 | 5 | class Codec: 6 | 7 | def encode(self, strs): 8 | """Encodes a list of strings to a single string. 9 | 10 | :type strs: List[str] 11 | :rtype: str 12 | """ 13 | if not strs: 14 | return ' /*/ ' 15 | modified = [s.replace('*', '**') for s in strs] 16 | return ' /*/ '.join(modified) 17 | 18 | def decode(self, s): 19 | """Decodes a single string to a list of strings. 20 | 21 | :type s: str 22 | :rtype: List[str] 23 | """ 24 | original = s.split(' /*/ ') 25 | return [s.replace('**', '*') for s in original] 26 | 27 | 28 | -------------------------------------------------------------------------------- /python/excel_column_sheet_title.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/3/17.""" 2 | """Given a positive integer, return its corresponding column title as appear in an Excel sheet. 3 | 4 | For example: 5 | 6 | 1 -> A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB """ 13 | 14 | 15 | class Solution(object): 16 | def convertToTitle(self, n): 17 | """ 18 | :type n: int 19 | :rtype: str 20 | """ 21 | result = [] 22 | while n > 0: 23 | result.append(chr((n-1) % 26 + ord('A'))) 24 | print(result) 25 | n = (n - 1) // 26 26 | return ''.join(reversed(result)) 27 | 28 | 29 | if __name__ == '__main__': 30 | solution = Solution() 31 | print(solution.convertToTitle(562)) -------------------------------------------------------------------------------- /python/excel_sheet_column_number.py: -------------------------------------------------------------------------------- 1 | """Given a column title as appear in an Excel sheet, return its corresponding column number. 2 | For example: 3 | A -> 1 4 | B -> 2 5 | C -> 3 6 | ... 7 | Z -> 26 8 | AA -> 27 9 | AB -> 28 """ 10 | 11 | 12 | class Solution: 13 | def titleToNumber(self, s): 14 | """ 15 | :type s: str 16 | :rtype: int 17 | """ 18 | res = 0 19 | for c in s: 20 | res = (res * 26) + (ord(c) - 65 + 1) 21 | return res 22 | 23 | 24 | if __name__ == '__main__': 25 | solution = Solution() 26 | print(solution.titleToNumber('ABB')) 27 | -------------------------------------------------------------------------------- /python/factor_combinations.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/9/17.""" 2 | """Numbers can be regarded as product of its factors. For example, 3 | 8 = 2 x 2 x 2; 4 | = 2 x 4. 5 | Write a function that takes an integer n and return all possible combinations of its factors.""" 6 | import sys 7 | 8 | 9 | class Solution(object): 10 | def getFactors(self, n): 11 | """ 12 | :type n: int 13 | :rtype: List[List[int]] 14 | """ 15 | pass 16 | 17 | 18 | if __name__ == '__main__': 19 | solution = Solution() 20 | print(solution.getFactors(32)) 21 | 22 | 23 | -------------------------------------------------------------------------------- /python/fibonacci_number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fib(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | a, b = 0, 1 8 | if n == 0: 9 | return a 10 | if n == 1: 11 | return b 12 | for i in range(2, n + 1): 13 | a, b = b, (a + b) 14 | return b 15 | -------------------------------------------------------------------------------- /python/find_all_anagrams_in_a_string.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/13/17.""" 2 | """Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. 3 | 4 | Strings consists of lowercase English letters only and the length of both strings s and p will not be 5 | larger than 20,100. 6 | 7 | The order of output does not matter.""" 8 | import collections 9 | 10 | 11 | class Solution(object): 12 | def findAnagrams(self, s, p): 13 | """ 14 | :type s: str 15 | :type p: str 16 | :rtype: List[int] 17 | """ 18 | if not s or not p: 19 | return [] 20 | p_map = dict(collections.Counter(p)) 21 | results = [] 22 | for i in range(len(s)): 23 | if s[i] in p_map: 24 | checker = dict(collections.Counter(s[i:i+len(p)])) 25 | if checker == p_map: 26 | results.append(i) 27 | return results 28 | 29 | if __name__ == '__main__': 30 | solution = Solution() 31 | print(solution.findAnagrams('cbaebabacd', 'abc')) 32 | -------------------------------------------------------------------------------- /python/find_k_pairs_with_smallest_sum.py: -------------------------------------------------------------------------------- 1 | def kSmallestPairs(self, nums1: list[int], nums2: list[int], k: int) -> list[list[int]]: 2 | all_pairs = [[i, j] for i in nums1 for j in nums2] 3 | all_pairs = sorted(all_pairs, key=lambda x : x[0] + x[1]) 4 | return all_pairs[:k] 5 | 6 | # TODO: Incomplete 7 | 8 | 9 | -------------------------------------------------------------------------------- /python/find_leaves_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def findLeaves(self, root: TreeNode) -> list[list[int]]: 11 | if not root: 12 | return [] 13 | res, ans = [], [] 14 | 15 | def helper(root): 16 | if not root: 17 | return 18 | if root.left: 19 | if root.left.left is None and root.left.right is None: 20 | ans.append(root.left.val) 21 | root.left = None 22 | if root.right: 23 | if root.right.left is None and root.right.right is None: 24 | ans.append(root.right.val) 25 | root.right = None 26 | helper(root.left) 27 | helper(root.right) 28 | while True: 29 | if not root.right and not root.left: 30 | res.append([root.val]) 31 | break 32 | helper(root) 33 | res.append(ans) 34 | ans = [] 35 | return res 36 | 37 | -------------------------------------------------------------------------------- /python/find_mode_in_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | import collections 3 | 4 | 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | 12 | class Solution: 13 | def findMode(self, root: TreeNode) -> [int]: 14 | if not root: 15 | return [] 16 | 17 | def dfs(node): 18 | if not node: 19 | return 20 | count[node.val] += 1 21 | dfs(node.left) 22 | dfs(node.right) 23 | count = collections.Counter() 24 | dfs(root) 25 | max_val = max(count.values()) 26 | return [s for s in count if count[s] == max_val] 27 | 28 | 29 | root = TreeNode(12) 30 | root.left = TreeNode(9) 31 | root.right = TreeNode(13) 32 | 33 | solution = Solution() 34 | print(solution.findMode(root)) 35 | -------------------------------------------------------------------------------- /python/find_peak_element.py: -------------------------------------------------------------------------------- 1 | """A peak element is an element that is greater than its neighbors. 2 | Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. 3 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 4 | You may imagine that nums[-1] = nums[n] = -∞.""" 5 | 6 | 7 | class Solution(object): 8 | def findPeakElement(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | if len(nums) == 0: 14 | return -1 15 | low, high = 0, len(nums) - 1 16 | while low < high: 17 | mid = low + (high - low) // 2 18 | if nums[mid] < nums[mid + 1]: 19 | low = mid + 1 20 | else: 21 | high = mid 22 | return low 23 | 24 | 25 | if __name__ == '__main__': 26 | solution = Solution() 27 | print(solution.findPeakElement([1, 2, 1, 3, 5, 6, 4])) 28 | -------------------------------------------------------------------------------- /python/first_unique_character_in_a_string.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 10/4/17.""" 2 | """Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.""" 3 | 4 | class Solution(object): 5 | def firstUniqChar(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | frequency = {} 11 | for c in s: 12 | if c not in frequency: 13 | frequency[c] = 1 14 | else: 15 | frequency[c] += 1 16 | 17 | for i in range(len(s)): 18 | if frequency[s[i]] == 1: 19 | return i 20 | return -1 21 | -------------------------------------------------------------------------------- /python/flatten_2d_vector.py: -------------------------------------------------------------------------------- 1 | """Implement an iterator to flatten a 2d vector.""" 2 | 3 | 4 | class Vector2D(object): 5 | 6 | def __init__(self, vec2d): 7 | """ 8 | Initialize your data structure here. 9 | :type vec2d: List[List[int]] 10 | """ 11 | 12 | def get(): 13 | for row in vec2d: 14 | for col in row: 15 | yield col 16 | 17 | self.itr = iter(get()) 18 | self.curr = next(self.itr, None) 19 | 20 | def next(self): 21 | """ 22 | :rtype: int 23 | """ 24 | if self.hasNext(): 25 | p = self.curr 26 | self.curr = next(self.itr, None) 27 | return p 28 | 29 | def hasNext(self): 30 | """ 31 | :rtype: bool 32 | """ 33 | return self.curr is not None 34 | -------------------------------------------------------------------------------- /python/flatten_binary_tree_to_linked_list.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | import collections 3 | 4 | 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | 12 | class Solution: 13 | def flatten(self, root: TreeNode) -> None: 14 | """ 15 | Do not return anything, modify root in-place instead. 16 | """ 17 | queue = collections.deque() 18 | 19 | def pre_order(root): 20 | if not root: 21 | return 22 | queue.appendleft(root) 23 | pre_order(root.left) 24 | pre_order(root.right) 25 | 26 | pre_order(root) 27 | if len(queue) > 0: 28 | curr = queue.pop() 29 | while len(queue) > 0: 30 | curr.left = None 31 | if len(queue) > 0: 32 | curr.right = queue.pop() 33 | curr = curr.right 34 | 35 | 36 | -------------------------------------------------------------------------------- /python/flipping_an_image.py: -------------------------------------------------------------------------------- 1 | """Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. 2 | To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] 3 | horizontally results in [0, 1, 1].""" 4 | 5 | 6 | class Solution(object): 7 | def flipAndInvertImage(self, A): 8 | """ 9 | :type A: List[List[int]] 10 | :rtype: List[List[int]] 11 | """ 12 | for i in range(len(A)): 13 | n = len(A[0]) - 1 14 | for j in range(len(A[i]) // 2): 15 | A[i][j], A[i][n] = A[i][n], A[i][j] 16 | n -= 1 17 | for i in range(len(A)): 18 | for j in range(len(A[i])): 19 | if A[i][j] == 0: 20 | A[i][j] = 1 21 | else: 22 | A[i][j] = 0 23 | # print(A) 24 | 25 | 26 | if __name__ == '__main__': 27 | solution = Solution() 28 | print(solution.flipAndInvertImage([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]])) 29 | -------------------------------------------------------------------------------- /python/generate_parantheses.py: -------------------------------------------------------------------------------- 1 | """Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | For example, given n = 3, a solution set is: 3 | [ 4 | "((()))", 5 | "(()())", 6 | "(())()", 7 | "()(())", 8 | "()()()" 9 | ] 10 | """ 11 | 12 | 13 | class Solution: 14 | def generateParenthesis(self, n): 15 | """ 16 | :type n: int 17 | :rtype: List[str] 18 | """ 19 | res = [] 20 | 21 | def _helper(left, right, path): 22 | if left == 0 and right == 0: 23 | res.append(path[:]) 24 | return 25 | if right >= left: 26 | if left != 0: 27 | _helper(left - 1, right, path + '(') 28 | if right != 0: 29 | _helper(left, right - 1, path + ')') 30 | 31 | _helper(n - 1, n, "(") 32 | return res 33 | 34 | 35 | if __name__ == '__main__': 36 | solution = Solution() 37 | print(solution.generateParenthesis(2)) 38 | -------------------------------------------------------------------------------- /python/happy_number.py: -------------------------------------------------------------------------------- 1 | """Write an algorithm to determine if a number is "happy". 2 | 3 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by 4 | the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it 5 | loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 6 | 7 | Example: 19 is a happy number 8 | 9 | 12 + 92 = 82 10 | 82 + 22 = 68 11 | 62 + 82 = 100 12 | 12 + 02 + 02 = 1""" 13 | 14 | 15 | class Solution: 16 | def isHappy(self, n): 17 | """ 18 | :type n: int 19 | :rtype: bool 20 | """ 21 | check = set() 22 | while 1: 23 | total = 0 24 | for c in str(n): 25 | total += int(c) ** 2 26 | if total == 1: 27 | return True 28 | elif total in check: 29 | return False 30 | else: 31 | check.add(total) 32 | n = total 33 | 34 | 35 | if __name__ == '__main__': 36 | solution = Solution() 37 | print(solution.isHappy(19)) 38 | -------------------------------------------------------------------------------- /python/house_robber.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/8/17.""" 2 | """You are a professional robber planning to rob houses along a street. Each house has a certain amount of money 3 | stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system 4 | connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 5 | 6 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount 7 | of money you can rob tonight without alerting the police.""" 8 | 9 | 10 | class Solution(object): 11 | def rob(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: int 15 | """ 16 | if not nums or len(nums) == 0: 17 | return 0 18 | memo = [0 for _ in range(len(nums) + 1)] 19 | memo[0] = 0 20 | memo[1] = nums[0] 21 | for i in range(2, len(memo)): 22 | memo[i] = max(memo[i-1], memo[i-2] + nums[i - 1]) 23 | return memo[-1] 24 | 25 | 26 | if __name__ == '__main__': 27 | solution = Solution() 28 | print(solution.rob([2, 1, 1, 2])) 29 | -------------------------------------------------------------------------------- /python/hr.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | def isPrime(n): 5 | if n <= 1: 6 | return 0 7 | for x in range(2, sqrt(n)): 8 | if not n % x == 0: 9 | return x 10 | else: 11 | return 0 12 | 13 | 14 | def maxDifference(arr): 15 | max_diff = -1 16 | max_right = arr[len(arr) - 1] 17 | 18 | for i in range(len(arr) - 2, -1, -1): 19 | if arr[i] > max_right: 20 | max_right = arr[i] 21 | else: 22 | diff = max_right - arr[i] 23 | if diff > max_diff: 24 | max_diff = diff 25 | return max_diff 26 | 27 | 28 | def schedule(tasks, cooldown): 29 | res = [tasks[0]] 30 | for i in range(1, len(tasks)): 31 | j, k = 0, i+1 32 | while j < cooldown and k < len(tasks): 33 | if tasks[k] != tasks[i]: 34 | res.append(tasks[k]) 35 | else: 36 | res.append('.') 37 | k += 1 38 | j += 1 39 | return ''.join(res) 40 | 41 | 42 | if __name__ == '__main__': 43 | print(schedule('aba', 2)) 44 | print(schedule('abca', 2)) 45 | print(schedule('aabb', 2)) 46 | print(schedule('acbab', 2)) 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /python/inorder_successor_ii.py: -------------------------------------------------------------------------------- 1 | # Definition for a Node. 2 | class Node: 3 | def __init__(self, val, left, right, parent): 4 | self.val = val 5 | self.left = left 6 | self.right = right 7 | self.parent = parent 8 | 9 | 10 | class Solution: 11 | def inorderSuccessor(self, node: 'Node') -> 'Node': 12 | if node.right: 13 | node = node.right 14 | while node.left: 15 | node = node.left 16 | return node 17 | while node.parent and node.parent.left != node: 18 | node = node.parent 19 | return node.parent 20 | 21 | -------------------------------------------------------------------------------- /python/intersection_of_two_arrays_ii.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]: 5 | dic = Counter(nums1) 6 | res = [] 7 | for num in nums2: 8 | if num in dic and dic[num] > 0: 9 | res.append(num) 10 | dic[num] -= 1 11 | return res 12 | -------------------------------------------------------------------------------- /python/is_subsequence.py: -------------------------------------------------------------------------------- 1 | """Given a string s and a string t, check if s is subsequence of t. 2 | You may assume that there is only lower case English letters in both s and t. t is potentially a very 3 | long (length ~= 500,000) string, and s is a short string (<=100). 4 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of 5 | the characters without disturbing the relative positions of the remaining characters. 6 | (ie, "ace" is a subsequence of "abcde" while "aec" is not).""" 7 | 8 | 9 | class Solution(object): 10 | def isSubsequence(self, s, t): 11 | """ 12 | :type s: str 13 | :type t: str 14 | :rtype: bool 15 | """ 16 | if len(s) == 0: 17 | return True 18 | i, j = 0, 0 19 | while j < len(t): 20 | if s[i] == t[j]: 21 | i += 1 22 | if i == len(s): 23 | return True 24 | j += 1 25 | return False 26 | -------------------------------------------------------------------------------- /python/k_similar_strings.py: -------------------------------------------------------------------------------- 1 | """Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A 2 | exactly K times so that the resulting string equals B. 3 | Given two anagrams A and B, return the smallest K for which A and B are K-similar. 4 | Example 1: 5 | Input: A = "ab", B = "ba" 6 | Output: 1 7 | 8 | Example 2: 9 | Input: A = "abc", B = "bca" 10 | Output: 2 11 | 12 | Example 3: 13 | Input: A = "abac", B = "baca" 14 | Output: 2 15 | """ 16 | from collections import deque 17 | 18 | 19 | class Solution(object): 20 | def kSimilarity(self, A, B): 21 | """ 22 | :type A: str 23 | :type B: str 24 | :rtype: int 25 | """ 26 | queue = deque() 27 | queue.appendleft(A) 28 | while len(queue) > 0: 29 | pass 30 | -------------------------------------------------------------------------------- /python/kth_largest_element_in_an_array.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/13/17.""" 2 | """Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, 3 | not the kth distinct element. 4 | 5 | For example, 6 | Given [3,2,1,5,6,4] and k = 2, return 5.""" 7 | import heapq 8 | 9 | class Solution(object): 10 | def findKthLargest(self, nums, k): 11 | """ 12 | :type nums: List[int] 13 | :type k: int 14 | :rtype: int 15 | """ 16 | queue = [] 17 | for num in nums: 18 | heapq.heappush(queue, num) 19 | return heapq.nlargest(k, queue)[-1] 20 | 21 | 22 | if __name__ == '__main__': 23 | solution = Solution() 24 | print(solution.findKthLargest([3, 2, 1, 5, 6, 4], 2)) 25 | -------------------------------------------------------------------------------- /python/largest_component_size_by_common_factor.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def largestComponentSize(self, A: [int]) -> int: 4 | parent = {c: c for c in A} 5 | 6 | def union(a, b): 7 | x = find(a) 8 | y = find(b) 9 | if x != y: 10 | parent[x] = y 11 | 12 | def find(item): 13 | if parent[item] == item: 14 | return item 15 | parent[item] = find(parent[item]) 16 | return parent[item] 17 | 18 | def common(a, b): 19 | for i in range(2, min(a, b)): 20 | if a % i == 0 and b % i == 0: 21 | return True 22 | return False 23 | 24 | for i in range(len(A)): 25 | for j in range(i+1, len(A)): 26 | if common(A[i], A[j]): 27 | union(A[i], A[j]) -------------------------------------------------------------------------------- /python/letter_case_permutation.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def letterCasePermutation(self, s: str) -> List[str]: 6 | n = len(s) 7 | results = [] 8 | def backtrack(i, sub): 9 | if i == n: 10 | results.append(sub) 11 | return 12 | curr = s[i].lower() 13 | backtrack(i+1, sub + curr) 14 | if curr.isalpha(): 15 | backtrack(i+1, sub + curr.upper()) 16 | 17 | backtrack(0, "") 18 | return results -------------------------------------------------------------------------------- /python/letter_combinations_of_a_phone_number.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/5/17.""" 2 | """Given a digit string, return all possible letter combinations that the number could represent.""" 3 | 4 | 5 | class Solution(object): 6 | def __init__(self): 7 | self.digit_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} 8 | 9 | def letterCombinations(self, digits): 10 | """ 11 | :type digits: str 12 | :rtype: List[str] 13 | """ 14 | if not digits: 15 | return [] 16 | result = set() 17 | 18 | def _helper(digits, path): 19 | if not digits: 20 | result.add(path) 21 | return 22 | curr, rest = digits[0], digits[1:] 23 | letters = self.digit_map[curr] 24 | for letter in letters: 25 | _helper(rest, path + letter) 26 | 27 | _helper(digits, '') 28 | return list(sorted(result)) 29 | 30 | 31 | if __name__ == '__main__': 32 | solution = Solution() 33 | print(solution.letterCombinations('23')) 34 | -------------------------------------------------------------------------------- /python/license_key_formatting.py: -------------------------------------------------------------------------------- 1 | """You are given a license key represented as a string S which consists only alphanumeric character and dashes. 2 | The string is separated into N+1 groups by N dashes. 3 | Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except 4 | for the first group which could be shorter than K, but still must contain at least one character. Furthermore, 5 | there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. 6 | Given a non-empty string S and a number K, format the string according to the rules described above.""" 7 | 8 | 9 | class Solution: 10 | def licenseKeyFormatting(self, S, K): 11 | """ 12 | :type S: str 13 | :type K: int 14 | :rtype: str 15 | """ 16 | chars = ''.join(S.split('-')).upper()[::-1] 17 | return '-'.join([chars[i:i + K] for i in range(0, len(chars), K)])[::-1] 18 | 19 | 20 | if __name__ == '__main__': 21 | solution = Solution() 22 | print(solution.licenseKeyFormatting("5F3Z-2e-9-w", 4)) 23 | print(solution.licenseKeyFormatting("2-5g-3-J", 2)) 24 | -------------------------------------------------------------------------------- /python/linked_list_components.py: -------------------------------------------------------------------------------- 1 | """We are given head, the head node of a linked list containing unique integer values. 2 | We are also given the list G, a subset of the values in the linked list. 3 | Return the number of connected components in G, where two values are connected if they appear consecutively in 4 | the linked list.""" 5 | 6 | 7 | # Definition for singly-linked list. 8 | class ListNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.next = None 12 | 13 | 14 | class Solution(object): 15 | def numComponents(self, head, G): 16 | """ 17 | :type head: ListNode 18 | :type G: List[int] 19 | :rtype: int 20 | """ 21 | check = set(i for i in G) 22 | -------------------------------------------------------------------------------- /python/longest_arithmetic_sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestArithSeqLength(self, A:[int]) -> int: 3 | pass 4 | 5 | 6 | if __name__ == '__main__': 7 | solution = Solution() 8 | print(solution.longestArithSeqLength([3, 6, 9, 12])) 9 | -------------------------------------------------------------------------------- /python/longest_consecutive_sequence.py: -------------------------------------------------------------------------------- 1 | """Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 2 | Your algorithm should run in O(n) complexity.""" 3 | 4 | 5 | class Solution: 6 | def longestConsecutive(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | visited = set() 12 | for num in nums: 13 | visited.add(num) 14 | 15 | max_len = 0 16 | for num in nums: 17 | if num - 1 not in visited: 18 | curr = 0 19 | item = num 20 | while item in visited: 21 | curr += 1 22 | item += 1 23 | max_len = max(max_len, curr) 24 | return max_len 25 | 26 | 27 | if __name__ == '__main__': 28 | solution = Solution() 29 | print(solution.longestConsecutive([100, 4, 200, 1, 3, 2])) 30 | -------------------------------------------------------------------------------- /python/longest_palindromic_subsequence.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/7/17.""" 2 | """Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length 3 | of s is 1000.""" 4 | 5 | 6 | class Solution(object): 7 | def longestPalindromeSubseq(self, s): 8 | """ 9 | :type s: str 10 | :rtype: int 11 | """ 12 | 13 | 14 | -------------------------------------------------------------------------------- /python/longest_palindromic_substring.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 3/23/17 as part of leetcode""" 2 | """Given a string s, find the longest palindromic substring in s. You may assume that the maximum 3 | length of s is 1000. 4 | Input: 'babad' 5 | Output: 'bab' 6 | Input: 'cbbd' 7 | Output: 'bb' 8 | """ 9 | 10 | 11 | class Solution(object): 12 | def longestPalindrome(self, s): 13 | """ 14 | :type s: str 15 | :rtype: str 16 | """ 17 | longest = '' 18 | for i in range(2 * len(s)): 19 | left = i // 2 20 | right = i // 2 + i % 2 21 | while left >= 0 and right < len(s) and s[left] == s[right]: 22 | sub = s[left:right + 1] 23 | if len(sub) > len(longest): 24 | longest = sub 25 | left -= 1 26 | right += 1 27 | return longest 28 | 29 | 30 | 31 | 32 | 33 | if __name__ == '__main__': 34 | solution = Solution() 35 | print(solution.longestPalindrome('babad')) 36 | -------------------------------------------------------------------------------- /python/longest_substring_with_at_most_2_distinct_characters.py: -------------------------------------------------------------------------------- 1 | """Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. 2 | """ 3 | from collections import OrderedDict 4 | 5 | 6 | class Solution(object): 7 | def lengthOfLongestSubstringTwoDistinct(self, s): 8 | """ 9 | :type s: str 10 | :rtype: int 11 | """ 12 | max_len = 0 13 | d = OrderedDict() 14 | j = 0 15 | for i in range(len(s)): 16 | d[s[i]] = d.get(s[i], 0) + 1 17 | while len(d) > 2: 18 | if d[s[j]] == 1: 19 | d.pop(s[j]) 20 | else: 21 | d[s[j]] -= 1 22 | j += 1 23 | curr = s[j:i + 1] 24 | max_len = max(len(curr), max_len) 25 | 26 | return max_len 27 | 28 | 29 | if __name__ == '__main__': 30 | solution = Solution() 31 | print(solution.lengthOfLongestSubstringTwoDistinct("ccaabbb")) 32 | -------------------------------------------------------------------------------- /python/lowest_common_ancestor.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/9/17.""" 2 | import collections 3 | 4 | """Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.""" 5 | 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | 13 | class Solution(object): 14 | def lowestCommonAncestor(self, root, p, q): 15 | if not root or root == p or root == q: 16 | return root 17 | left = self.lowestCommonAncestor(root.left, p, q) 18 | right = self.lowestCommonAncestor(root.right, p, q) 19 | if not left and not right: 20 | return None 21 | if not left: 22 | return right 23 | if not right: 24 | return left 25 | return root 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /python/magic_squares_in_a_grid.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/magic_squares_in_a_grid.py -------------------------------------------------------------------------------- /python/malware_spread_problem.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMalwareSpread(self, graph: [[int]], initial: [int]) -> int: 3 | parent = {c: c for c in range(len(graph))} 4 | 5 | def union(a, b): 6 | x = find(a) 7 | y = find(b) 8 | if x != y: 9 | parent[x] = y 10 | 11 | def find(item): 12 | if parent[item] == item: 13 | return item 14 | parent[item] = find(parent[item]) 15 | return parent[item] 16 | for i in range(0, len(initial)): 17 | for j in range(i+1, len(initial)): 18 | if graph[initial[i], initial[j]] == 1: 19 | union(initial[i], initial[j]) 20 | -------------------------------------------------------------------------------- /python/max_consecutive_ones_iii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestOnes(self, A: [int], K: int) -> int: 3 | zpos = [i for i in range(len(A)) if A[i] == 0] 4 | for i in range(len(zpos)): 5 | pass 6 | -------------------------------------------------------------------------------- /python/max_points_on_a_line.py: -------------------------------------------------------------------------------- 1 | from collections import Counter, defaultdict 2 | 3 | 4 | class Solution: 5 | def maxPoints(self, points: list[list[int]]) -> int: 6 | if not points or len(points) == 0: 7 | return 0 8 | points = [(point[0], point[1]) for point in points] 9 | repeated = Counter(points) 10 | points = list(set(points)) 11 | if len(points) < 3: 12 | return sum(repeated.values()) 13 | lines = {} 14 | 15 | def slope(p1, p2): 16 | if p1[1] == p2[1]: 17 | return 0 18 | return (p2[0] - p1[0])/(p2[1] - p1[1]) 19 | count = 0 20 | for i in range(len(points) - 1): 21 | lines[count] = [points[i], points[i+1]] 22 | j = 2 23 | while i+j < len(points): 24 | curr = points[i+j] 25 | if slope(points[i], points[i+1]) == slope(points[i], points[i+j]): 26 | lines[count].append(points[i+j]) 27 | j += 1 28 | count += 1 29 | 30 | 31 | #TODO: Incomplete -------------------------------------------------------------------------------- /python/maximum_binary_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def constructMaximumBinaryTree(self, nums: [int]) -> TreeNode: 11 | 12 | def construct(arr): 13 | if not arr or len(arr) == 0: 14 | return 15 | max_value = max(arr) 16 | max_index = arr.index(max_value) 17 | p = TreeNode(max_value) 18 | p.left = construct(arr[:max_index]) 19 | p.right = construct(arr[max_index + 1:]) 20 | return p 21 | return construct(nums) 22 | -------------------------------------------------------------------------------- /python/maximum_consecutive_ones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 3 | curr_window, max_window = 0, 0 4 | for i in range(len(nums)): 5 | if nums[i] == 1: 6 | curr_window += 1 7 | else: 8 | max_window = max(max_window, curr_window) 9 | curr_window = 0 10 | return max(max_window, curr_window) -------------------------------------------------------------------------------- /python/maximum_depth_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/8/17.""" 2 | """Given a binary tree, find its maximum depth. 3 | 4 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.""" 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.left = None 11 | # self.right = None 12 | 13 | 14 | class Solution(object): 15 | def maxDepth(self, root): 16 | """ 17 | :type root: TreeNode 18 | :rtype: int 19 | """ 20 | if root is None: 21 | return 0 22 | return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 23 | -------------------------------------------------------------------------------- /python/maximum_difference_between_node_ancestor.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def maxAncestorDiff(self, root: TreeNode) -> int: 11 | ans = [0] 12 | 13 | def dfs(node, a, b): 14 | if node: 15 | a, b = min(a, node.val), max(b, node.val) 16 | ans[0] = max(ans[0], b - a) 17 | dfs(node.left, a, b) 18 | dfs(node.right, a, b) 19 | dfs(root, root.val, root.val) 20 | return ans[0] 21 | -------------------------------------------------------------------------------- /python/maximum_length_of_pair_chain.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 10/8/17.""" 2 | """You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. 3 | Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed 4 | in this fashion. 5 | Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. 6 | You can select pairs in any order.""" 7 | 8 | 9 | class Solution(object): 10 | def findLongestChain(self, pairs): 11 | """ 12 | :type pairs: List[List[int]] 13 | :rtype: int 14 | """ 15 | sorted_pairs = sorted(pairs, key= lambda x:x[1]) 16 | if len(sorted_pairs) == 0: 17 | return 0 18 | curr = sorted_pairs[0][1] 19 | chain_len = 1 20 | for i, pair in enumerate(sorted_pairs): 21 | if curr < pair[0]: 22 | chain_len += 1 23 | curr = pair[1] 24 | return chain_len 25 | 26 | 27 | if __name__ == '__main__': 28 | solution = Solution() 29 | print(solution.findLongestChain([[1, 2], [2, 3], [3, 4]])) 30 | 31 | 32 | -------------------------------------------------------------------------------- /python/maximum_product_subarray.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/9/17.""" 2 | """Find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | For example, given the array [2,3,-2,4], 4 | the contiguous subarray [2,3] has the largest product = 6.""" 5 | import sys 6 | 7 | 8 | class Solution(object): 9 | def maxProduct(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | max_prod = min_prod = overall = nums[0] 15 | for i in range(1, len(nums)): 16 | if nums[i] < 0: 17 | max_prod, min_prod = min_prod, max_prod 18 | max_prod = max(nums[i], max_prod*nums[i]) 19 | min_prod = min(nums[i], min_prod*nums[i]) 20 | overall = max(overall, max_prod) 21 | return overall 22 | 23 | 24 | if __name__ == '__main__': 25 | solution = Solution() 26 | print(solution.maxProduct([-2])) 27 | 28 | -------------------------------------------------------------------------------- /python/maximum_size_subarray_sum_equals_k.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 3/8/17 as part of leetcode""" 2 | """Given an array nums and a target value k, find the maximum length of a subarray that sums to k. 3 | If there isn't one, return 0 instead.""" 4 | import sys 5 | 6 | class Solution(object): 7 | def maxSubArrayLen(self, nums, k): 8 | """ 9 | :type nums: List[int] 10 | :type k: int 11 | :rtype: int 12 | """ 13 | total = nums[0] 14 | cumulative_sum = [0 for _ in range(len(nums))] 15 | cumulative_sum[0] = nums[0] 16 | for i in range(1, len(nums)): 17 | total += cumulative_sum[i] 18 | cumulative_sum[i] = total 19 | 20 | i, j = 0, len(nums)-1 21 | while i < j: 22 | curr = nums[j] - nums[i] 23 | if curr < k: 24 | i += 1 25 | elif curr > k: 26 | j -= 1 27 | else: 28 | return j - i + 1 29 | return 0 30 | 31 | 32 | solution = Solution() 33 | print(solution.maxSubArrayLen([-2, -1, 2, 1], 1)) 34 | print(solution.maxSubArrayLen([1, -1, 5, -2, 3], 3)) 35 | -------------------------------------------------------------------------------- /python/maximum_subarray.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/31/17.""" 2 | """Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 5 | the contiguous subarray [4,-1,2,1] has the largest sum = 6.""" 6 | import sys 7 | 8 | 9 | class Solution(object): 10 | def maxSubArray(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: int 14 | """ 15 | curr_sum, max_sum = 0, -sys.maxsize 16 | for i in nums: 17 | curr_sum += i 18 | max_sum = max(curr_sum, max_sum) 19 | if curr_sum < 0: 20 | curr_sum = 0 21 | return max_sum 22 | 23 | 24 | if __name__ == '__main__': 25 | solution = Solution() 26 | print(solution.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) 27 | -------------------------------------------------------------------------------- /python/meeting_rooms.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/19/17.""" 2 | """Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), 3 | determine if a person could attend all meetings. 4 | 5 | For example, 6 | Given [[0, 30],[5, 10],[15, 20]], 7 | return false.""" 8 | import heapq 9 | 10 | # Definition for an interval. 11 | class Interval(object): 12 | def __init__(self, s=0, e=0): 13 | self.start = s 14 | self.end = e 15 | 16 | 17 | class Solution(object): 18 | def canAttendMeetings(self, intervals): 19 | """ 20 | :type intervals: List[Interval] 21 | :rtype: bool 22 | """ 23 | if not intervals or len(intervals) == 0: 24 | return True 25 | heap = [] 26 | intervals = sorted(intervals, key=lambda x: x.start) 27 | heapq.heappush(heap, intervals[0].end) 28 | for i in range(1, len(intervals)): 29 | if intervals[i].start >= heap[0]: 30 | heapq.heappop(heap) 31 | heapq.heappush(heap, intervals[i].end) 32 | return len(heap) == 1 33 | -------------------------------------------------------------------------------- /python/meeting_rooms_ii.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/6/17.""" 2 | """Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), 3 | find the minimum number of conference rooms required.""" 4 | import heapq 5 | 6 | 7 | class Interval(object): 8 | def __init__(self, s=0, e=0): 9 | self.start = s 10 | self.end = e 11 | 12 | 13 | class Solution(object): 14 | def minMeetingRooms(self, intervals): 15 | """ 16 | :type intervals: List[Interval] 17 | :rtype: int 18 | """ 19 | if not intervals or len(intervals) == 0: 20 | return 0 21 | queue = [] 22 | intervals = sorted(intervals, key=lambda x: x.start) 23 | heapq.heappush(queue, intervals[0].end) 24 | for i in range(1, len(intervals)): 25 | if intervals[i].start >= queue[0]: 26 | heapq.heappop(queue) 27 | heapq.heappush(queue, intervals[i].end) 28 | return len(queue) 29 | 30 | 31 | if __name__ == '__main__': 32 | solution = Solution() 33 | intervals = [Interval(s=0, e=30), Interval(s=5, e=10), Interval(s=15, e=20)] 34 | print(solution.minMeetingRooms(intervals)) 35 | -------------------------------------------------------------------------------- /python/merge_two_sorted_lists.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/8/17.""" 2 | """Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the 3 | nodes of the first two lists.""" 4 | 5 | # Definition for singly-linked list. 6 | 7 | 8 | class ListNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.next = None 12 | 13 | 14 | class Solution(object): 15 | def mergeTwoLists(self, l1, l2): 16 | """ 17 | :type l1: ListNode 18 | :type l2: ListNode 19 | :rtype: ListNode 20 | """ 21 | curr = head = ListNode(0) 22 | while l1 and l2: 23 | if l1.val < l2.val: 24 | curr.next = ListNode(l1.val) 25 | l1 = l1.next 26 | else: 27 | curr.next = ListNode(l2.val) 28 | l2 = l2.next 29 | curr = curr.next 30 | curr.next = l1 or l2 31 | return head.next 32 | 33 | -------------------------------------------------------------------------------- /python/min_cost_climbing_stairs.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def minCostClimbingStairs(self, cost: List[int]) -> int: 6 | if len(cost) == 1: 7 | return cost[0] 8 | dp = [0 for _ in range(len(cost))] 9 | dp[0] = cost[0] 10 | dp[1] = cost[1] 11 | for i in range(2, len(dp)): 12 | dp[i] = min(dp[i-1], dp[i-2]) + cost[i] 13 | return min(dp[-1], dp[-2]) 14 | -------------------------------------------------------------------------------- /python/minimum_absolute_difference_in_bst.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | import heapq 10 | import sys 11 | 12 | 13 | class Solution: 14 | def getMinimumDifference(self, root: TreeNode) -> int: 15 | 16 | heap = [] 17 | 18 | def dfs(node): 19 | if not node: 20 | return 21 | heapq.heappush(heap, node.val) 22 | dfs(node.left) 23 | dfs(node.right) 24 | 25 | dfs(root) 26 | diff = sys.maxsize 27 | res = heapq.nsmallest(len(heap), heap) 28 | for i in range(1, len(res)): 29 | diff = min(diff, res[i] - res[i - 1]) 30 | return diff 31 | 32 | 33 | solution = Solution() 34 | t = TreeNode(1) 35 | t.right = TreeNode(3) 36 | t.left = TreeNode(2) 37 | print(solution.getMinimumDifference(t)) 38 | -------------------------------------------------------------------------------- /python/minimum_distance_between_bst_nodes.py: -------------------------------------------------------------------------------- 1 | """Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any 2 | two different nodes in the tree.""" 3 | from typing import Optional 4 | 5 | # Definition for a binary tree node. 6 | class TreeNode: 7 | def __init__(self, val=0, left=None, right=None): 8 | self.val = val 9 | self.left = left 10 | self.right = right 11 | 12 | 13 | class Solution(object): 14 | def minDiffInBST(self, root: Optional[TreeNode]): 15 | """ 16 | :type root: TreeNode 17 | :rtype: int 18 | """ 19 | 20 | min_diff = float('inf') 21 | prev = float('-inf') 22 | 23 | def inorder(node): 24 | nonlocal min_diff, prev 25 | if not node: 26 | return 27 | inorder(node.left) 28 | if prev != float('-inf'): 29 | min_diff = min(min_diff, node.val - prev) 30 | prev = node.val 31 | inorder(node.right) 32 | 33 | inorder(root) 34 | return min_diff 35 | 36 | -------------------------------------------------------------------------------- /python/most_frequent_subtree_sum.py: -------------------------------------------------------------------------------- 1 | #Definition for a binary tree node. 2 | import collections 3 | 4 | 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | 12 | class Solution: 13 | def findFrequentTreeSum(self, root: TreeNode) -> list[int]: 14 | if not root: 15 | return [] 16 | 17 | def dfs(node): 18 | if not node: 19 | return 0 20 | s = node.val + dfs(node.left) + dfs(node.right) 21 | count[s] += 1 22 | return s 23 | count = collections.Counter() 24 | dfs(root) 25 | max_val = max(count.values()) 26 | return [s for s in count if count[s] == max_val] 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /python/move_zeroes.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 3/7/17 as part of leetcode""" 2 | 3 | """Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of 4 | the non-zero elements. 5 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].""" 6 | 7 | 8 | class Solution(object): 9 | def moveZeroes(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: void Do not return anything, modify nums in-place instead. 13 | """ 14 | 15 | j = 0 16 | for i in range(len(nums)): 17 | if nums[i] != 0: 18 | nums[i], nums[j] = nums[j], nums[i] 19 | j += 1 20 | 21 | if __name__ == '__main__': 22 | solution = Solution() 23 | nums = [0, 1, 0, 3, 12] 24 | print(solution.moveZeroes(nums)) 25 | -------------------------------------------------------------------------------- /python/moving_average_of_a_data_stream.py: -------------------------------------------------------------------------------- 1 | """Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.""" 2 | from collections import deque 3 | 4 | 5 | class MovingAverage(object): 6 | 7 | def __init__(self, size): 8 | """ 9 | Initialize your data structure here. 10 | :type size: int 11 | """ 12 | self.capacity = size 13 | self.size = 0 14 | self.queue = deque() 15 | self.total = 0 16 | 17 | def next(self, val): 18 | """ 19 | :type val: int 20 | :rtype: float 21 | """ 22 | if self.size < self.capacity: 23 | self.queue.appendleft(val) 24 | self.total += val 25 | self.size += 1 26 | return self.total / self.size 27 | 28 | else: 29 | p = self.queue.pop() 30 | self.total -= p 31 | self.queue.appendleft(val) 32 | self.total += val 33 | return self.total / self.size 34 | 35 | 36 | if __name__ == '__main__': 37 | m = MovingAverage(3) 38 | print(m.next(1)) 39 | print(m.next(10)) 40 | print(m.next(3)) 41 | print(m.next(5)) 42 | -------------------------------------------------------------------------------- /python/n_ary_tree_postorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | def preorder(self, root: 'Node') -> List[int]: 11 | def _helper(p, lst): 12 | if not p: 13 | return 14 | for child in p.children: 15 | _helper(child, lst) 16 | lst.append(p.val) 17 | res = [] 18 | _helper(root, res) 19 | return res 20 | -------------------------------------------------------------------------------- /python/n_ary_tree_preorder_traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | def preorder(self, root: 'Node') -> List[int]: 11 | def _helper(p, lst): 12 | if not p: 13 | return 14 | lst.append(p.val) 15 | for child in p.children: 16 | _helper(child, lst) 17 | 18 | res = [] 19 | _helper(root, res) 20 | return res 21 | -------------------------------------------------------------------------------- /python/n_th_tribonacci_number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def tribonacci(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | if n == 0: 8 | return 0 9 | if n == 1: 10 | return 1 11 | if n == 2: 12 | return 1 13 | dp = [0 for _ in range(n + 1)] 14 | dp[0] = 0 15 | dp[1] = 1 16 | dp[2] = 1 17 | for i in range(3, n + 1): 18 | dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] 19 | return dp[-1] 20 | -------------------------------------------------------------------------------- /python/next_closest_time.py: -------------------------------------------------------------------------------- 1 | """Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. 2 | There is no limit on how many times a digit can be reused. 3 | 4 | You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" 5 | are all invalid.""" 6 | 7 | 8 | class Solution: 9 | def nextClosestTime(self, time): 10 | """ 11 | :type time: str 12 | :rtype: str 13 | """ 14 | nums = {time[0], time[1], time[3], time[4]} 15 | times = set() 16 | for n1 in nums: 17 | for n2 in nums: 18 | for n3 in nums: 19 | for n4 in nums: 20 | if int(n1) * 10 + int(n2) < 24 and int(n3) * 10 + int(n4) < 60: 21 | times.add(n1 + n2 + ':' + n3 + n4) 22 | times = sorted(list(times)) 23 | return times[(times.index(time) + 1) % len(times)] 24 | 25 | 26 | if __name__ == '__main__': 27 | solution = Solution() 28 | print(solution.nextClosestTime('19:34')) 29 | -------------------------------------------------------------------------------- /python/number_of_boomerangs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfBoomerangs(self, points): 3 | """ 4 | :type points: List[List[int]] 5 | :rtype: int 6 | """ 7 | dist_map = {} 8 | for i in range(len(points)): 9 | a = points[i] 10 | for j in range(len(points)): 11 | if i != j: 12 | b = points[j] 13 | d = self.distance(a, b) 14 | if d in dist_map: 15 | dist_map[d] += 1 16 | else: 17 | dist_map[d] = 0 18 | 19 | ans = 0 20 | for k, v in dist_map.items(): 21 | ans += v 22 | return ans 23 | 24 | def distance(self, a, b): 25 | return (b[0] - a[0]) ^ 2 + (b[1] - a[1]) ^ 2 26 | 27 | 28 | if __name__ == '__main__': 29 | solution = Solution() 30 | print(solution.numberOfBoomerangs([[0,0],[1,0],[2,0]])) -------------------------------------------------------------------------------- /python/one_edit_distance.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/17/17.""" 2 | """Given two strings S and T, determine if they are both one edit distance apart.""" 3 | 4 | 5 | class Solution(object): 6 | 7 | def isOneEditDistance(self, s, t): 8 | """ 9 | :type s: str 10 | :type t: str 11 | :rtype: bool 12 | """ 13 | if s is None and t is None or len(s) == len(t) == 0 or s == t: 14 | return False 15 | return self.oneDel(s, t) or self.oneModify(s, t) 16 | 17 | def oneDel(self, s, t): 18 | if abs(len(s) - len(t)) > 1: 19 | return False 20 | longer = s if len(s) > len(t) else t 21 | shorter = s if longer == t else t 22 | for i in range(len(longer)): 23 | reduced = longer[:i] + longer[i+1:] 24 | if reduced == shorter: 25 | return True 26 | return False 27 | 28 | def oneModify(self, s, t): 29 | if len(s) != len(t): 30 | return False 31 | i, count = 0, 0 32 | while i < len(s): 33 | if s[i] != t[i]: 34 | count += 1 35 | i += 1 36 | return count <= 1 37 | -------------------------------------------------------------------------------- /python/outliers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/outliers/__init__.py -------------------------------------------------------------------------------- /python/outliers/cartesian_tree.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/13/17.""" 2 | """You're given an array as an input, form a binary tree with the following characteristics, 3 | 1. Should satisfy binary heap property at every node, thus the value if the node should be less than both its children. 4 | 2. An inorder traversal should return the array.""" 5 | 6 | import sys 7 | 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | class Solution: 15 | def buildTree(self, arr): 16 | """ 17 | :type list 18 | :rtype: TreeNode 19 | """ 20 | if len(arr) == 0: 21 | return None 22 | index = self.find_min_index(arr) 23 | root = TreeNode(arr[index]) 24 | root.left = self.buildTree(arr[:index]) 25 | root.right = self.buildTree(arr[index:]) 26 | return root 27 | 28 | def find_min_index(self, arr): 29 | min_index, min_val = -1, sys.maxsize 30 | for i, v in enumerate(arr): 31 | if v < min_val: 32 | min_index, min_val = i, v 33 | return min_index 34 | 35 | -------------------------------------------------------------------------------- /python/outliers/detect_loop_in_singly_linked_list.py: -------------------------------------------------------------------------------- 1 | """You're given a singly linked list, return the node at which the loop starts. If there's no loop in the linked 2 | list return null""" 3 | 4 | 5 | class Solution: 6 | def findStartOfLoop(self, head): 7 | slow = fast = head 8 | while slow and fast and fast.next: 9 | slow = slow.next 10 | fast = fast.next.next 11 | if slow == fast: 12 | break 13 | slow = head 14 | while slow and fast: 15 | slow = slow.next 16 | fast = fast.next 17 | if slow == fast: 18 | return slow 19 | return None 20 | -------------------------------------------------------------------------------- /python/outliers/duplicate_users.py: -------------------------------------------------------------------------------- 1 | # Input: List(set(1,2,3), set(4,5,6), set(7,8), set(8,2)) 2 | # ouput: List(set(1,2,3,7,8), set(4,5,6)) 3 | 4 | 5 | def find_duplicate_users(arr: list) -> list: 6 | result = [arr[0]] 7 | trigger = len(arr) 8 | 9 | while True: 10 | arr = result[:] 11 | if len(arr) != trigger: 12 | trigger = len(arr) 13 | else: 14 | break 15 | result = [arr[0]] 16 | for i in range(1, len(arr)): 17 | for k in result: 18 | for j in (arr[i]): 19 | if j in k: 20 | k.add(arr[i]) 21 | break 22 | result.append(i) 23 | return arr 24 | 25 | 26 | result = [(1, 2, 3), (4, 5, 6), (7, 8, 2)] -------------------------------------------------------------------------------- /python/outliers/find_all_permutations_of_string.py: -------------------------------------------------------------------------------- 1 | """Find all permutations of a string and return them in a sorted order.""" 2 | 3 | 4 | class Solution: 5 | def permutations(self, s): 6 | result = [] 7 | self.helper('', s, result) 8 | return len(list(sorted(result))) 9 | 10 | def helper(self, prefix, suffix, arr): 11 | if not suffix: 12 | arr.append(prefix) 13 | return 14 | for i in range(len(suffix)): 15 | self.helper(suffix[i]+prefix, suffix[:i]+suffix[i+1:], arr) 16 | 17 | 18 | if __name__ == '__main__': 19 | solution = Solution() 20 | print(solution.permutations('abcde')) -------------------------------------------------------------------------------- /python/outliers/find_files_with_same_content.py: -------------------------------------------------------------------------------- 1 | """Write a function that takes a path and finds all files in that directory which have the exact same content.""" 2 | 3 | 4 | class Solution: 5 | def findFiles(self, path): 6 | pass 7 | -------------------------------------------------------------------------------- /python/outliers/find_the_n_fibonacci_number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findFibonacci(self, n): 3 | memo = [0 for _ in range(n)] 4 | memo[1] = 1 5 | for i in range(2, len(memo)): 6 | memo[i] = memo[i-1] + memo[i-2] 7 | return memo[-1] 8 | -------------------------------------------------------------------------------- /python/outliers/infer_spaces.py: -------------------------------------------------------------------------------- 1 | """Detect the most likely words from a text without spaces and a given list of words. 2 | Example 3 | Text: filesaveas 4 | Words: [files, file, save, as] 5 | Solution: file save as 6 | 7 | Text: tomorrowneverdies 8 | Words: [tom, tomorrow, row, ever, never, die, dies] 9 | Solution: tomorrow never dies 10 | 11 | Assume each text has only one unique split. 12 | """ 13 | 14 | 15 | class Solution: 16 | def infer_spaces(self, text, words): 17 | pass 18 | -------------------------------------------------------------------------------- /python/outliers/longest_subsequence_less_than_target.py: -------------------------------------------------------------------------------- 1 | """Find the length of longest contiguous subsequence in an array which has a sum less than or equal to a given target 2 | Ex- 1: 3 | arr = [8, 3, 7, 4, 1, 6, 5], target = 16 4 | In this case the answer is 4 5 | 3, 7, 4, 1 and 4, 1, 6, 5 both satisfy the condition and both are 4 elements long. 6 | 7 | """ 8 | 9 | 10 | def longest_subsequence(arr, target): 11 | total, max_length = 0, 0 12 | j = 0 13 | for i in range(len(arr)): 14 | total += arr[i] 15 | while total > target: 16 | total -= arr[j] 17 | j += 1 18 | max_length = max(i - j + 1, max_length) 19 | return max_length 20 | 21 | print(longest_subsequence([8, 3, 7, 4, 1, 6, 5], 16)) 22 | -------------------------------------------------------------------------------- /python/outliers/number_of_paths.py: -------------------------------------------------------------------------------- 1 | """Given a matrix of size n X m find the number of unique paths that start from 0,0 of the matrix and end 2 | at n-1,m-1 if you can only move RIGHT and DOWN.""" 3 | 4 | 5 | class Solution: 6 | def numPaths(self, n, m): 7 | memo = [[0 for _ in range(m)] for _ in range(n)] 8 | 9 | for i in range(len(memo)): 10 | memo[i][0] = 1 11 | 12 | for i in range(len(memo[0])): 13 | memo[0][i] = 1 14 | 15 | for i in range(1, len(memo)): 16 | for j in range(1, len(memo[0])): 17 | memo[i][j] = memo[i-1][j] + memo[i][j-1] 18 | 19 | return memo[-1][-1] 20 | 21 | 22 | if __name__ == '__main__': 23 | solution = Solution() 24 | print(solution.numPaths(2, 3)) -------------------------------------------------------------------------------- /python/outliers/optimal_component_cost.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | class Solution: 5 | def minimumTime(numOfParts, parts): 6 | heap = [] 7 | for item in parts: 8 | heapq.heappush(heap, item) 9 | result = 0 10 | while len(heap) > 1: 11 | first = heapq.heappop(heap) 12 | second = heapq.heappop(heap) 13 | total = first + second 14 | result += total 15 | heapq.heappush(heap, total) 16 | 17 | return result 18 | 19 | solution = Solution() 20 | print(solution.minimumTime(4, [8, 4, 6, 12])) 21 | 22 | -------------------------------------------------------------------------------- /python/outliers/optimal_utilization.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def optimalUtilization(deviceCapacity, foregroundAppList, backgroundAppList): 3 | result = {} 4 | 5 | for i in range(len(foregroundAppList)): 6 | for j in range(len(backgroundAppList)): 7 | utilization = foregroundAppList[i][1] + backgroundAppList[j][1] 8 | if utilization <= deviceCapacity: 9 | result[(foregroundAppList[i][0], backgroundAppList[j][0])] = utilization 10 | 11 | try: 12 | maximum = max(result.values()) 13 | except ValueError as v: 14 | return [[]] 15 | return [list(key) for key, value in result.items() if value == maximum] 16 | 17 | 18 | solution = Solution() 19 | print(solution.optimalUtilization(7, [[1, 2], [2, 4], [3, 6]], [[1, 2]])) 20 | print(solution.optimalUtilization(10, [[1, 3], [2, 5], [3, 7], [4, 10]], [[1, 2], [2, 3], [3, 4], [4, 5]])) 21 | print(solution.optimalUtilization(16, [[2, 7], [3, 14]], [[2, 10], [3, 14]])) 22 | -------------------------------------------------------------------------------- /python/outliers/second_largest_element_in_a_bst.py: -------------------------------------------------------------------------------- 1 | """Find the second largest element in a binary search tree.""" 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val): 6 | self.val = val 7 | self.left = None 8 | self.right = None 9 | 10 | 11 | class Solution: 12 | def findSecondLargestElement(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | if not root.right.left and not root.right.right: 18 | return root 19 | self.findSecondLargestElement(root.right) 20 | -------------------------------------------------------------------------------- /python/outliers/stack_server.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | class Stack: 5 | def __init__(self, capacity): 6 | self.stack = [] 7 | self.capacity = capacity 8 | self.lock = threading.Lock() 9 | self.buffer_not_full = threading.Condition(self.lock) 10 | self.buffer_not_empty = threading.Condition(self.lock) 11 | 12 | def push(self, item): 13 | with self.lock: 14 | while len(self.stack) == self.capacity: 15 | self.buffer_not_full.wait() 16 | self.stack.append(item) 17 | self.buffer_not_empty.notify_all() 18 | 19 | def pop(self): 20 | with self.lock: 21 | while len(self.stack) == 0: 22 | self.buffer_not_empty.wait() 23 | item = self.stack.pop() 24 | self.buffer_not_full.notify_all() 25 | return item 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /python/paint_fence.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/30/17.""" 2 | """There is a fence with n posts, each post can be painted with one of the k colors. 3 | You have to paint all the posts such that no more than two adjacent fence posts have the same color. 4 | Return the total number of ways you can paint the fence.""" 5 | 6 | 7 | class Solution(object): 8 | def numWays(self, n, k): 9 | """ 10 | :type n: int 11 | :type k: int 12 | :rtype: int 13 | """ 14 | 15 | -------------------------------------------------------------------------------- /python/palindrome_number.py: -------------------------------------------------------------------------------- 1 | """Determine whether an integer is a palindrome. Do this without extra space.""" 2 | 3 | class Solution(object): 4 | def isPalindrome(self, x): 5 | """ 6 | :type x: int 7 | :rtype: bool 8 | """ 9 | return str(x) == str(x)[::-1] 10 | -------------------------------------------------------------------------------- /python/palindrome_permutation.py: -------------------------------------------------------------------------------- 1 | """Given a string, determine if a permutation of the string could form a palindrome. 2 | For example, 3 | "code" -> False, "aab" -> True, "carerac" -> True.""" 4 | 5 | 6 | class Solution: 7 | def canPermutePalindrome(self, s): 8 | """ 9 | :type s: str 10 | :rtype: bool 11 | """ 12 | check = set() 13 | for c in s: 14 | if c in check: 15 | check.remove(c) 16 | else: 17 | check.add(c) 18 | return len(check) <= 1 19 | -------------------------------------------------------------------------------- /python/palindromic_substring.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/3/17.""" 2 | """Given a string, your task is to count how many palindromic substrings in this string. 3 | 4 | The substrings with different start indexes or end indexes are counted as different substrings even they consist 5 | of same characters.""" 6 | #TODO: Not passing all test cases 7 | 8 | 9 | class Solution(object): 10 | def countSubstrings(self, s): 11 | """ 12 | :type s: str 13 | :rtype: int 14 | """ 15 | ans = 0 16 | for i in range(2*len(s)): 17 | left = i//2 18 | right = i//2 + i % 2 19 | while left >= 0 and right < len(s) and s[left] == s[right]: 20 | ans += 1 21 | left -= 1 22 | right += 1 23 | return ans 24 | 25 | 26 | if __name__ == '__main__': 27 | solution = Solution() 28 | print(solution.countSubstrings('fdsklf')) -------------------------------------------------------------------------------- /python/partition_equal_subset_sum.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 6/6/17.""" -------------------------------------------------------------------------------- /python/path_sum_iii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def __init__(self): 11 | self.num_paths = 0 12 | 13 | def pathSum(self, root: TreeNode, sum: int) -> int: 14 | self.dfs(root, sum) 15 | return self.num_paths 16 | 17 | def dfs(self, node, target): 18 | if not node: 19 | return 20 | self.find_path(node, target) 21 | self.dfs(node.left, target) 22 | self.dfs(node.right, target) 23 | 24 | 25 | def find_path(self, node, target): 26 | if not node: 27 | return 28 | if node.val == target: 29 | self.num_paths += 1 30 | self.find_path(node.left, target - node.val) 31 | self.find_path(node.right, target - node.val) 32 | 33 | 34 | -------------------------------------------------------------------------------- /python/peak_index_in_a_mountain_array.py: -------------------------------------------------------------------------------- 1 | """Let's call an array A a mountain if the following properties hold: 2 | 3 | A.length >= 3 4 | There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 5 | Given an array that is definitely a mountain, return any i such that 6 | A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 7 | 8 | Example 1: 9 | Input: [0,1,0] 10 | Output: 1 11 | 12 | Example 2: 13 | Input: [0,2,1,0] 14 | Output: 1 15 | """ 16 | 17 | 18 | class Solution(object): 19 | def peakIndexInMountainArray(self, A): 20 | """ 21 | :type A: List[int] 22 | :rtype: int 23 | """ 24 | low, high = 0, len(A) - 1 25 | while low <= high: 26 | mid = low + (high - low) // 2 27 | if A[mid - 1] < A[mid] < A[mid + 1]: 28 | low = mid + 1 29 | elif A[mid - 1] > A[mid] > A[mid + 1]: 30 | high = mid - 1 31 | else: 32 | return mid 33 | return -1 34 | 35 | 36 | if __name__ == '__main__': 37 | solution = Solution() 38 | print(solution.peakIndexInMountainArray([3, 4, 5, 1])) 39 | -------------------------------------------------------------------------------- /python/permutations.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/8/17.""" 2 | """Given a collection of distinct numbers, return all possible permutations.""" 3 | 4 | 5 | class Solution(object): 6 | def permute(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: List[List[int]] 10 | """ 11 | result = [] 12 | self.helper(nums, 0, result) 13 | return result 14 | 15 | def helper(self, nums, start, results): 16 | if start == len(nums): 17 | results.append(nums[:]) 18 | return 19 | for i in range(start, len(nums)): 20 | nums[i], nums[start] = nums[start], nums[i] 21 | self.helper(nums, start+1, results) 22 | nums[i], nums[start] = nums[start], nums[i] 23 | 24 | 25 | if __name__ == '__main__': 26 | solution = Solution() 27 | print(solution.permute([1, 2, 3])) 28 | -------------------------------------------------------------------------------- /python/plus_one.py: -------------------------------------------------------------------------------- 1 | """Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 2 | You may assume the integer do not contain any leading zero, except the number 0 itself. 3 | The digits are stored such that the most significant digit is at the head of the list.""" 4 | 5 | 6 | class Solution(object): 7 | def plusOne(self, digits): 8 | """ 9 | :type digits: List[int] 10 | :rtype: List[int] 11 | """ 12 | res = digits[:] 13 | carry = 1 14 | for i in range(len(digits) - 1, -1, -1): 15 | val = digits[i] + carry 16 | carry, val = divmod(val, 10) 17 | res[i] = val 18 | if i == 0 and carry > 0: 19 | res.insert(0, carry) 20 | return res 21 | 22 | 23 | if __name__ == '__main__': 24 | solution = Solution() 25 | print(solution.plusOne([9, 9])) 26 | -------------------------------------------------------------------------------- /python/positions_of_large_groups.py: -------------------------------------------------------------------------------- 1 | """In a string S of lowercase letters, these letters form consecutive groups of the same character. 2 | For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy". 3 | Call a group large if it has 3 or more characters. We would like the starting and ending positions of every 4 | large group. 5 | The final answer should be in lexicographic order. 6 | """ 7 | 8 | 9 | class Solution(object): 10 | def largeGroupPositions(self, S): 11 | """ 12 | :type S: str 13 | :rtype: List[List[int]] 14 | """ 15 | -------------------------------------------------------------------------------- /python/pow_x_n.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/30/17.""" 2 | """Implement pow(x, n).""" 3 | 4 | 5 | class Solution(object): 6 | def myPow(self, x, n): 7 | """ 8 | :type x: float 9 | :type n: int 10 | :rtype: float 11 | """ 12 | if n == 0: 13 | return 1 14 | if n < 0: 15 | return 1 / self.myPow(x, -n) 16 | if n % 2 == 0: 17 | return self.myPow(x * x, n/2) 18 | else: 19 | return self.myPow(x, n - 1) * x 20 | 21 | -------------------------------------------------------------------------------- /python/power_of_three.py: -------------------------------------------------------------------------------- 1 | """Given an integer, write a function to determine if it is a power of three.""" 2 | 3 | 4 | class Solution(object): 5 | def isPowerOfThree(self, n): 6 | """ 7 | :type n: int 8 | :rtype: bool 9 | """ 10 | if n <= 0 or n > 1162261467: 11 | return False 12 | return 1162261467 % n == 0 13 | 14 | 15 | if __name__ == '__main__': 16 | solution = Solution() 17 | print(solution.isPowerOfThree(45)) 18 | -------------------------------------------------------------------------------- /python/power_of_two.py: -------------------------------------------------------------------------------- 1 | """Given an integer, write a function to determine if it is a power of two.""" 2 | 3 | 4 | class Solution(object): 5 | def isPowerOfTwo(self, n): 6 | """ 7 | :type n: int 8 | :rtype: bool 9 | """ 10 | if n == 1: 11 | return True 12 | num = 1 13 | while num < n: 14 | num *= 2 15 | if n / num == 1: 16 | return True 17 | return False 18 | 19 | 20 | if __name__ == '__main__': 21 | solution = Solution() 22 | print(solution.isPowerOfTwo(4)) 23 | -------------------------------------------------------------------------------- /python/print_foobar_alternately.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | class FooBar: 5 | def __init__(self, n): 6 | self.n = n 7 | self.trigger = 0 8 | self.lock = threading.Lock() 9 | self.foo_not_printed = threading.Condition(lock=self.lock) 10 | self.bar_not_printed = threading.Condition(lock=self.lock) 11 | 12 | def foo(self, printFoo: 'Callable[[], None]') -> None: 13 | 14 | for i in range(self.n): 15 | # printFoo() outputs "foo". Do not change or remove this line. 16 | self.lock.acquire() 17 | while self.trigger != 0: 18 | self.bar_not_printed.wait() 19 | printFoo() 20 | self.trigger = 1 21 | self.foo_not_printed.notify_all() 22 | self.lock.release() 23 | 24 | def bar(self, printBar: 'Callable[[], None]') -> None: 25 | 26 | for i in range(self.n): 27 | # printBar() outputs "bar". Do not change or remove this line. 28 | self.lock.acquire() 29 | while self.trigger != 1: 30 | self.foo_not_printed.wait() 31 | printBar() 32 | self.trigger = 0 33 | self.bar_not_printed.notify_all() 34 | self.lock.release() -------------------------------------------------------------------------------- /python/print_in_order.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | class Foo: 5 | def __init__(self): 6 | self.lock = threading.Lock() 7 | self.first_completed = threading.Condition(lock=self.lock) 8 | self.second_completed = threading.Condition(lock=self.lock) 9 | self.counter = 0 10 | 11 | def first(self, printFirst: 'Callable[[], None]') -> None: 12 | with self.lock: 13 | printFirst() 14 | self.counter += 1 15 | self.first_completed.notify_all() 16 | 17 | def second(self, printSecond: 'Callable[[], None]') -> None: 18 | with self.lock: 19 | while self.counter != 1: 20 | self.first_completed.wait() 21 | printSecond() 22 | self.counter += 1 23 | self.second_completed.notify_all() 24 | 25 | def third(self, printThird: 'Callable[[], None]') -> None: 26 | with self.lock: 27 | while self.counter != 2: 28 | self.second_completed.wait() 29 | printThird() 30 | -------------------------------------------------------------------------------- /python/ransom_note.py: -------------------------------------------------------------------------------- 1 | """Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function 2 | that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 3 | Each letter in the magazine string can only be used once in your ransom note. 4 | You may assume that both strings contain only lowercase letters. 5 | canConstruct("a", "b") -> false 6 | canConstruct("aa", "ab") -> false 7 | canConstruct("aa", "aab") -> true""" 8 | import collections 9 | 10 | class Solution: 11 | def canConstruct(self, ransomNote, magazine): 12 | """ 13 | :type ransomNote: str 14 | :type magazine: str 15 | :rtype: bool 16 | """ 17 | count_map = collections.Counter(magazine) 18 | for i,v in enumerate(ransomNote): 19 | if v not in count_map or count_map[v] <= 0: 20 | return False 21 | count_map[v] -= 1 22 | return True 23 | 24 | if __name__ == '__main__': 25 | solution = Solution() 26 | print(solution.canConstruct('aa', 'aab')) 27 | print(solution.canConstruct('a', 'b')) 28 | print(solution.canConstruct('aa', 'ab')) 29 | -------------------------------------------------------------------------------- /python/read_n_characters_given_read_4_ii.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/11/17.""" 2 | """The API: int read4(char *buf) reads 4 characters at a time from a file. 3 | 4 | The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters 5 | left in the file. 6 | By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. 7 | 8 | Note: 9 | The read function may be called multiple times.""" 10 | 11 | 12 | # The read4 API is already defined for you. 13 | # @param buf, a list of characters 14 | # @return an integer 15 | def read4(buf): 16 | pass 17 | 18 | class Solution(object): 19 | def read(self, buf, n): 20 | """ 21 | :type buf: Destination buffer (List[str]) 22 | :type n: Maximum number of characters to read (int) 23 | :rtype: The number of characters read (int) 24 | """ 25 | i = 0 26 | while i <= n: 27 | buf4 = [] 28 | read = read4(buf4) 29 | buf.extend(buf4) 30 | i += read 31 | -------------------------------------------------------------------------------- /python/read_n_chars_given_read_4.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/18/17.""" 2 | """The API: int read4(char *buf) reads 4 characters at a time from a file. 3 | The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters 4 | left in the file. 5 | By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. 6 | 7 | Note: 8 | The read function will only be called once for each test case.""" 9 | 10 | 11 | # The read4 API is already defined for you. 12 | # @param buf, a list of characters 13 | # @return an integer 14 | 15 | #TODO:Not passing a few tests 16 | 17 | def read4(buf): 18 | pass 19 | 20 | class Solution(object): 21 | def read(self, buf, n): 22 | """ 23 | :type buf: Destination buffer (List[str]) 24 | :type n: Maximum number of characters to read (int) 25 | :rtype: The number of characters read (int) 26 | """ 27 | i = 0 28 | buf4 = [''] * 4 29 | while True: 30 | num_bytes = read4(buf4) 31 | for i, v in enumerate(buf4): 32 | buf[i] = v 33 | i += num_bytes 34 | if num_bytes < 4 or i == n: 35 | return i 36 | -------------------------------------------------------------------------------- /python/recover_a_tree_from_preorder_traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | import re 10 | 11 | class Solution: 12 | def recoverFromPreorder(self, S: str) -> TreeNode: 13 | tokens = [i for i in re.split(r'(\d+|\W+)', S) if i] 14 | itr = iter(tokens) 15 | def recover_tree(arr, i): 16 | item = next(arr, None) 17 | 18 | 19 | 20 | 21 | solution = Solution() 22 | solution.recoverFromPreorder("1-2--3--4-5--6--7") -------------------------------------------------------------------------------- /python/regex/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/regex/README.md -------------------------------------------------------------------------------- /python/regex/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/regex/__init__.py -------------------------------------------------------------------------------- /python/regex/address_book.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | with open("data/names.txt") as file: 4 | data = file.read() 5 | # print(data) 6 | # print(re.match(r'Love', data)) 7 | # print(re.search(r'Kenneth', data)) 8 | print(re.findall(r'\w*,\s\w+', data)) 9 | print(re.findall(r'\(?\d{3}\)?\s?\d{3}-\d{4}', data)) 10 | print(re.findall(r'[\w\d+.]+@[\w\d.]+', data, re.I)) 11 | -------------------------------------------------------------------------------- /python/remove_duplicate_letters.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | class Solution(object): 4 | def removeDuplicateLetters(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | count_map = collections.Counter(s) 10 | stack = [] 11 | for c in s: 12 | if len(stack) == 0: 13 | stack.append(c) 14 | count_map[c] -= 1 15 | elif c in stack: 16 | while ord(c) < ord(stack[-1]) and count_map[stack[-1]] > 0: 17 | stack.pop() 18 | stack.append(c) 19 | count_map[c] -= 1 20 | return ''.join(stack) 21 | 22 | 23 | if __name__ == '__main__': 24 | solution = Solution() 25 | print(solution.removeDuplicateLetters('cbacdcbc')) 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /python/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/22/17.""" 2 | 3 | """Given a sorted array, remove the duplicates in place such that each element appear only once and return the new 4 | length. 5 | Do not allocate extra space for another array, you must do this in place with constant memory. 6 | 7 | For example, 8 | Given input array nums = [1,1,2], 9 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 10 | It doesn't matter what you leave beyond the new length.""" 11 | 12 | 13 | class Solution(object): 14 | def removeDuplicates(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: int 18 | """ 19 | if len(nums) == 0: 20 | return 0 21 | curr, idx, count = nums[0], 1, 1 22 | 23 | for i, v in enumerate(nums): 24 | if v != curr: 25 | nums[idx] = v 26 | curr = v 27 | count += 1 28 | idx += 1 29 | print(nums) 30 | return count 31 | 32 | 33 | if __name__ == '__main__': 34 | solution = Solution() 35 | print(solution.removeDuplicates([1, 1, 2, 2, 2, 3])) 36 | 37 | -------------------------------------------------------------------------------- /python/remove_invalid_parahthesis.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/2/17.""" 2 | 3 | """Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. 4 | Note: The input string may contain letters other than the parentheses ( and ).""" 5 | import collections 6 | 7 | 8 | class Solution(object): 9 | def removeInvalidParentheses(self, s): 10 | """ 11 | :type s: str 12 | :rtype: List[str] 13 | """ 14 | stack = collections.deque() 15 | left, right = 0, 0 16 | result = [] 17 | for i in s: 18 | if i == '(': 19 | stack.append(i) 20 | left += 1 21 | elif i == ')': 22 | if left > 1: 23 | stack.append(i) 24 | left -= 0 25 | else: 26 | stack.append(i) 27 | 28 | 29 | if __name__ == '__main__': 30 | solution = Solution() 31 | print(solution.removeInvalidParentheses("()())()")) 32 | -------------------------------------------------------------------------------- /python/remove_outermost_parantheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeOuterParentheses(self, S: str) -> str: 3 | res = [] 4 | outer = 0 5 | for c in S: 6 | if c == '(' and outer > 0: 7 | res.append(c) 8 | outer += 1 9 | elif c == '(' and outer == 0: 10 | outer += 1 11 | elif c == ')' and outer > 1: 12 | res.append(c) 13 | outer -= 1 14 | elif c == ')' and outer <= 1: 15 | outer -= 1 16 | return ''.join(res) 17 | -------------------------------------------------------------------------------- /python/repeated_dna_sequence.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/22/17.""" 2 | """All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". 3 | When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 4 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 5 | For example, 6 | Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", 7 | 8 | Return: 9 | ["AAAAACCCCC", "CCCCCAAAAA"].""" 10 | import collections 11 | 12 | 13 | class Solution(object): 14 | def findRepeatedDnaSequences(self, s): 15 | """ 16 | :type s: str 17 | :rtype: List[str] 18 | """ 19 | if not s or len(s) < 10: 20 | return [] 21 | sequence_map = collections.Counter([s[i:i+10] for i in range(len(s))]) 22 | return [k for k, v in sequence_map.items() if v > 1] 23 | 24 | 25 | if __name__ == '__main__': 26 | solution = Solution() 27 | print(solution.findRepeatedDnaSequences("AAAAAAAAAAA")) -------------------------------------------------------------------------------- /python/repeated_substring_pattern.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 10/7/17.""" 2 | """Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies 3 | of the substring together. You may assume the given string consists of lowercase English letters only and its length 4 | will not exceed 10000.""" -------------------------------------------------------------------------------- /python/reverse_a_linked_list.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 4/12/17 as part of leetcode""" 2 | """Reverse a singly linked list.""" 3 | 4 | 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution(object): 11 | def reverseList(self, head): 12 | """ 13 | :type head: ListNode 14 | :rtype: ListNode 15 | """ 16 | if not head or not head.next: 17 | return head 18 | p = self.reverseList(head.next) 19 | head.next.next = head 20 | head.next = None 21 | return p 22 | 23 | def reverseListInteratively(self, head): 24 | prev, curr, nxt = None, None, head 25 | while head: 26 | curr = nxt 27 | nxt = nxt.next 28 | curr.next = prev 29 | prev = curr -------------------------------------------------------------------------------- /python/reverse_integer.py: -------------------------------------------------------------------------------- 1 | """Given a 32-bit signed integer, reverse digits of an integer.""" 2 | 3 | 4 | class Solution(object): 5 | def reverse(self, x): 6 | """ 7 | :type x: int 8 | :rtype: int 9 | """ 10 | 11 | if str(x)[0] == '-': 12 | res = -int(str(x)[1:][::-1]) 13 | else: 14 | res = int(str(x)[::-1]) 15 | 16 | if (-1 << 31) < res < (1 << 31): 17 | return res 18 | else: 19 | return 0 20 | 21 | 22 | if __name__ == '__main__': 23 | solution = Solution() 24 | print(solution.reverse(-123)) 25 | -------------------------------------------------------------------------------- /python/reverse_vowels_of_a_string.py: -------------------------------------------------------------------------------- 1 | """Write a function that takes a string as input and reverse only the vowels of a string.""" 2 | 3 | 4 | class Solution(object): 5 | def reverseVowels(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | if not s or len(s) == 0: 11 | return None 12 | vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']) 13 | index_list = [] 14 | vowel_list = [] 15 | for i, c in enumerate(s): 16 | if c in vowels: 17 | index_list.append(i) 18 | vowel_list.append(c) 19 | vowel_list = vowel_list[::-1] 20 | l = list(s) 21 | for i in range(len(index_list)): 22 | l[index_list[i]] = vowel_list[i] 23 | return ''.join(l) 24 | 25 | 26 | if __name__ == '__main__': 27 | solution = Solution() 28 | print(solution.reverseVowels("hello")) 29 | -------------------------------------------------------------------------------- /python/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | mapper = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} 4 | total, i = 0, 0 5 | while i < len(s): 6 | if len(s) - i >= 2 and mapper[s[i]] < mapper[s[i + 1]]: 7 | total += (mapper[s[i + 1]] - mapper[s[i]]) 8 | i += 2 9 | else: 10 | total += mapper[s[i]] 11 | i += 1 12 | return total 13 | 14 | 15 | import unittest 16 | 17 | 18 | class TestRomanToInteger(unittest.TestCase): 19 | def test_one(self): 20 | self.assertEqual(Solution().romanToInt('III'), 3) 21 | 22 | def test_two(self): 23 | self.assertEqual(Solution().romanToInt('IV'), 4) 24 | 25 | def test_three(self): 26 | self.assertEqual(Solution().romanToInt('IX'), 9) 27 | 28 | def test_four(self): 29 | self.assertEqual(Solution().romanToInt('LVIII'), 58) 30 | 31 | def test_five(self): 32 | self.assertEqual(Solution().romanToInt('MCMXCIV'), 1994) 33 | 34 | 35 | unittest.main(exit=False) 36 | -------------------------------------------------------------------------------- /python/rotate_image.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 10/2/17.""" 2 | """You are given an n x n 2D matrix representing an image. 3 | Rotate the image by 90 degrees (clockwise). 4 | Note: 5 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. 6 | DO NOT allocate another 2D matrix and do the rotation.""" 7 | 8 | 9 | class Solution(object): 10 | def rotate(self, matrix): 11 | """ 12 | :type matrix: List[List[int]] 13 | :rtype: void Do not return anything, modify matrix in-place instead. 14 | """ 15 | matrix.reverse() 16 | for i in range(len(matrix)): 17 | for j in range(i): 18 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 19 | return matrix 20 | 21 | 22 | if __name__ == '__main__': 23 | solution = Solution() 24 | print(solution.rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) 25 | -------------------------------------------------------------------------------- /python/rotting_oranges.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | def orangesRotting(self, grid: List[List[int]]) -> int: 8 | rows, cols = len(grid), len(grid[0]) 9 | fresh_count = 0 10 | queue = deque() 11 | 12 | for r in range(rows): 13 | for c in range(cols): 14 | if grid[r][c] == 2: 15 | queue.append((r, c)) 16 | elif grid[r][c] == 1: 17 | fresh_count += 1 18 | 19 | directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] 20 | minutes = 0 21 | 22 | while queue and fresh_count > 0: 23 | for _ in range(len(queue)): 24 | r, c = queue.popleft() 25 | for dr, dc in directions: 26 | nr, nc = r + dr, c + dc 27 | if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1: 28 | grid[nr][nc] = 2 29 | queue.append((nr, nc)) 30 | fresh_count -= 1 31 | minutes += 1 32 | 33 | return minutes if fresh_count == 0 else -1 -------------------------------------------------------------------------------- /python/s_from_t.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | def solution(S, T): 4 | 5 | def oneDel(self, s, t): 6 | 7 | longer = s if len(s) > len(t) else t 8 | shorter = s if longer == t else t 9 | for i in range(len(longer)): 10 | reduced = longer[:i] + longer[i + 1:] 11 | if reduced == shorter: 12 | return True 13 | return False 14 | 15 | def oneModify(self, s, t): 16 | i, count = 0, 0 17 | while i < len(s): 18 | if s[i] != t[i]: 19 | count += 1 20 | i += 1 21 | return count <= 1 22 | 23 | if abs(len(S) - len(T)) > 1: 24 | return "IMPOSSIBLE" 25 | 26 | if len(S) == len(T) and oneModify(S, T): 27 | t_map, s_map = Counter(T), Counter(S) 28 | for k, v in t_map.items(): 29 | if k not in s_map or s_map[k] != v: 30 | return "REPLACE " 31 | -------------------------------------------------------------------------------- /python/same_tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 11 | if not p and not q: 12 | return True 13 | if p and not q: 14 | return False 15 | if not p and q: 16 | return False 17 | if p and q and p.val != q.val: 18 | return False 19 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 20 | -------------------------------------------------------------------------------- /python/satisfiability_of_equations.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | 4 | class Solution: 5 | def equationsPossible(self, equations: [str]) -> bool: 6 | parent = {c: c for c in string.ascii_lowercase} 7 | 8 | def union(a, b): 9 | x = find(a) 10 | y = find(b) 11 | if x != y: 12 | parent[x] = y 13 | 14 | def find(item): 15 | if parent[item] == item: 16 | return item 17 | parent[item] = find(parent[item]) 18 | return parent[item] 19 | 20 | for equation in equations: 21 | if equation[1] == '=': 22 | union(equation[0], equation[-1]) 23 | 24 | for equation in equations: 25 | if equation[1] == '!': 26 | if find(equation[0]) == find(equation[-1]): 27 | return False 28 | 29 | return True 30 | 31 | 32 | solution = Solution() 33 | print(solution.equationsPossible(["b==a","a==b"])) -------------------------------------------------------------------------------- /python/scratch/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/python/scratch/__init__.py -------------------------------------------------------------------------------- /python/scratch/closures.py: -------------------------------------------------------------------------------- 1 | def enclosing(): 2 | x = 'closed over' 3 | 4 | def local_func(): 5 | print(x) 6 | 7 | return local_func 8 | 9 | 10 | def raise_to(exp): 11 | def raise_to_exp(x): 12 | return pow(x, exp) 13 | 14 | return raise_to_exp 15 | 16 | 17 | def escape_unicode(f): 18 | def wrap(args): 19 | x = f(args) 20 | return ascii(x) 21 | 22 | return wrap 23 | 24 | 25 | square = raise_to(2) 26 | print(square(4)) 27 | 28 | lf = enclosing() 29 | lf() 30 | print(lf.__closure__) 31 | -------------------------------------------------------------------------------- /python/scratch/dominos.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def longestMatchingGroup(S): 4 | tile_list = S.split(',') 5 | max_count, curr_count = 1, 1 6 | prev = tile_list[0] 7 | for i in range(1, len(tile_list)): 8 | curr = tile_list[i] 9 | if prev[2] == curr[0]: 10 | curr_count += 1 11 | else: 12 | max_count = max(max_count, curr_count) 13 | curr_count = 1 14 | prev = curr 15 | max_count = max(curr_count, max_count) 16 | return max_count 17 | 18 | 19 | print(longestMatchingGroup("6-3")) 20 | print(longestMatchingGroup("1-2,1-2")) 21 | print(longestMatchingGroup("1-1,3-5,5-2,2-3,2-4")) 22 | print(longestMatchingGroup("5-5,5-5,4-4,5-5,5-5,5-5,5-5,5-5,5-5,5-5")) 23 | print(longestMatchingGroup("1-1,3-5,5-5,5-4,4-2,1-3")) 24 | print(longestMatchingGroup("1-2,2-2,3-3,3-4,4-5,1-1,1-2")) 25 | 26 | 27 | -------------------------------------------------------------------------------- /python/scratch/higher_order_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python support the concept of higher order functions, what that means is that you can define a function inside 3 | another function. The most common use of this is helper functions. Here's an example of a classic use case - sorting 4 | using an enclosed function and one using an anonymous lambda. 5 | """ 6 | 7 | 8 | def sort_by_last_letter(arr): 9 | def last_letter(s): 10 | return s[-1] 11 | 12 | return sorted(arr, key=last_letter) 13 | 14 | 15 | def sort_by_last_letter_lambda(arr): 16 | return sorted(arr, key=lambda s: s[-1]) 17 | 18 | 19 | if __name__ == '__main__': 20 | print(sort_by_last_letter_lambda(['penguin', 'octopus', 'rhino'])) 21 | -------------------------------------------------------------------------------- /python/set_mismatch.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/6/17.""" 2 | """The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers 3 | in the set got duplicated to another number in the set, which results in repetition of one number and loss of another 4 | number. 5 | 6 | Given an array nums representing the data status of this set after the error. Your task is to firstly find the number 7 | occurs twice and then find the number that is missing. Return them in the form of an array.""" 8 | import collections 9 | 10 | 11 | class Solution(object): 12 | def findErrorNums(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: List[int] 16 | """ 17 | index_map = {i+1: 0 for i in range(len(nums))} 18 | duplicate, missing = -1, -1 19 | for item in nums: 20 | index_map[item] += 1 21 | for k, v in index_map.items(): 22 | if v == 2: 23 | duplicate = k 24 | if v == 0: 25 | missing = k 26 | 27 | return [duplicate, missing] 28 | 29 | 30 | if __name__ == '__main__': 31 | solution = Solution() 32 | print(solution.findErrorNums([1, 5, 3, 2, 2, 7, 6, 4, 8, 9])) -------------------------------------------------------------------------------- /python/single_element_in_a_soted_array.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 6/5/17.""" 2 | 3 | 4 | class Solution(object): 5 | def singleNonDuplicate(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | low, high = 0, len(nums) -1 11 | while low < high: 12 | mid = low + (high -low)/2 13 | if nums[mid] != nums[mid -1] and nums[mid] != nums[mid +1]: 14 | return nums[mid] 15 | elif nums[mid] == nums[mid-1] and mid%2 == 0: 16 | high = mid -1 17 | elif nums[mid] == nums[mid +1] and mid%2 != 0: 18 | high = mid -1 19 | else: 20 | low = mid +1 21 | 22 | return nums[low] 23 | -------------------------------------------------------------------------------- /python/sort_characters_by_frequency.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/6/17.""" 2 | """Given a string, sort it in decreasing order based on the frequency of characters. 3 | Input: 4 | "tree" 5 | 6 | Output: 7 | "eert" 8 | 9 | Explanation: 10 | 'e' appears twice while 'r' and 't' both appear once. 11 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.""" 12 | import collections 13 | 14 | 15 | class Solution(object): 16 | def frequencySort(self, s): 17 | """ 18 | :type s: str 19 | :rtype: str 20 | """ 21 | freq_map = collections.Counter(s) 22 | reverse_map = {} 23 | for k, v in freq_map.items(): 24 | reverse_map.setdefault(v, []).append(k) 25 | ordered = collections.OrderedDict(sorted(reverse_map.items(), reverse=True)) 26 | res = '' 27 | for k, v in ordered.items(): 28 | for item in v: 29 | res += self.get_k_occurences(item, k) 30 | 31 | return res 32 | 33 | def get_k_occurences(self, c, k): 34 | return ''.join([c for _ in range(k)]) 35 | 36 | if __name__ == '__main__': 37 | solution = Solution() 38 | print(solution.frequencySort('Aabb')) 39 | 40 | -------------------------------------------------------------------------------- /python/sqrt_x.py: -------------------------------------------------------------------------------- 1 | """Implement int sqrt(int x). 2 | Compute and return the square root of x.""" 3 | 4 | 5 | class Solution: 6 | def mySqrt(self, x): 7 | """ 8 | :type x: int 9 | :rtype: int 10 | """ 11 | low, high = 1, x 12 | while low < high: 13 | mid = low + (high - low) // 2 14 | if mid * mid > x: 15 | high = mid - 1 16 | elif mid * mid < x: 17 | low = mid 18 | else: 19 | return mid 20 | return low 21 | 22 | 23 | if __name__ == '__main__': 24 | solution = Solution() 25 | print(solution.mySqrt(9)) 26 | -------------------------------------------------------------------------------- /python/strobogrammatic_number.py: -------------------------------------------------------------------------------- 1 | """A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 2 | Write a function to determine if a number is strobogrammatic. The number is represented as a string.""" 3 | 4 | 5 | class Solution(object): 6 | def isStrobogrammatic(self, num): 7 | """ 8 | :type num: str 9 | :rtype: bool 10 | """ 11 | numbers = {"6": "9", "9": "6", "8": "8", "0": "0", "1": "1"} 12 | 13 | low, high = 0, len(num) - 1 14 | while low <= high: 15 | if num[low] not in numbers: 16 | return False 17 | if numbers[num[low]] != num[high]: 18 | return False 19 | low += 1 20 | high -= 1 21 | return True 22 | 23 | 24 | if __name__ == '__main__': 25 | solution = Solution() 26 | print(solution.isStrobogrammatic('2')) 27 | -------------------------------------------------------------------------------- /python/subsets.py: -------------------------------------------------------------------------------- 1 | """Given a set of distinct integers, nums, return all possible subsets (the power set).""" 2 | 3 | 4 | class Solution(object): 5 | def subsets(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[List[int]] 9 | """ 10 | prev = result = [[]] 11 | 12 | for num in nums: 13 | for p in prev: 14 | p.append(num) 15 | prev.append([num]) 16 | result.append(prev) 17 | return result 18 | 19 | 20 | if __name__ == '__main__': 21 | solution = Solution() 22 | print(solution.subsets([1, 2, 3])) 23 | -------------------------------------------------------------------------------- /python/sum_of_left_leaves.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/22/17.""" 2 | """Find the sum of all left leaves in a given binary tree.""" 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | import collections 12 | 13 | class Solution(object): 14 | def sumOfLeftLeaves(self, root): 15 | """ 16 | :type root: TreeNode 17 | :rtype: int 18 | """ 19 | if root is None: 20 | return 0 21 | count = 0 22 | 23 | if root.left: 24 | if root.left.left is None and root.left.right is None: 25 | count += root.left.val 26 | else: 27 | count += self.sumOfLeftLeaves(root.left) 28 | count += self.sumOfLeftLeaves(root.right) 29 | return count 30 | 31 | 32 | -------------------------------------------------------------------------------- /python/sum_of_root_to_leaf_binary_numbers.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def sumRootToLeaf(self, root: TreeNode) -> int: 11 | if not root: 12 | return 0 13 | result_arr = [] 14 | 15 | def dfs(node, s): 16 | if not node: 17 | return 18 | if not node.left and not node.right: 19 | s += str(node.val) 20 | result_arr.append(s) 21 | s += str(node.val) 22 | dfs(node.left, s) 23 | dfs(node.right, s) 24 | dfs(root, '') 25 | print(result_arr) 26 | return sum([int(i, 2) for i in result_arr]) 27 | 28 | 29 | solution = Solution() 30 | t = TreeNode(1) 31 | t.left = TreeNode(0) 32 | t.left.left = TreeNode(0) 33 | t.left.right = TreeNode(1) 34 | t.right = TreeNode(1) 35 | t.right.left = TreeNode(0) 36 | t.right.right = TreeNode(1) 37 | 38 | print(solution.sumRootToLeaf(t)) -------------------------------------------------------------------------------- /python/sum_of_square_numbers.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/8/17.""" 2 | """Given a non-negative integer c, your task is to decide whether there're two integers a and b 3 | such that a2 + b2 = c.""" 4 | import math 5 | 6 | 7 | class Solution(object): 8 | def judgeSquareSum(self, c): 9 | """ 10 | :type c: int 11 | :rtype: bool 12 | """ 13 | if c < 0: 14 | return False 15 | start, end = 0, round(math.sqrt(c)) 16 | while start <= end: 17 | curr = start * start + end * end 18 | if curr < c: 19 | start += 1 20 | elif curr > c: 21 | end -= 1 22 | else: 23 | return True 24 | return False 25 | 26 | 27 | if __name__ == '__main__': 28 | solution = Solution() 29 | print(solution.judgeSquareSum(25)) -------------------------------------------------------------------------------- /python/swap_nodes_in_pairs.py: -------------------------------------------------------------------------------- 1 | """Given a linked list, swap every two adjacent nodes and return its head. 2 | For example, 3 | Given 1->2->3->4, you should return the list as 2->1->4->3. 4 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.""" 5 | 6 | 7 | # Definition for singly-linked list. 8 | class ListNode: 9 | def __init__(self, x): 10 | self.val = x 11 | self.next = None 12 | 13 | 14 | class Solution: 15 | def swapPairs(self, head): 16 | """ 17 | :type head: ListNode 18 | :rtype: ListNode 19 | """ 20 | if not head or not head.next: 21 | return head 22 | 23 | prev = head 24 | curr = prev.next 25 | while prev and curr: 26 | v = prev.val 27 | prev.val = curr.val 28 | curr.val = v 29 | prev = curr.next 30 | if prev: 31 | curr = prev.next 32 | return head 33 | 34 | l = ListNode(1) 35 | l.next = ListNode(2) 36 | l.next.next = ListNode(3) 37 | l.next.next.next = ListNode(4) 38 | 39 | solution = Solution() 40 | print(solution.swapPairs(l)) -------------------------------------------------------------------------------- /python/symmetric_tree.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/9/17.""" 2 | """Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).""" 3 | 4 | 5 | # Definition for a binary tree node. 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | 13 | class Solution(object): 14 | def isSymmetric(self, root): 15 | """ 16 | :type root: TreeNode 17 | :rtype: bool 18 | """ 19 | if not root: 20 | return True 21 | 22 | def helper(left, right): 23 | if not left and not right: 24 | return True 25 | if not left and right: 26 | return False 27 | if left and not right: 28 | return False 29 | if left.val != right.val: 30 | return False 31 | return helper(left.left, right.right) and helper(left.right, right.left) 32 | 33 | return helper(root.left, root.right) 34 | -------------------------------------------------------------------------------- /python/trapping_rain_water.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/11/17.""" 2 | """Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much 3 | water it is able to trap after raining.""" 4 | import sys 5 | 6 | 7 | class Solution(object): 8 | def trap(self, height): 9 | """ 10 | :type height: List[int] 11 | :rtype: int 12 | """ 13 | 14 | left_max, right_max = [0 for _ in range(len(height))], [0 for _ in range(len(height))] 15 | left_max[0], right_max[-1] = 0, 0 16 | max_left, max_right = height[0], height[-1] 17 | for i in range(1, len(height)): 18 | max_left = max(max_left, height[i]) 19 | left_max[i] = max_left 20 | 21 | for i in range(len(height) - 2, 0, -1): 22 | max_right = max(max_right, height[i]) 23 | right_max[i] = max_right 24 | 25 | total = 0 26 | for i in range(len(height)): 27 | total += max(min(left_max[i], right_max[i]) - height[i], 0) 28 | return total 29 | 30 | 31 | if __name__ == '__main__': 32 | solution = Solution() 33 | print(solution.trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /python/two_sum.py: -------------------------------------------------------------------------------- 1 | """Given an array of integers, return indices of the two numbers such that they add up to a 2 | specific target.You may assume that each input would have exactly one solution.""" 3 | 4 | """Store the number against the index in a dict 5 | While traversing the dict if target - curr is in the dict, return the curr index and the index of target - curr """ 6 | 7 | 8 | def two_sum(nums, target): 9 | index_map = {} 10 | for i in range(len(nums)): 11 | if target - nums[i] in index_map: 12 | return i, index_map[target - nums[i]] 13 | index_map[nums[i]] = i -------------------------------------------------------------------------------- /python/two_sum_iv_input_is_a_bst.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/2/17.""" 2 | """Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that 3 | their sum is equal to the given target.""" 4 | 5 | # Definition for a binary tree node. 6 | class TreeNode(object): 7 | def __init__(self, x): 8 | self.val = x 9 | self.left = None 10 | self.right = None 11 | 12 | 13 | class Solution(object): 14 | def findTarget(self, root, k): 15 | """ 16 | :type root: TreeNode 17 | :type k: int 18 | :rtype: bool 19 | """ 20 | arr = [] 21 | self.inorder_helper(root, arr) 22 | i, j = 0, len(arr)-1 23 | while i < j: 24 | total = arr[i] + arr[j] 25 | if total > k: 26 | j -= 1 27 | elif total < k: 28 | i += 1 29 | else: 30 | return True 31 | return False 32 | 33 | def inorder_helper(self, root, arr): 34 | if not root: 35 | return 36 | self.inorder_helper(root.left, arr) 37 | arr.append(root.val) 38 | self.inorder_helper(root.right, arr) -------------------------------------------------------------------------------- /python/unique_binary_search_trees_ii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def generateTrees(self, n: int) -> list[TreeNode]: 11 | 12 | def helper(start, stop): 13 | res = [] 14 | 15 | if start > stop: 16 | res.append(None) 17 | return res 18 | if start == stop: 19 | res.append(TreeNode(start)) 20 | return res 21 | left, right = [], [] 22 | for i in range(start, stop+1): 23 | left = helper(start, i-1) 24 | right = helper(i+1, stop) 25 | 26 | for lnode in left: 27 | for rnode in right: 28 | root = TreeNode(i) 29 | root.left = lnode 30 | root.right = rnode 31 | res.append(root) 32 | return res 33 | return helper(1, n) 34 | 35 | 36 | -------------------------------------------------------------------------------- /python/valid_palindrome.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/18/17.""" 2 | 3 | """Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 4 | For example, 5 | "A man, a plan, a canal: Panama" is a palindrome. 6 | "race a car" is not a palindrome. 7 | 8 | Note: 9 | Have you consider that the string might be empty? This is a good question to ask during an interview. 10 | For the purpose of this problem, we define empty string as valid palindrome.""" 11 | import re 12 | 13 | class Solution(object): 14 | def isPalindrome(self, s): 15 | """ 16 | :type s: str 17 | :rtype: bool 18 | """ 19 | cleaned = re.sub('[^0-9a-zA-Z]', '', s) 20 | if cleaned.lower() == cleaned[::-1].lower(): 21 | return True 22 | return False 23 | 24 | 25 | if __name__ == '__main__': 26 | solution = Solution() 27 | print(solution.isPalindrome("A man, a plan, a canal: Panama")) 28 | -------------------------------------------------------------------------------- /python/valid_parantheses.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 10/2/17.""" 2 | """Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.""" 5 | 6 | 7 | class Solution(object): 8 | def isValid(self, s): 9 | """ 10 | :type s: str 11 | :rtype: bool 12 | """ 13 | 14 | def _match(c, t): 15 | if c == '(' and t == ')': 16 | return True 17 | if c == '{' and t == '}': 18 | return True 19 | if c == '[' and t == ']': 20 | return True 21 | return False 22 | 23 | stack = [] 24 | for c in s: 25 | if c == '(' or c == '{' or c == '[': 26 | stack.append(c) 27 | elif c == ')' or c == '}' or c == ']': 28 | if len(stack) > 0 and _match(stack[-1], c): 29 | stack.pop() 30 | else: 31 | return False 32 | return len(stack) == 0 33 | 34 | 35 | 36 | if __name__ == '__main__': 37 | solution = Solution() 38 | print(solution.isValid('()[]{}')) 39 | -------------------------------------------------------------------------------- /python/valid_perfect_square.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 8/5/17.""" 2 | """Given a positive integer num, write a function which returns True if num is a perfect square else False.""" 3 | 4 | 5 | # TODO: some weird error 6 | 7 | class Solution(object): 8 | def isPerfectSquare(self, num): 9 | """ 10 | :type num: int 11 | :rtype: bool 12 | """ 13 | if num < 1: 14 | return False 15 | if num == 1: 16 | return True 17 | start, end = 1, num 18 | while start < end: 19 | mid = start + (end - start) // 2 20 | if mid * mid < num: 21 | start = mid + 1 22 | elif mid * mid > num: 23 | end = mid 24 | else: 25 | return True 26 | return False 27 | 28 | 29 | 30 | if __name__ == '__main__': 31 | solution = Solution() 32 | print(solution.isPerfectSquare(104976)) 33 | -------------------------------------------------------------------------------- /python/validate_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 9/13/17.""" 2 | """Given a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | Assume a BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | """ 10 | import sys 11 | 12 | # Definition for a binary tree node. 13 | 14 | class TreeNode(object): 15 | def __init__(self, x): 16 | self.val = x 17 | self.left = None 18 | self.right = None 19 | 20 | 21 | class Solution(object): 22 | def isValidBST(self, root): 23 | """ 24 | :type root: TreeNode 25 | :rtype: bool 26 | """ 27 | def _helper(root, floor, ceiling): 28 | if not root: 29 | return True 30 | if root.val <= floor or root.val >= ceiling: 31 | return False 32 | return _helper(root.left, floor, root.val) and _helper(root.right, root.val, ceiling) 33 | 34 | return _helper(root, -sys.maxsize, sys.maxsize) 35 | -------------------------------------------------------------------------------- /python/vertical_order_traversal_of_a_binary_tree.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | 4 | # Definition for a binary tree node. 5 | class TreeNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | 12 | class Solution: 13 | def verticalTraversal(self, root: TreeNode) -> list[list[int]]: 14 | queue = deque() 15 | queue.appendleft((root, 0, 0)) 16 | dic = defaultdict(list) 17 | while len(queue) > 0: 18 | curr = queue.popleft() 19 | dic[curr[1]].append((curr[0].val, curr[2])) 20 | if curr[0].left: 21 | queue.append((curr[0].left, curr[1] - 1, curr[2] + 1)) 22 | if curr[0].right: 23 | queue.append((curr[0].right, curr[1] + 1, curr[2] + 1)) 24 | res = [] 25 | for k in sorted(dic.keys()): 26 | level = sorted(dic[k], key=lambda x: (x[1], x[0])) 27 | level = [x[0] for x in level] 28 | res.append(level) 29 | return res 30 | -------------------------------------------------------------------------------- /python/word_break.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 7/18/17.""" 2 | 3 | """Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be 4 | segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not 5 | contain duplicate words. 6 | 7 | For example, given 8 | s = "leetcode", 9 | dict = ["leet", "code"]. 10 | 11 | Return true because "leetcode" can be segmented as "leet code".""" 12 | 13 | 14 | class Solution(object): 15 | def wordBreak(self, s, wordDict): 16 | """ 17 | :type s: str 18 | :type wordDict: List[str] 19 | :rtype: bool 20 | """ 21 | memo = [False for _ in range(len(s) + 1)] 22 | memo[0] = True 23 | for i in range(1, len(s) + 1): 24 | for w in wordDict: 25 | if memo[i - len(w)] and s[i - len(w):i] == w: 26 | memo[i] = True 27 | return memo[-1] 28 | 29 | 30 | if __name__ == '__main__': 31 | solution = Solution() 32 | print(solution.wordBreak('applepieapple', ['apple', 'pie'])) 33 | -------------------------------------------------------------------------------- /python/word_pattern.py: -------------------------------------------------------------------------------- 1 | """Given a pattern and a string str, find if str follows the same pattern. 2 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. 3 | 4 | Examples: 5 | pattern = "abba", str = "dog cat cat dog" should return true. 6 | pattern = "abba", str = "dog cat cat fish" should return false. 7 | pattern = "aaaa", str = "dog cat cat dog" should return false. 8 | pattern = "abba", str = "dog dog dog dog" should return false. 9 | """ 10 | 11 | 12 | class Solution: 13 | def wordPattern(self, pattern, str): 14 | """ 15 | :type pattern: str 16 | :type str: str 17 | :rtype: bool 18 | """ 19 | arr = str.split(" ") 20 | if len(arr) != len(pattern): 21 | return False 22 | check = {pattern[0]: arr[0]} 23 | for i in range(1, len(str)): 24 | if pattern[i] == pattern[i-1]: 25 | pass 26 | 27 | -------------------------------------------------------------------------------- /python/zig_zag_conversion.py: -------------------------------------------------------------------------------- 1 | """Created by sgoswami on 3/23/17 as part of leetcode""" 2 | """The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to 3 | display this pattern in a fixed font for better legibility). 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: 'PAHNAPLSIIGYIR' 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | string convert(string text, int nRows)""" 10 | 11 | class Solution(object): 12 | def convert(self, s, numRows): 13 | """ 14 | :type s: str 15 | :type numRows: int 16 | :rtype: str 17 | """ -------------------------------------------------------------------------------- /python/zig_zag_iterator.py: -------------------------------------------------------------------------------- 1 | """ Given two 1d vectors, implement an iterator to return their elements alternately. 2 | For example, given two 1d vectors: 3 | v1 = [1, 2] 4 | v2 = [3, 4, 5, 6] 5 | By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: 6 | [1, 3, 2, 4, 5, 6]. """ 7 | 8 | class ZigzagIterator(object): 9 | 10 | def __init__(self, v1, v2): 11 | """ 12 | Initialize your data structure here. 13 | :type v1: List[int] 14 | :type v2: List[int] 15 | """ 16 | self.queue = [item for item in (v1, v2) if item] 17 | 18 | def next(self): 19 | """ 20 | :rtype: int 21 | """ 22 | v = self.queue.pop(0) 23 | ans = v.pop(0) 24 | if v: 25 | self.queue.append(v) 26 | return ans 27 | 28 | def hasNext(self): 29 | """ 30 | :rtype: bool 31 | """ 32 | return len(self.queue) > 0 33 | 34 | 35 | if __name__ == '__main__': 36 | zigzag = ZigzagIterator([1, 2], [3, 4, 5, 6]) 37 | while zigzag.hasNext(): 38 | print(zigzag.next()) 39 | -------------------------------------------------------------------------------- /sql/actors_and_directors_who_cooperated_atleast_3_times.sql: -------------------------------------------------------------------------------- 1 | SELECT actor_id, director_id 2 | FROM 3 | (SELECT actor_id, director_id, count(timestamp) AS cooperated 4 | FROM ActorDirector 5 | GROUP BY actor_id, director_id) AS temp 6 | WHERE cooperated >= 3 -------------------------------------------------------------------------------- /sql/ads_performance.sql: -------------------------------------------------------------------------------- 1 | SELECT ad_id, 2 | ROUND(IFNULL(100* SUM(clicked)/SUM(clicked_viewed), 0), 2) AS ctr 3 | FROM 4 | (SELECT 5 | *, 6 | CASE WHEN action = 'Clicked' THEN 1 ELSE 0 END AS clicked, 7 | CASE WHEN action IN ('Clicked', 'Viewed') THEN 1 ELSE 0 END AS clicked_viewed 8 | FROM Ads) AS temp 9 | GROUP BY ad_id 10 | ORDER BY ctr DESC, ad_id -------------------------------------------------------------------------------- /sql/big_countries.sql: -------------------------------------------------------------------------------- 1 | SELECT name, population, area 2 | FROM World 3 | WHERE area >= 3000000 4 | OR population > 25000000 5 | -------------------------------------------------------------------------------- /sql/biggest_single_number.sql: -------------------------------------------------------------------------------- 1 | SELECT MAX(num) AS num 2 | FROM 3 | (SELECT num, count(num) AS occurence 4 | FROM my_numbers 5 | GROUP BY num) AS P 6 | WHERE p.occurence = 1 7 | -------------------------------------------------------------------------------- /sql/combine_two_tables.sql: -------------------------------------------------------------------------------- 1 | SELECT FirstName, LastName, City, State 2 | FROM Person p 3 | LEFT JOIN Address a 4 | ON p.personId = a.personId -------------------------------------------------------------------------------- /sql/consecutive_numbers.sql: -------------------------------------------------------------------------------- 1 | WITH temp AS (SELECT num, lead(num, 1) over(order by id ) as next1, lead(num, 2) over(order by id) as next2 from Logs) 2 | 3 | SELECT DISTINCT(num) as ConsecutiveNums 4 | FROM temp 5 | WHERE num = next1 and num = next2 -------------------------------------------------------------------------------- /sql/customers_who_bought_all_products.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soumasish/leetcodely/0c0eff14a444ed5aba3eba4269b5d14721b3dfae/sql/customers_who_bought_all_products.sql -------------------------------------------------------------------------------- /sql/customers_who_never_order.sql: -------------------------------------------------------------------------------- 1 | SELECT Name AS Customers 2 | FROM 3 | (SELECT name, count(o.Id) AS num_orders 4 | FROM Customers c 5 | LEFT JOIN Orders o 6 | ON c.Id = o.CustomerId 7 | GROUP BY c.name) AS x 8 | WHERE num_orders = 0 -------------------------------------------------------------------------------- /sql/delete_duplicate_emails.sql: -------------------------------------------------------------------------------- 1 | DELETE 2 | FROM Person WHERE Id NOT IN 3 | (SELECT * 4 | FROM( 5 | SELECT MIN(Id) 6 | FROM Person 7 | GROUP BY Email) as temp; -------------------------------------------------------------------------------- /sql/duplicate_emails.sql: -------------------------------------------------------------------------------- 1 | SELECT Email 2 | FROM 3 | (SELECT Email, count(Id) AS count 4 | FROM Person 5 | GROUP BY Email) AS temp 6 | WHERE count > 1 -------------------------------------------------------------------------------- /sql/employees_earning_more_than_their_managers.sql: -------------------------------------------------------------------------------- 1 | SELECT Name AS Employee 2 | FROM 3 | (SELECT a.Name, a.Salary, b.Salary AS manager_salary 4 | FROM Employee a 5 | JOIN Employee b 6 | ON a.ManagerId = b.Id) AS temp 7 | WHERE salary > manager_salary -------------------------------------------------------------------------------- /sql/find_start_and_end_number_of_continuous_ranges.sql: -------------------------------------------------------------------------------- 1 | with temp as ( 2 | select log_id, log_id - dense_rank() over (order by log_id) rnk 3 | from Logs 4 | ) 5 | -------------------------------------------------------------------------------- /sql/find_team_size.sql: -------------------------------------------------------------------------------- 1 | with temp AS (SELECT team_id, COUNT(employee_id) AS team_size 2 | FROM Employee 3 | GROUP BY team_id) 4 | 5 | SELECT employee_id, team_size 6 | FROM Employee e 7 | INNER JOIN temp 8 | ON e.team_id = temp.team_id -------------------------------------------------------------------------------- /sql/fix_names_in_table.sql: -------------------------------------------------------------------------------- 1 | SELECT user_id, CONCAT(UPPER(SUBSTRING(name, 1, 1)), LOWER(SUBSTRING(name, 2, LENGTH(name)-1))) as name 2 | FROM Users -------------------------------------------------------------------------------- /sql/friend_requests_i.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | COALESCE( 3 | ROUND( 4 | (SELECT COUNT(DISTINCT requester_id, accepter_id) FROM RequestAccepted)/ 5 | (SELECT COUNT(DISTINCT sender_id, send_to_id) FROM FriendRequest) 6 | ,2) 7 | ,0) 8 | AS accept_rate -------------------------------------------------------------------------------- /sql/game_plan_analysis_iii.sql: -------------------------------------------------------------------------------- 1 | SELECT player_id, event_date, SUM(games_played) OVER(PARTITION BY player_id ORDER BY event_date) AS games_played_so_far 2 | FROM Activity -------------------------------------------------------------------------------- /sql/game_plan_analysis_iv.sql: -------------------------------------------------------------------------------- 1 | SELECT COUNT(player_id) 2 | SElECT player_id, 3 | CASE WHEN datediff(event_date, next_event_date) <= 1 THEN 1 ELSE 0 AS valid_candidate 4 | FROM 5 | (SELECT player_id, 6 | event_date, 7 | lead(event_date) over(parition by player_id order by event_date) next_event_date 8 | FROM Activity) -------------------------------------------------------------------------------- /sql/game_play_analysis_i.sql: -------------------------------------------------------------------------------- 1 | SELECT player_id, MIN(event_date) AS first_login 2 | FROM Activity 3 | GROUP BY player_id; -------------------------------------------------------------------------------- /sql/game_play_analysis_ii.sql: -------------------------------------------------------------------------------- 1 | SELECT player_id, device_id 2 | FROM 3 | (SELECT player_id, MIN(device_id) AS device_id, MIN(event_date) 4 | FROM Activity 5 | GROUP BY player_id) AS temp -------------------------------------------------------------------------------- /sql/highest_grade_for_each_student.sql: -------------------------------------------------------------------------------- 1 | SELECT student_id, MIN(course_id) AS course_id, grade 2 | FROM Enrollments 3 | WHERE (student_id, grade) IN 4 | (SELECT student_id, MAX(grade) 5 | FROM Enrollments 6 | GROUP BY student_id) 7 | GROUP BY student_id 8 | ORDER By student_id; 9 | -------------------------------------------------------------------------------- /sql/nth_highest_salary.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | RETURN( 4 | WITH temp AS( 5 | SELECT Id, Salary, DENSE_RANK() OVER(ORDER BY Salary DESC) AS rk 6 | FROM Employee 7 | ) 8 | SELECT CASE WHEN N <= MAX(rk) THEN Salary ELSE NULL END 9 | FROM temp 10 | WHERE rk = N 11 | ); 12 | END -------------------------------------------------------------------------------- /sql/number_of_comments_per_post.sql: -------------------------------------------------------------------------------- 1 | SELECT post_id, count(DISTINCT post_id, sub_id) AS 'number_of_comments' FROM 2 | (SELECT DISTINCT sub_id as post_id 3 | FROM Submissions 4 | WHERE parent_id is NULL) As T 5 | LEFT JOIN Submissions AS s 6 | ON T.post_id = s.parent_id 7 | GROUP BY post_id; -------------------------------------------------------------------------------- /sql/project_employees_i.sql: -------------------------------------------------------------------------------- 1 | SELECT p.project_id, ROUND(AVG(experience_years), 2) as average_years 2 | FROM Project as p 3 | INNER JOIN Employee as e 4 | ON p.employee_id = e.employee_id 5 | GROUP BY p.project_id; -------------------------------------------------------------------------------- /sql/recyclable_and_low_fat_products.sql: -------------------------------------------------------------------------------- 1 | SELECT product_id 2 | FROM Products 3 | WHERE low_fats = 'Y' AND recyclable = 'Y' -------------------------------------------------------------------------------- /sql/rising_temperature.sql: -------------------------------------------------------------------------------- 1 | SELECT Id FROM 2 | (SELECT w1.Id, w1.Temperature, w2.Temperature AS PreviousTemperature 3 | FROM Weather as w1 4 | JOIN Weather as W2 5 | ON DATEDIFF(w1.RecordDate, w2.RecordDate) = 1) 6 | as T 7 | WHERE T.Temperature> T.PreviousTemperature; -------------------------------------------------------------------------------- /sql/second_highest_salary.sql: -------------------------------------------------------------------------------- 1 | SELECT MAX(Salary) AS SecondHighestSalary 2 | FROM Employee 3 | WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee) -------------------------------------------------------------------------------- /sql/winning_candidate.sql: -------------------------------------------------------------------------------- 1 | WITH temp AS 2 | (SELECT CandidateId, COUNT(*) AS votes 3 | FROM Vote 4 | GROUP BY CandidateId 5 | ) 6 | SELECT Name 7 | FROM Candidate 8 | LEFT JOIN temp 9 | ON Candidate.Id = temp.CandidateId 10 | ORDER BY votes DESC LIMIT 1 --------------------------------------------------------------------------------